﻿//Author:   rebecca.mccay
//Created:  11/16/2009 10:41:41 AM

var Locator = {
    InitialZoom: 4,
    InitialCentre: new MapDS.LatLng(-28, 135),
    InitialNzCentre: new MapDS.LatLng(-41, 174),
    InitialNzZoom: 5,
    PoiSearchBuffer: 200000, // metres from the location.
    PoiSearchRecordLimit: 5, // max number of POIs to find.
    country: "AU",
    LastLocatorSearchType: "none",
    tripStartAddress: "",
    currPolyline: null,
    prevPolyline: null,

    Strings: {
        InvalidSearch: 'Please enter a Town/Suburb or Postcode.',
        InvalidService: 'Please select a service.',
        InvalidTripSearch: 'Please enter both a start and end location.',
        InvalidSuburb: 'The value of Suburb is not valid.',
        InvalidPostcode: 'The value of Postcode is not valid.',
        MultipleAddressDialogTitle: 'Multiple Address Matches Found.',
        MultipleAddressPrompt: 'Choose an address:',
        NoLocations: 'There are no Locations in this map area. Please broaden your search by: <ul><li>Select fewer filters</li><li>Zoom out<li><li>Try a new search area</li></ul>',
        Searching: 'Searching...'
    },

    Images: {
        Loading: './images/loading-circle-black.gif'
    },

    ElementIDs: {
        Map: 'map',
        //Error Messages
        MultipleAddressDialog: 'multipleAddressDialog',
        MultipleAddresses: 'ddlMultipleAddresses',
        ExceptionDialog: 'exceptionDialog',
        NoResultDialog: 'noLocationsFound',
        TripSearchHidden: 'tripSearchHidden',

        //Search Elements
        Search: 'search',
        SearchStreet: 'txtStreet',
        SearchSuburb: 'txtSuburb',
        SearchState: 'ddlState',
        SearchService: 'ddlService',
        SearchNzService: 'ddlNzService',
        SearchDistance: 'ddlDistance',
        SearchPostcode: 'txtPostcode',
        SearchButton: 'btnSearch',
        ResetButton: 'btnReset',
        ResetTripButton: 'btnResetTrip',

        //Trip/ Drving Directions Elements
        TripSearchButton: 'btnGetDirections',
        DirectionsButton: 'btnDirections',
        DrivingDirectionsList: 'drivingDirectionsList',
        TripDirectionsList: 'tripPlannerList',
        TripSearch: 'tripPlanner',
        TripFieldList: 'tripPlanner',
        TxtTripSuburb: 'txtTripSuburb',
        TxtTripStreet: 'txtTripStreet',
        HideInputs: 'hideinputs',
        ShowInputs: 'showinputs',
        ShowStreet1: 'showStreet1',
        ShowStreet2: 'showStreet2',
        RemoveField1: 'removeField1',
        RemoveField2: 'removeField2',
        TripFieldsInputs: 'tripFieldsInputs',
        StartTitle: 'startTitle',
        EndTitle: 'endTitle',

        //POIs/Filter Elements
        POIsButton: 'btnPointsOfInterest',
        LocatorButton: 'btnLocator',
        TripplannerButton: 'btnTripplanner',
        ResultsButton: 'ResultButtons',
        panel2: 'panel2',
        POIsList: 'pointsOfInterestList',
        POIsFound: 'pointsOfInterestFound',
        FiltersButton: 'btnFilters',
        FiltersList: 'filtersList',
        LocationID: 'locationID',
        FeaturesSearchType: 'featuresSearchType',
        PrintLink: 'print_link',
        MaxResults: 'maxResults'
    },

    toggleHidden: function() {
        $('.hideable').toggle();

    },

    /// Reset the search fields back to default values.
    /// Here we set the textfields to the value in the title attribute and then call the blur method to
    /// trigger jQuery hint code.
    resetSearchFields: function() {

        $(this.getElementID(this.ElementIDs.Search) + ' input[title!=""]').attr("value", "").blur();
        $(this.getElementID(this.ElementIDs.Search) + ' input[type="checkbox"]').attr("checked", "");
        $(this.getElementID(this.ElementIDs.SearchState)).attr("selectedIndex", 0);
        $(this.getElementID(this.ElementIDs.SearchService)).attr("selectedIndex", 0);
        $(this.getElementID(this.ElementIDs.SearchNzService)).attr("selectedIndex", 0);
        $(this.getElementID(this.ElementIDs.SearchDistance)).attr("selectedIndex", 1);
        this.toggleDropdown(0);
    },

    /// Reset the trip search fields back to default values.
    /// Here we set the textfields to the value in the title attribute and then call the blur method to
    /// trigger jQuery hint code.
    resetTripSearchFields: function() {
        this.removeExtraFields(2);
        $(this.getElementID(this.ElementIDs.TxtTripStreet) + 1).hide();
        $(this.getElementID(this.ElementIDs.TxtTripStreet) + 2).hide();
        $(this.getElementID(this.ElementIDs.TripFieldsInputs) + ' input:text[title!=""]').hint();
        $(this.getElementID(this.ElementIDs.TripFieldsInputs) + ' input[title!=""]').attr("value", "").blur();
        $(this.getElementID(this.ElementIDs.TripFieldsInputs) + ' input:text[title!=""]').attr("value", "").blur();
        $(this.getElementID(this.ElementIDs.TripFieldsInputs) + ' input:hidden[title!=""]').attr("value", "").blur();
        this.removeExtraFields();
        this.toggleDropdown(3);
        $(this.getElementID(this.ElementIDs.TripDirectionsList)).hide();
        $(this.getElementID(this.ElementIDs.FiltersList)).show();
        $(this.getElementID(this.ElementIDs.FiltersButton)).addClass("menu-open");
        $(this.getElementID(this.ElementIDs.POIsButton)).removeClass("menu-open");
        $(this.getElementID(this.ElementIDs.DirectionsButton)).removeClass("menu-open");
        $('#fuelLoc').attr('checked', true);
    },

    //Remove the all fields except for the orignal two on the page. 
    removeExtraFields: function() {
        var _SELF = this;
        var jFilesContainer = $("#" + _SELF.ElementIDs.TripFieldsInputs);
        var intNewFileCount = (jFilesContainer.find("div.row").length);
        var i = 1;
        while (i <= intNewFileCount) {
            if (i > 2) {
                addFields.removeField(3);
            }
            i++;
        }
    },

    /// This method is used to validate the search fields. The following function has code
    /// to perform validation on the standard address fields. Use it as a guide for your
    /// custom search fields.
    validateSearchFields: function() {
        var haveValidSuburb = false;
        var haveValidPostcode = false;
        var txtSuburb = $(this.getElementID(this.ElementIDs.SearchSuburb));
        var txtPostcode = $(this.getElementID(this.ElementIDs.SearchPostcode));

        if (Locator.country == 'AU') {
            var serviceType = $(this.getElementID(this.ElementIDs.SearchService)).val();
        }
        else {
            var serviceNzType = $(this.getElementID(this.ElementIDs.SearchNzService)).val();
        }

        if (serviceType == "none") {
            this.displayException(this.Strings.InvalidService);
            return false;
        }

        if (txtSuburb.attr("value") != '' && txtSuburb.attr("value").toLowerCase() != txtSuburb.attr("title").toLowerCase()) {
            haveValidSuburb = true;
        }

        if (!haveValidSuburb && !haveValidPostcode) {
            this.displayException(this.Strings.InvalidSearch);
            return false;
        }
        return true;
    },

    /// This method is used to validate the trip fields. The following function has code
    /// to perform validation on the standard address fields. Use it as a guide for your
    /// custom search fields.
    validateTripFields: function() {
        var _SELF = this;
        var validSuburbNo = 0;
        var suburbValue = '';
        var streetValue = '';

        //Validate trip inputs to ensure at least two locations have been entered. 
        // The ids for these locations are then placed in an array for reference later in the application this will allow users to leave fields blank between entered fields
        $('input:text[name=txtTripSuburb]').each(function(i) {

            if (this.value != '' && this.value.toLowerCase() != this.title.toLowerCase()) {
                validSuburbNo = validSuburbNo + 1;
                haveValidSuburb = true;
                sid = i + 1;
                _SELF._tripAddress.push(sid);
            }
        });

        // Show error if there are not enough valid locations
        if (validSuburbNo < 2) {
            _SELF.displayException(_SELF.Strings.InvalidTripSearch);
            return false;
        }
        return true;
    },

    /// Builds a MapDS.Address representation of the Search address to be geocoded.
    /// This method is automatically called if autocomplete has not been used.
    buildAddressSearch: function() {
        //   if (this.DebugMode) { Logger.info('buildAddressSearch'); }

        // load street information
        var txtStreet = $(this.getElementID(this.ElementIDs.SearchStreet));
        var street = txtStreet.attr("value");
        street = '';

        // load suburb information
        var txtSuburb = $(this.getElementID(this.ElementIDs.SearchSuburb));
        var suburb = txtSuburb.attr("value");
        if (txtSuburb.attr("value").toLowerCase() == txtSuburb.attr("title").toLowerCase()) {
            suburb = '';
        }

        // load postcode information
        var txtPostcode = $(this.getElementID(this.ElementIDs.SearchPostcode));
        var postcode = txtPostcode.attr("value");
        if (txtPostcode.attr("value").toLowerCase() == txtPostcode.attr("title").toLowerCase()) {
            postcode = '';
        }

        // load selected state value
        var state = '';
        var ddlState = $(this.getElementID(this.ElementIDs.SearchState));
        if (ddlState.attr("selectedIndex") != 0) {
            state = ddlState.attr("value");
        }

        var autoComplete = autoCompleteFunction.checkAutoComplete(txtSuburb);
        if (autoComplete) {
            suburb = autoComplete.Locality;
            postcode = autoComplete.PostCode;
            state = autoComplete.Region;
        }

        //return address
        var address = new MapDS.Address(street, suburb, postcode, null, state, Locator.country);
        return address;
    },

    /// Builds a MapDS.Address representation of the Trip address to be geocoded.
    /// This method is automatically called if autocomplete has not been used.
    buildTripAddressSearch: function(ID) {

        var _SELF = this;
        // load street information
        var txtStreet = $(this.getElementID(this.ElementIDs.TxtTripStreet) + ID);
        var street = $(this.getElementID(this.ElementIDs.TxtTripStreet) + ID).val();
        if (street != '' && street.toLowerCase() == txtStreet.attr("title").toLowerCase()) {
            street = '';
        }

        // load suburb information
        var txtSuburb = $(this.getElementID(this.ElementIDs.TxtTripSuburb) + ID);
        var suburb = $(this.getElementID(this.ElementIDs.TxtTripSuburb) + ID).val();

        if ($(this.getElementID(this.ElementIDs.TxtTripSuburb) + ID).val().toLowerCase() == txtSuburb.attr("title").toLowerCase()) {
            suburb = '';
        }

        var autoComplete = autoCompleteFunction.checkAutoComplete(txtSuburb);
        if (autoComplete) {
            suburb = autoComplete.Locality;
            postcode = autoComplete.PostCode;
            state = autoComplete.Region;
        }

        var address = new MapDS.Address(street, suburb, null, null, null, Locator.country);
        return address;
    },

    /// Builds a string representation of the search filters available.
    /// MUST return either an object or null. Last line should always be "return null;"
    /// instead of removing, return your object before this line.
    getSearchFiltersString: function() {
        Logger.log ("Filters");
        var filterString = "";
        var filterStringAND = "";
        var filtersAND = [];
        var filters = [];
        
        $.each($(this.getElementID(this.ElementIDs.FiltersList) + ' input:checkbox'), function(i, checkbox) {
            if (!checkbox.checked) { return; }
            
            // here we replace " with \" so that the features service can use it.
            //var filter = checkbox.value.replace('"', '\"');
            var filter = checkbox.value;
            
            Logger.log(filter);
            if (filter == 'Independent') {
                if (checkbox.name.match('1')){
                filters.push('{0} = 1 OR Woolworths = 1'.format(filter));
                }else{
                filtersAND.push('{0} = 1 OR Woolworths = 1'.format(filter));
                }
            }
            else if (filter == 'AutoElec') {
                 if (checkbox.name.match('1')){
                    filters.push('{0} = 1 OR Category_Code = \"Auto electrical\"'.format(filter));
                 }else{   
                   filtersAND.push('{0} = 1 OR Category_Code = \"Auto electrical\"'.format(filter));
                }
            }
            else if (filter == 'Batteries') {
                 if (checkbox.name.match('1')){
                    filters.push('{0} = 1 OR MarshallBatteries = 1'.format(filter));
                }else{
                    filtersAND.push('{0} = 1 OR MarshallBatteries = 1'.format(filter));
                }       
            }
            else if (filter == 'ScheduledService') {
                if (checkbox.name.match('1')){
                    filters.push('ScheduledService = 1'.format(filter));
                }else{
                    filtersAND.push('ScheduledService = 1'.format(filter));
                }      
            }
            else if (filter == 'Repairs' || filter == 'Maintenance') {
                if (checkbox.name.match('1')){
                    filters.push('Category_Code = \"Trucks\"'.format(filter));
                }else{
                    filtersAND.push('Category_Code = \"Trucks\"'.format(filter));
                }       
            }
            else if (filter == 'ScheduledServiceTrucks') {
                if (checkbox.name.match('1')){
                    filters.push('Category_Code = \"Trucks\" AND ScheduledService = 1'.format(filter));
                }else{
                    filtersAND.push('Category_Code = \"Trucks\" AND ScheduledService = 1'.format(filter));
                }       
            }
            else if (filter == 'Tyres' && Locator.country == 'AU') {
                if (checkbox.name.match('1')){
                    filters.push('Category_Code = \"Tyres\" OR KmartTyreAuto = 1'.format(filter));
                }else{
                    filtersAND.push('Category_Code = \"Tyres\" OR KmartTyreAuto = 1'.format(filter));
                }      
            }
            else if (filter == 'Windscreens' && Locator.country == 'NZ') {
                if (checkbox.name.match('1')){
                    filters.push('Category_Code = \"Windscreens\" OR Windscreens = 1'.format(filter));
                }else{
                    filtersAND.push('Category_Code = \"Windscreens\" OR Windscreens = 1'.format(filter));
                }       
            }
            else if (filter == 'Windscreens' && Locator.country == 'AU') {
                if (checkbox.name.match('1')){
                    filters.push('Category_Code = \"Windscreens\"'.format(filter));
                }else{
                    filtersAND.push('Category_Code = \"Windscreens\"'.format(filter));
                }      
            }
            else if (filter == 'Tyres' && Locator.country == 'NZ') {
                if (checkbox.name.match('1')){
                    filters.push('Category_Code = \"Tyres\" OR Tyres = 1'.format(filter));
                }else{
                    filtersAND.push('Category_Code = \"Tyres\" OR Tyres = 1'.format(filter));
                }     
            }
            else {
                if (checkbox.name.match('1')){
                    filters.push('{0} = 1'.format(filter));
                    Logger.log(filter);
                }else{
                     filtersAND.push('{0} = 1'.format(filter));
                     Logger.log(filter);
                }     
                
            }
        });

        
        if (filters.length > 0) {
            filterString = filters.join(" OR ");
        }
        
        Logger.log (filterString);
        if (filtersAND.length > 0) {
            filterStringAND = filtersAND.join(" OR ");
        }
        
        if (filterString !="" && filterStringAND != ""){
            filterString = "(" + filterString + ") AND (" + filterStringAND + ")";
        } else if (filterStringAND !=""){
            filterString = filterStringAND;
        }

        if (filterString == "") {

            //get main filter from dropdown
            var selectedFilterType = "none";
            if (Locator.country == "AU") {
                selectedFilterType = $("#ddlService").val();
            } else {
                selectedFilterType = $("#ddlNzService").val();
            }

            var filterString = filterString + 'Category_Code = \"{0}\"'.format(selectedFilterType);

            if (selectedFilterType == 'Tyres' && Locator.country == "AU") {
                filterString = filterString + ' OR MarshallBatteries=1 OR Category_Code=\"Windscreens\" OR Windowtinting = 1 OR KmartTyreAuto = 1';
            }
            if (selectedFilterType == 'Tyres' && Locator.country == "NZ") {
                filterString = filterString + ' OR MarshallBatteries=1 OR Category_Code=\"Windscreens\" OR Windowtinting = 1 OR Tyres = 1';
            }
            if (selectedFilterType == 'Car wash' && Locator.country == "NZ") {
                filterString = filterString + ' OR Carwash = 1';
            }
        }

        filterString = "[(" + filterString + ")]";
        return filterString;
    },


    // Set the map centre/ zoom level
    setMapCentre: function(lat, lng) {
        this.map.setCentre(new MapDS.LatLng(lat, lng), 16);
    },


    /// This method is called from within findNearest. The purpose of this function is to allow
    /// for control of how the marker is created and how the extra POI information is displayed.
    processPOI: function(id, poi) {
        //if (this.DebugMode) { Logger.debug(poi); }
        var _SELF = this;
        poi.position = new MapDS.LatLng(Number(poi.geometry.coordinates[1]), Number(poi.geometry.coordinates[0]));

        //do this if tripplanner only
        var icn = "";
        if ($(this.getElementID(this.ElementIDs.TripplannerButton)).is('.menu-open')) {
            icn = _SELF.getSecondPoiIcon(id);
        }
        else {
            icn = _SELF.getMainPoiIcon(id);

        }

        var mkr = new MapDS.Maps.Marker(poi.position, { icon: icn });

        var serviceType = "";
        if (Locator.country == 'NZ') {
            serviceType = $(this.getElementID(this.ElementIDs.SearchNzService)).val();
        }
        else {
            serviceType = $(this.getElementID(this.ElementIDs.SearchService)).val();
        }

        var servicesList = "";
        if (serviceType == "Service station") {

            servicesList = '{0}{1}{2}{3}{4}{5}{6}{7}'.format(((poi.properties.Unleaded != '0' && !_SELF.isUndefined(poi.properties.Unleaded)) ? 'Unleaded, ' : ''),
             ((poi.properties.PremiumUnleaded != '0' && !_SELF.isUndefined(poi.properties.PremiumUnleaded)) ? 'Premium Unleaded, ' : ''),
             ((poi.properties.Diesel != '0' && !_SELF.isUndefined(poi.properties.Diesel)) ? 'Diesel, ' : ''),
             ((poi.properties.Autogas != '0' && !_SELF.isUndefined(poi.properties.Autogas)) ? 'LPG, ' : ''),
             ((poi.properties.CarWash != '0' && !_SELF.isUndefined(poi.properties.CarWash)) ? 'Car Wash, ' : ''),
             ((poi.properties.Detailing != '0' && !_SELF.isUndefined(poi.properties.Detailing)) ? 'Detailing, ' : ''),
             ((poi.properties.Superdiesel != '0' && !_SELF.isUndefined(poi.properties.SuperDiesel)) ? 'Bio Diesel, ' : ''),
             ((poi.properties.Restaurant != '0' && !_SELF.isUndefined(poi.properties.Restaurant)) ? 'Cafe/Food, ' : '')
             );
        }

        else if (serviceType == "Smash repairs") {
            servicesList = '{0}'.format(((poi.properties.AccMmentPre != '0' && !_SELF.isUndefined(poi.properties.AccMmentPre)) ? 'Accident Management, ' : '')
     );

        }
        else if (serviceType == "Repairs") {
            servicesList = '{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}'.format(((poi.properties.AlarmRadioAirCon != '0' && !_SELF.isUndefined(poi.properties.AlarmRadioAirCon)) ? 'Alarm,Radio & Air Conditioning, ' : ''),
             ((poi.properties.AutoElec != '0' && !_SELF.isUndefined(poi.properties.AutoElec)) ? 'Auto Electrical, ' : ''),
             ((poi.properties.AutoTrans != '0' && !_SELF.isUndefined(poi.properties.AutoTrans)) ? 'Auto Transmissions, ' : ''),
             ((poi.properties.Batteries != '0' && !_SELF.isUndefined(poi.properties.Batteries)) ? 'Batteries, ' : ''),
             ((poi.properties.BrakeClutch != '0' && !_SELF.isUndefined(poi.properties.BrakeClutch)) ? 'Brake &amp; Clutch, ' : ''),
             ((poi.properties.Exhaust != '0' && !_SELF.isUndefined(poi.properties.Exhaust)) ? 'Exhaust, ' : ''),
             ((poi.properties.LPGFittingMaintenance != '0' && !_SELF.isUndefined(poi.properties.LPGFittingMaintenance)) ? 'LPG fitting & maintenance, ' : ''),
             ((poi.properties.MobileService != '0' && !_SELF.isUndefined(poi.properties.MobileService)) ? 'Mobile service, ' : ''),
             ((poi.properties.RadiatorRepairs != '0' && !_SELF.isUndefined(poi.properties.RadiatorRepairs)) ? 'Radiator repairs, ' : ''),
             ((poi.properties.Windowtinting != '0' && !_SELF.isUndefined(poi.properties.Windowtinting)) ? 'Window tinting, ' : ''),
             ((poi.properties.Towing != '0' && !_SELF.isUndefined(poi.properties.Towing)) ? 'Towing, ' : '')
             );
        }
        else if (serviceType == "Motor dealership") {

            servicesList = '{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}{16}{17}{18}{19}{20}{21}{22}{23}{24}{25}{26}{27}{28}{29}{30}{31}{32}{33}{34}{35}{36}{37}{38}{39}{40}{41}'.format(((poi.properties.Ford != '0' && !_SELF.isUndefined(poi.properties.Ford)) ? 'Ford, ' : ''),
         ((poi.properties.Holden != '0' && !_SELF.isUndefined(poi.properties.Holden)) ? 'Holden, ' : ''),
         ((poi.properties.Honda != '0' && !_SELF.isUndefined(poi.properties.Honda)) ? 'Honda, ' : ''),
         ((poi.properties.Hyundai != '0' && !_SELF.isUndefined(poi.properties.Hyundai)) ? 'Hyundai, ' : ''),
         ((poi.properties.Mazda != '0' && !_SELF.isUndefined(poi.properties.Mazda)) ? 'Mazda, ' : ''),
         ((poi.properties.Mitsubishi != '0' && !_SELF.isUndefined(poi.properties.Mitsubishi)) ? 'Mitsubishi, ' : ''),
         ((poi.properties.Nissan != '0' && !_SELF.isUndefined(poi.properties.Nissan)) ? 'Nissan ' : ''),
         ((poi.properties.Subaru != '0' && !_SELF.isUndefined(poi.properties.Subaru)) ? 'Subaru, ' : ''),
         ((poi.properties.Toyota != '0' && !_SELF.isUndefined(poi.properties.Toyota)) ? 'Toyota, ' : ''),
         ((poi.properties.VW != '0' && !_SELF.isUndefined(poi.properties.VW)) ? 'VW, ' : ''),
         ((poi.properties.AlfaRomeo != '0' && !_SELF.isUndefined(poi.properties.AlfaRomeo)) ? 'Alfa Romeo, ' : ''),
         ((poi.properties.Audi != '0' && !_SELF.isUndefined(poi.properties.Audi)) ? 'Audi, ' : ''),
         ((poi.properties.BMW != '0' && !_SELF.isUndefined(poi.properties.BMW)) ? 'BMW, ' : ''),
         ((poi.properties.Chrysler != '0' && !_SELF.isUndefined(poi.properties.Chrysler)) ? 'Chrysler, ' : ''),
         ((poi.properties.Citroen != '0' && !_SELF.isUndefined(poi.properties.Citroen)) ? 'Citroen, ' : ''),
         ((poi.properties.Daewoo != '0' && !_SELF.isUndefined(poi.properties.Daewoo)) ? 'Daewoo, ' : ''),
         ((poi.properties.Daihatsu != '0' && !_SELF.isUndefined(poi.properties.Daihatsu)) ? 'Daihatsu, ' : ''),
         ((poi.properties.Eunos != '0' && !_SELF.isUndefined(poi.properties.Eunos)) ? 'Eunos, ' : ''),
         ((poi.properties.Freightliner != '0' && !_SELF.isUndefined(poi.properties.Freightliner)) ? 'Freightliner, ' : ''),
         ((poi.properties.Hino != '0' && !_SELF.isUndefined(poi.properties.Hino)) ? 'Hino, ' : ''),
         ((poi.properties.International != '0' && !_SELF.isUndefined(poi.properties.International)) ? 'International, ' : ''),
         ((poi.properties.Isuzu != '0' && !_SELF.isUndefined(poi.properties.Isuzu)) ? 'Isuzu, ' : ''),
         ((poi.properties.Jaguar != '0' && !_SELF.isUndefined(poi.properties.Jaguar)) ? 'Jaguar, ' : ''),
         ((poi.properties.Kenworth != '0' && !_SELF.isUndefined(poi.properties.Kenworth)) ? 'Kenworth, ' : ''),
         ((poi.properties.Kia != '0' && !_SELF.isUndefined(poi.properties.Kia)) ? 'Kia, ' : ''),
         ((poi.properties.LandRover != '0' && !_SELF.isUndefined(poi.properties.LandRover)) ? 'Land Rover, ' : ''),
         ((poi.properties.Lexus != '0' && !_SELF.isUndefined(poi.properties.Lexus)) ? 'Lexus, ' : ''),
         ((poi.properties.Mack != '0' && !_SELF.isUndefined(poi.properties.Mack)) ? 'Mack, ' : ''),
         ((poi.properties.MercedesBenz != '0' && !_SELF.isUndefined(poi.properties.MercedesBenz)) ? 'Mercedes Benz, ' : ''),
         ((poi.properties.UDNissan != '0' && !_SELF.isUndefined(poi.properties.UDNissan)) ? 'UD Nissan, ' : ''),
         ((poi.properties.Peugeot != '0' && !_SELF.isUndefined(poi.properties.Peugeot)) ? 'Peugeot, ' : ''),
         ((poi.properties.Porsche != '0' && !_SELF.isUndefined(poi.properties.Porsche)) ? 'Porsche, ' : ''),
         ((poi.properties.Proton != '0' && !_SELF.isUndefined(poi.properties.Proton)) ? 'Proton, ' : ''),
         ((poi.properties.Renault != '0' && !_SELF.isUndefined(poi.properties.Renault)) ? 'Renault, ' : ''),
         ((poi.properties.Rover != '0' && !_SELF.isUndefined(poi.properties.Rover)) ? 'Rover, ' : ''),
         ((poi.properties.Saab != '0' && !_SELF.isUndefined(poi.properties.Saab)) ? 'Saab, ' : ''),
         ((poi.properties.Scania != '0' && !_SELF.isUndefined(poi.properties.Scania)) ? 'Scania, ' : ''),
         ((poi.properties.Seat != '0' && !_SELF.isUndefined(poi.properties.Seat)) ? 'Seat, ' : ''),
         ((poi.properties.Ssangyong != '0' && !_SELF.isUndefined(poi.properties.Ssangyong)) ? 'Ssangyong, ' : ''),
         ((poi.properties.Suzuki != '0' && !_SELF.isUndefined(poi.properties.Suzuki)) ? 'Suzuki, ' : ''),
         ((poi.properties.Volvo != '0' && !_SELF.isUndefined(poi.properties.Volvo)) ? 'Volvo, ' : ''),
         ((poi.properties.WesternStar != '0' && !_SELF.isUndefined(poi.properties.WesternStar)) ? 'Western Star, ' : '')
         );

        }
        else if (serviceType == "Tyres") {
            servicesList = '{0}{1}{2}{3}'.format(((poi.properties.Category_Code != '0' && !_SELF.isUndefined(poi.properties.Category_Code)) ? 'Tyres, ' : ''),
            ((poi.properties.Batteries != '0' && !_SELF.isUndefined(poi.properties.Batteries)) ? 'Batteries, ' : ''),
            ((poi.properties.Windscreens != '0' && !_SELF.isUndefined(poi.properties.Windscreens)) ? 'Windscreens, ' : ''),
            ((poi.properties.Windowtinting != '0' && !_SELF.isUndefined(poi.properties.Windowtinting)) ? 'Window tinting, ' : '')
            );
        }

        else if (serviceType == "Accessories") {
            servicesList = '{0}{1}{2}{3}{4}{5}{6}{7}'.format(((poi.properties.Canopy != '0' && !_SELF.isUndefined(poi.properties.Canopy)) ? 'Canopy, ' : ''),
            ((poi.properties.Fitout != '0' && !_SELF.isUndefined(poi.properties.Fitout)) ? 'Van Fitout, ' : ''),
            ((poi.properties.Signage != '0' && !_SELF.isUndefined(poi.properties.Signage)) ? 'Signage, ' : ''),
            ((poi.properties.Bluetooth != '0' && !_SELF.isUndefined(poi.properties.Bluetooth)) ? 'Bluetooth, ' : ''),
            ((poi.properties.Alloys != '0' && !_SELF.isUndefined(poi.properties.Alloys)) ? 'Alloys, ' : ''),
            ((poi.properties.Upholstry != '0' && !_SELF.isUndefined(poi.properties.Upholstry)) ? 'Upholstery Leather, ' : ''),
            ((poi.properties.Towbars != '0' && !_SELF.isUndefined(poi.properties.Towbars)) ? 'Towbars / Bullbars, ' : ''),
            ((poi.properties.Flatdecks != '0' && !_SELF.isUndefined(poi.properties.Flatdecks)) ? 'FlatDecks, ' : '')
            );
        }
        var strLen = servicesList.length;
        servicesList = servicesList.slice(0, strLen - 2);

        mkr.setPopupContent('<div class="popup-content"><h6><img src="./images/markers/' + eval(id + 1) + '.png">{0}</h6><p>{1}</p><p>{2}{3}{4}{5}</p><p>Distance:{6}</p><p>{7}</p><p>{8}</p><p><div id="servicesList"><b>Services: </b>{9}</p></div><p>{10} {11}</p></div>'.format(
            (poi.properties.DisplayName ? poi.properties.DisplayName : 'undefined'),
            ((poi.properties.Shop_Unit_No != '' && !_SELF.isUndefined(poi.properties.Shop_Unit_No)) ? poi.properties.Shop_Unit_No + ', ' : ''),
            ((poi.properties.Street != '' && !_SELF.isUndefined(poi.properties.Street)) ? poi.properties.Street + ', ' : ''),
            ((poi.properties.Suburb != '' && !_SELF.isUndefined(poi.properties.Suburb)) ? poi.properties.Suburb + ', ' : ''),
            ((poi.properties.Postcode != '' && !_SELF.isUndefined(poi.properties.Postcode)) ? poi.properties.Postcode + ', ' : ''),
            poi.properties.State,
            (poi.properties.distance ? _SELF.formatDistance(poi.properties.distance) : ''),
            ((poi.properties.Phone1 != '' && !_SELF.isUndefined(poi.properties.Phone1)) ? 'Ph: ' + poi.properties.Phone1 + ' ' : ''),
            ((poi.properties.ExternalUri != '' && poi.properties.ExternalUri != '0' && !_SELF.isUndefined(poi.properties.ExternalUri)) ? '<a href="http://' + poi.properties.ExternalUri + '" target=_blank">' + poi.properties.ExternalUri + '</a>' : ''),
              servicesList,
             (_SELF._lastSearchedLocation != null ? '<a href="#" class="directions" onclick="Locator.getDirections(' + eval(id + 1) + ');return false;">Directions</a> ' + '' : ''),
            '<a onclick="Locator.setMapCentre(' + poi.position.Latitude() + ',' + poi.position.Longitude() + ');"> Zoom in</a>'
        ));
        return mkr;
    },

    /// called automatically this method is used to build the POI item that appears in the results list. 
    /// the appropriate marker number is passed into the method.
    /// this method returns a jQuery object, which is the LI for the list.
    processPOIForResultsList: function(poi, id) {
        var _SELF = this; // maintain scope 
        icnID = id + 1;
        var listPoi = $('<li/>').css(
                    'background', 'url(./images/markers/{0}.png) no-repeat 3px 3px'.format(icnID)
                ).html(
                    '<h6>{0}</h6><p>{1}{2}{3}{4}{5}</p><p>Distance:{7}</p><p><a href="javascript:Locator.getDirections({8});" class=\"dir\">Directions</a></p>'.format(
                         (poi.properties.DisplayName ? poi.properties.DisplayName : 'undefined'),
                        ((poi.properties.Shop_Unit_No != '' && !_SELF.isUndefined(poi.properties.Shop_Unit_No)) ? poi.properties.Shop_Unit_No + ', ' : ''),
                        ((poi.properties.Street != '' && !_SELF.isUndefined(poi.properties.Street)) ? poi.properties.Street + ', ' : ''),
                        ((poi.properties.Suburb != '' && !_SELF.isUndefined(poi.properties.Suburb)) ? poi.properties.Suburb + ', ' : ''),
                         ((poi.properties.Postcode != '' && !_SELF.isUndefined(poi.properties.Postcode)) ? poi.properties.Postcode + ', ' : ''),
                        poi.properties.State,
                        ((poi.properties.Phone1 != '' && !_SELF.isUndefined(poi.properties.Phone1)) ? '<b>Phone:</b> ' + poi.properties.Phone1 + ' ' : ''),
                          (poi.properties.distance ? _SELF.formatDistance(poi.properties.distance) : ''),
                          icnID
                     )
                ).click(function() { poi.Marker.showPopup(); _SELF.map.setCentre(poi.Marker.getPoint(), _SELF.map.getZoom()); });
        return listPoi;
    },

    /// called automatically this method is used to return a red icon for use with a marker.
    getMainPoiIcon: function(i) {
        var size = new MapDS.Size(22, 36);
        var offset = new MapDS.Pixel(-11, -35);
        var iconIndex = i + 1;
        return new MapDS.Maps.Icon('./images/markers/' + iconIndex + '.png', size, offset);
    },


    getSecondPoiIcon: function(id) {
        id++;
        var _SELF = this;
        var size = new MapDS.Size(15, 24);
        var offset = new MapDS.Pixel(-7, -24);
        var iconIndex = i + 1;
        return new MapDS.Maps.Icon('./images/markers/smallMarkers/' + iconIndex + '.png', size, offset);
    },


    /// This method is called from within findNearest. The purpose of this function is to allow
    /// for control of how the searched location marker is created and how the extra information is displayed.
    processLocationPOI: function(poi, pt) {
        var _SELF = this;
        var size = new MapDS.Size(29, 36);
        var offset = new MapDS.Pixel(-3, -35);
        var locicn = new MapDS.Maps.Icon('./images/markers/poi_home.png', size, offset);
        var searchLocation = '';
        var postalCode = '';

        var mkr = new MapDS.Maps.Marker(pt, { icon: locicn });
        mkr.setPopupContent('<div class="popup-content search-location"><h4>Your searched location</h4><p>{0}{1}{2}</p></div>'.format(
                 ((poi.Locality != '' && !_SELF.isUndefined(poi.Locality)) ? poi.Locality + ', ' : ''),
                 ((poi.PostalCode != '' && !_SELF.isUndefined(poi.PostalCode)) ? poi.PostalCode + ', ' : ''),
                 ((poi.Region != '' && !_SELF.isUndefined(poi.Region)) ? poi.Region + ' ' : '')
            )
        );

        _SELF.map.addOverlay(mkr);

        // DO NOT REMOVE THE FOLLOWING LINE - It is needed for routing purposes.
        _SELF.locationMarker = mkr;
    },

    // Set information for each trip via icon    
    processLocationVia: function(id, tripVia) {
        id++
        var _SELF = this;
        tripVia.position = new MapDS.LatLng(Number(tripVia.Position.Latitude), Number(tripVia.Position.Longitude));
        var size = new MapDS.Size(22, 36);
        var offset = new MapDS.Pixel(-11, -35);
        var icn = new MapDS.Maps.Icon('./images/tripmarkers/{0}.png'.format(id), size, offset);
        var mkr = new MapDS.Maps.Marker(tripVia.position, { icon: icn });
        Locator.tripStartAddress = tripVia.PostalCode;
        mkr.setPopupContent('<div class="popup-content"><h6>{0}</h6><p>{1}</p><p>{2}{3}</div>'.format(
            (tripVia.Locality ? tripVia.Locality : 'undefined'),
            ((tripVia.AddressLine != '' && !_SELF.isUndefined(tripVia.AddressLine)) ? tripVia.AddressLine + ', ' : ''),
            ((tripVia.PostalCode != '' && !_SELF.isUndefined(tripVia.PostalCode)) ? tripVia.PostalCode + ', ' : ''),
            ((tripVia.Region != '' && !_SELF.isUndefined(tripVia.Region)) ? tripVia.Region + ' ' : '')
        ));
        return mkr;
    },

    /// Start of core Locator code
    map: null, // object that contains the QuickMap instance
    geocoder: new MapDS.Maps.Geocoder(),
    tripHelper: null,
    RouteMode: 1, // eventually this will be a setting that can change therefore it will move to the top of the script file.
    locationMarker: null,
    DebugMode: false,
    _foundLocations: null, // private
    _lastSearchedLocation: null, // private
    _pois: [], // private
    _tripvias: [],
    _lastFieldFocussed: null, // private, the last search field to have focus
    _tripAddress: [],
    _tripAddressGeocoded: [],
    _tripCoords: [],
    _routeType: "search",
    _drivingDirections: false,

    /// Returns true if object is undefined
    isUndefined: function(object) { return typeof object === "undefined"; },

    /// Private method
    /// Returns true if object is an Image
    /// IE doesn't support "instanceof Image" so instead we test that the object is in the DOM then test the tagName is 'IMG'
    isImage: function(object) { return this.isHTMLElement(object, 'IMG'); },

    /// Returns true if object is an HTML Element
    /// {type} is a string that represents the type of HTML element that the object should be.
    ///      for example. if [type] is "div" then the element should be a div.
    isHTMLElement: function(object, type) { if (!type || !(typeof type === "string")) { return false; } if (object && object.nodeType) { return (object.tagName === type.toUpperCase() ? true : false); } return false; },

    /// Returns true if input is a number
    isNumeric: function(input) { return (input - 0) == input && input.length > 0; },

    /// Returns true if object is a function
    isFunction: function(object) { return typeof object === "function"; },

    /// Returns the id string asked for, will prepend # unless the second parameter is false.
    getElementID: function(id, withHash) { if (this.isUndefined(withHash)) { withHash = true; } return (withHash ? "#" : "") + id; },

    /// Will fire a call to load up the exception dialog, the HTML will be set using the message parameter.
    displayException: function(errorMessage) { $(this.getElementID(this.ElementIDs.ExceptionDialog)).html(errorMessage).dialog('open'); },

    /// Will save a POI as the last location.
    saveLocationPOI: function(poi) { this._lastSearchedLocation = poi; },

    /// Formats a distance into a string representation.
    formatDistance: function(d) {
        d = parseInt(d, 10);
        if (d < 1000) { return d + ' metres'; }
        d = d / 1000;
        var d = Math.round(d * Math.pow(10, 2)) / Math.pow(10, 2);
        return d + ' km';
    },

    /// Resets everything!
    reset: function() {

        this._foundLocations = null;
        this._lastSearchedLocation = null;
        this.locationMarker = null;
        this._pois = [];
        this._tripCoords = [];
        this._tripAddress = [];
        this._tripAddressGeocoded = [];
        this._routeType = 'search';
        this.resetDropdowns();
        this.searchClear = true;

        if (this.map instanceof MapDS.Maps.Map) {
            if (Locator.country == 'AU') {
                this.map.setCentre(this.InitialCentre, this.InitialZoom);
            }
            else {
                this.map.setCentre(this.InitialNzCentre, this.InitialNzZoom);
            }
            this.map.clearOverlays();
        }
        $.each($(this.getElementID(this.ElementIDs.FiltersList) + ' input:checkbox'), function(i, checkbox) {
            $(this).attr("checked", "");
        });

    },

    /// Resets the content of the POIs and Direction dropdowns.
    resetDropdowns: function() {
        $(this.getElementID(this.ElementIDs.DrivingDirectionsList)).html('<p>Please perform a search or zoom in to see locations.</p>');
        $(this.getElementID(this.ElementIDs.POIsFound)).html('<div class="errMsg">No results are available. Please enter a suburb or postcode and select a service to search.</div>');
        $(this.getElementID(this.ElementIDs.POIsList)).html('');
        $(this.getElementID(this.ElementIDs.DrivingDirectionsList)).html('<div class="errMsg">There are currently no driving directions available. Please select ‘directions’ link from the results tab.</div>');
        $(this.getElementID(this.ElementIDs.StartTitle)).html('');
        $(this.getElementID(this.ElementIDs.EndTitle)).html('');
    },

    applyFilters: function() {

        if ($(this.getElementID(this.ElementIDs.TripplannerButton)).is('.menu-open')) {
            this.planTrip();
        }
        else {
            this.findAddress();
        }

    },

    /// Performs a call to geocode in order to geocode an address for a search.
    findAddress: function() {

        //if called from trip planner call planTrip instead
        if (!this.validateSearchFields()) { return; }
        var _SELF = this;
        _SELF.map.clearOverlays();
        _SELF.tripHelper.clear();
        $(this.getElementID(this.ElementIDs.POIsFound)).html('');
        $(this.getElementID(this.ElementIDs.POIsList)).html('<p><img src="./images/loading-circle-black.gif" alt="Loading" height="16px" width="16px" /> Loading</p>');
        _SELF._tripCoords = [];
        _SELF._tripVias = [];
        _SELF._routeType = 'search';
        var txtSuburb = $(_SELF.getElementID(_SELF.ElementIDs.SearchSuburb));
        var autoComplete = autoCompleteFunction.checkAutoComplete(txtSuburb);
        _SELF.toggleDropdown(2);

        //check autocomplete option has been selected
        if (autoComplete) {
            _SELF.findNearest(autoComplete, null);
        } else {

            _SELF.geocode(_SELF.buildAddressSearch(), null, function(address, k) {
                var coords = address.Position.Latitude + ', ' + address.Position.Longitude;
                autoCompleteFunction.addFieldID(_SELF.ElementIDs.SearchSuburb, coords); txtSuburb.val(address.Locality.toProperCase() + ',' + address.PostalCode + ',' + address.Region); _SELF.findNearest(address, k);
            });
        }
    },

    /// Performs a call to Geocode an address. If a single match is found then the method 
    /// will automatically call findNearest. Multiple matches are displayed within a 
    /// dialog for the user to select.
    //Tests to see if it is a trip planned or a search this is used to correctly direct information after a multiple result.
    geocode: function(addressToGeocode, ID, loadAddressCallBack, multipleAddressCallBack) {

        // make jQuery Ajax call...
        var _SELF = this;
        _SELF.geocoder.getLocations(addressToGeocode, function(result) {
            // if (this.DebugMode) { Logger.log(result); }

            if (result.Code === 1) {
                loadAddressCallBack(result.Locations[0], ID);
            } else if (result.Code === 100) {
                _SELF._foundLocations = result.Locations;

                $(_SELF.getElementID(_SELF.ElementIDs.MultipleAddressDialog)).find(
                        _SELF.getElementID(_SELF.ElementIDs.MultipleAddresses)).html('');



                // Sets what type of search it is for the multiple results form
                if (_SELF._routeType == 'search') {
                    $('<input type="hidden" id="tripSearchHidden" value="notTripSearch" />').appendTo(
                            $(_SELF.getElementID(_SELF.ElementIDs.MultipleAddressDialog)));
                } else {
                    $('<input type="hidden"  id="tripSearchHidden" value="tripSearch" />').appendTo(
                            $(_SELF.getElementID(_SELF.ElementIDs.MultipleAddressDialog)));
                    $('<input type="hidden"  id="locationID" value="' + ID + '" />').appendTo(
                            $(_SELF.getElementID(_SELF.ElementIDs.MultipleAddressDialog)))
                }

                $("<option/>").attr('value', '0').html(_SELF.Strings.MultipleAddressPrompt).appendTo(
                        $(_SELF.getElementID(_SELF.ElementIDs.MultipleAddressDialog)).find(
                        _SELF.getElementID(_SELF.ElementIDs.MultipleAddresses)));

                $.each(result.Locations, function(i, address) {
                    $("<option/>").html((address.AddressLine != '' ? address.AddressLine + ', ' : '') +
                        address.Locality + ', ' + address.Region + ', ' + address.PostalCode).appendTo(
                        $(_SELF.getElementID(_SELF.ElementIDs.MultipleAddressDialog)).find(
                        _SELF.getElementID(_SELF.ElementIDs.MultipleAddresses)));
                });

                $(_SELF.getElementID(_SELF.ElementIDs.MultipleAddressDialog)).dialog('open');
            } else if (result.Code === 110) {
                ID++;
                if (_SELF._routeType == 'search') {
                    _SELF.displayException("<p class='errorheader'>Invalid location</p> We were unable to find the location specified. Please try new information");
                }
                else {
                    _SELF.displayException("<p class='errorheader'>Location Via " + ID + "</p> We were unable to find the location specified. Please try new information");
                }
            } else if (result.Code > 100) {
                _SELF.displayException(result.Message);
            }
        });
    },

    /// Calls findnearest.ashx passing X/Y and search filters. Results are displayed.
    findNearest: function(address, id) {
        var _SELF = this;
        var txtSuburb = $(_SELF.getElementID(_SELF.ElementIDs.SearchSuburb));
        var txtSuburbID = _SELF.ElementIDs.SearchSuburb;
        var pt = new MapDS.LatLng(Number(address.Position.Latitude), Number(address.Position.Longitude));
        // Set the map centre at the found location. Once the map zooms in a features call will be made. 
        _SELF.map.setCentre(pt, 11);
        // Save the location for driving directions
        _SELF.saveLocationPOI.apply(_SELF, [address]);
        _SELF.processLocationPOI(address, pt);
        //open results tab if closed
        if ($(_SELF.getElementID(_SELF.ElementIDs.panel2)).is(":hidden")) { _SELF.toggleDropdown(2); $(_SELF.getElementID(_SELF.ElementIDs.POIsButton)); $(_SELF.getElementID(_SELF.ElementIDs.ResultsButton)); }
        _SELF.findTripPOIs(0);
    },

    /// Executes a request for driving directions for the given POI id.
    getDirections: function(id) {
        var _SELF = this;
        var txtStartLocation = '';
        _SELF.resetTripSearchFields();
        _SELF._tripAddressGeocoded = [];
        _SELF._tripAddress = [];
        _SELF._tripCoords = [];
        _SELF._routeType = 'search';
        _SELF._drivingDirections = true;
        _SELF.removeExtraFields();

        if (_SELF.map.hasVisiblePopup()) { _SELF.map.removePopups(); }
        if (!_SELF.isUndefined(_SELF._pois) && _SELF._pois.length >= id) {
            id -= 1; // decrement to get array position

            // Get coorinates and 
            var st = _SELF._lastSearchedLocation.position;
            var startAddress = $(_SELF.getElementID(_SELF.ElementIDs.SearchSuburb)).val();
            var txtSuburb = $(_SELF.getElementID(_SELF.ElementIDs.SearchSuburb));
            var autoComplete = autoCompleteFunction.checkAutoComplete(txtSuburb);

            // Take the suburb if it has been populated 
            if (!_SELF._lastSearchedLocation.Locality.isUndefined && _SELF._lastSearchedLocation.Locality != '') {
                var suburb = _SELF._lastSearchedLocation.Locality.toProperCase();
            }

            // Region and postcode should be populated as a minimum
            var region = _SELF._lastSearchedLocation.Region;
            var postcode = _SELF._lastSearchedLocation.PostalCode;
            txtStartLocation = suburb + ',' + postcode + ',' + region;
        }


        // Format the start location coordinates to be put in the first coordinates field. This will allow them to be used to same as the trip planner. 
        var txtStartLocationCoords = _SELF._lastSearchedLocation.Position.Latitude + ',' + _SELF._lastSearchedLocation.Position.Longitude;

        // Add coodinates/ location information to fields
        var startID = this.ElementIDs.TxtTripSuburb + '1';
        autoCompleteFunction.addFieldID(startID, txtStartLocationCoords);
        $(this.getElementID(this.ElementIDs.TxtTripSuburb) + "1").val(txtStartLocation);
        $(this.getElementID(this.ElementIDs.StartTitle)).html("<b>Start: " + txtStartLocation + "</b>");

        // Format end location details
        var suburb = _SELF._pois[id].properties.DisplayName;
        var state = _SELF._pois[id].properties.State;
        var postcode = _SELF._pois[id].properties.Postcode;
        txtEndLocation = suburb + ',' + postcode + ',' + state;

        // Format the end location coordinates to be put in the first coordinates field. This will allow them to be used to same as the trip planner
        var txtEndLocationCoords = _SELF._pois[id].position.Latitude() + ',' + _SELF._pois[id].position.Longitude();

        // Add coodinates/ location information to fields
        var endID = this.ElementIDs.TxtTripSuburb + '2';
        autoCompleteFunction.addFieldID(endID, txtEndLocationCoords);
        $(this.getElementID(this.ElementIDs.TxtTripSuburb) + "2").val(txtEndLocation);
        $(this.getElementID(this.ElementIDs.EndTitle)).html("<br><b>End: " + txtEndLocation + "</b>");

        // Add as the validation does which fields are populated
        _SELF._tripAddress.push(1, 2);
        _SELF._tripCoords.push(txtStartLocationCoords, txtEndLocationCoords);
        _SELF.planTrip();
        $(this.getElementID(this.ElementIDs.TripFieldsInputs) + ' input:text[title!=""]').hint();
        $(this.getElementID(this.ElementIDs.TripFieldsInputs) + ' input[title!=""]').attr("value", "").blur();
        $(this.getElementID(this.ElementIDs.TripFieldsInputs) + ' input:text[title!=""]').attr("value", "").blur();
        $(this.getElementID(this.ElementIDs.TripFieldsInputs) + ' input:hidden[title!=""]').attr("value", "").blur();
    },


    // Shows/Hides the street field 
    showStreet: function(txtID) {
        var _SELF = this;
        $(_SELF.getElementID(_SELF.ElementIDs.TxtTripStreet) + txtID).attr("value", "").blur();
        $(_SELF.getElementID(_SELF.ElementIDs.TxtTripStreet) + txtID).toggle();
    },

    // Shows/Hides the inputs
    hideInputs: function() {
        var _SELF = this;
        $(_SELF.getElementID(_SELF.ElementIDs.HideInputs)).toggle();
        $(_SELF.getElementID(_SELF.ElementIDs.ShowInputs)).toggle();
        $(_SELF.getElementID(_SELF.ElementIDs.TripFieldList)).toggle();
    },


    /// Executes a request for driving directions for the trip Planner.
    getTripDirections: function() {
        var _SELF = this;
        if (_SELF.map.hasVisiblePopup()) { _SELF.map.removePopups(); }

        _SELF.tripHelper.clear();
        _SELF._tripVias = [];

        var ddList = $(_SELF.getElementID(_SELF.ElementIDs.DrivingDirectionsList));
        ddList.html('<p><img src="./images/loading-circle-black.gif" alt="Loading" height="16px" width="16px" /> Loading</p>');

        var dd = $(_SELF.getElementID(_SELF.ElementIDs.TripDirectionsList));
        if (dd.is(":hidden")) {
            _SELF.toggleDropdown(3);
        }

        _SELF._lastSearchedLocation = _SELF._tripAddressGeocoded[0];
        _SELF.tripHelper.buildFromWaypoints(_SELF._tripCoords);
        $(_SELF.getElementID(_SELF.ElementIDs.POIsButton));

        // Add each location marker to the map
        $.each(_SELF._tripAddressGeocoded, function(i) {
            tripVia = _SELF._tripAddressGeocoded[i];
            tripVia.Marker = _SELF.processLocationVia(i, _SELF._tripAddressGeocoded[i])
            _SELF._tripVias.push(tripVia);
            _SELF.map.addOverlay(tripVia.Marker);
        });

        _SELF.map.loadBestView();

        if ($('#fuelLoc').attr('checked') == true) {

            if ($(this.getElementID(this.ElementIDs.TripplannerButton)).is('.menu-open')) {

            }
        }


    },

    // Adds a POI location to a route
    addToRoute: function(id) {
        var _SELF = this;
        id = id - 1;
        // hide any open popups
        _SELF.map.removePopups();
        addFields.addNewTripRow();

        // Get a reference to the upload container.
        var jFilesContainer = $(_SELF.getElementID(_SELF.ElementIDs.TripFieldsInputs));
        var intNewFileCount = (jFilesContainer.find("div.row").length);

        // Format end location details
        var suburb = _SELF._pois[id].properties.DisplayName;
        var state = _SELF._pois[id].properties.State;
        var postcode = _SELF._pois[id].properties.Postcode;
        txtEndLocation = suburb + ',' + postcode + ',' + state;

        // Format the end location coordinates to be put in the first coordinates field. This will allow them to be used to same as the trip planner
        var txtEndLocationCoords = _SELF._pois[id].position.Latitude() + ',' + _SELF._pois[id].position.Longitude();

        // Add coodinates/ location information to fields
        var endID = this.ElementIDs.TxtTripSuburb + intNewFileCount;
        autoCompleteFunction.addFieldID(endID, txtEndLocationCoords);

        $(this.getElementID(this.ElementIDs.TxtTripSuburb) + intNewFileCount).val(txtEndLocation);
        var dd = $(_SELF.getElementID(_SELF.ElementIDs.TripDirectionsList));
        if (dd.is(":hidden")) {
            _SELF.toggleDropdown(3);
        }
    },

    //Find and display POIs either within a bounding box or along a route
    findTripPOIs: function(searchType) {


        var str = $("input[name='features']:checked").val();
        var _SELF = this;
        var featureTable = "GECUSTOMFLEETAU";

        if (Locator.country == 'NZ') {
            featureTable = 'GECUSTOMFLEETNZ';
        }



        var tpOpen = $(this.getElementID(this.ElementIDs.TripplannerButton)).is('.menu-open');
        // Finds locations along the route if a trip has been submitted. Will not find locations if driving directions   
        if (_SELF._routeType == 'trip') {

            var featuresClient = new MapDS.Features.ServiceClient();
            var searchBuffer = $(this.getElementID(this.ElementIDs.SearchDistance)).val();
            var centrePoint = _SELF.map.getCentre();
            var polyline = null;

            var pts = [];
            var nth = Math.floor(_SELF.tripHelper.getPolyline().points.length * 0.01);
            var rec = 0;

            for (var i = 0; i < nth; i++) {
                if (rec < _SELF.tripHelper.getPolyline().points.length) {
                    pts.push(_SELF.tripHelper.getPolyline().points[rec]);
                    rec += Math.floor(_SELF.tripHelper.getPolyline().points.length / nth);
                }
            }

            pts.push(_SELF.tripHelper.getPolyline().points[_SELF.tripHelper.getPolyline().points.length - 1])
            polyline = new MapDS.Maps.Polyline(pts);
            var p = new MapDS.Features.PointsQuery(polyline.toEncoded(), { buffer: 1000, items: 100, filter: _SELF.getSearchFiltersString(), sortby: 'distance' });

            var tpOpen = $(this.getElementID(this.ElementIDs.TripplannerButton)).is('.menu-open');
            if (tpOpen) {
                //execute query on service and display result
                featuresClient.getFeatures(p, featureTable, function(results) {

                    if (results.length < 1) {
                        $(_SELF.getElementID(_SELF.ElementIDs.POIsList)).html(_SELF.Strings.InvalidSearch);
                    }

                    $.each(_SELF._pois, function(i, poi) {
                        _SELF.map.removeOverlay(poi.Marker);
                    });

                    _SELF._pois = [];
                    $(_SELF.getElementID(_SELF.ElementIDs.POIsList)).html('');

                    Logger.log(results);


                    if (results.features != undefined) {
                        $.each(results.features, function(i) {
                            var id = i + 1;
                            poi = results.features[i]
                            poi.Marker = _SELF.processPOI(id, results.features[i])
                            _SELF.map.addOverlay(poi.Marker);

                        });

                    }

                    _SELF.switchIcons(results, searchType);
                });
            }
            //}

        } else {



            var bb = _SELF.map.getBounds();
            var featuresClient = new MapDS.Features.ServiceClient();
            var searchBuffer = $(this.getElementID(this.ElementIDs.SearchDistance)).val();
            var centrePoint = _SELF.map.getCentre();
            var lng = centrePoint.Longitude();
            var lat = centrePoint.Latitude();
            var ll = [new MapDS.LatLng(lat, lng)];
            if (_SELF._routeType == 'trip' && $(this.getElementID(this.ElementIDs.TripplannerButton)).is('.menu-open')) {
                var p = new MapDS.Features.BBOXQuery(bb, { items: 50, page: 1, filter: _SELF.getSearchFiltersString() });
            }
            else {

                var p = new MapDS.Features.PointsQuery(ll, { buffer: searchBuffer, items: 50, page: 1, filter: _SELF.getSearchFiltersString(), sortby: 'distance' });
            }

            //execute query on service and display result     
            featuresClient.getFeatures(p, featureTable, function(results) {
                $.each(_SELF._pois, function(i, poi) {
                    _SELF.map.removeOverlay(poi.Marker);
                });



                _SELF._pois = [];
                $(_SELF.getElementID(_SELF.ElementIDs.POIsList)).html('');

                if (results.features != undefined) {

                    //  $.each(results.features, function(i) {
                    //   var id = i + 1;
                    //  poi = results.features[i]
                    // poi.Marker = _SELF.processPOI(id, results.features[i])
                    // _SELF.map.addOverlay(poi.Marker);

                    //  });

                }

                _SELF.switchIcons(results, searchType);
            });
        }
    },

    // Displays the current ten icon locaitons in the list/ removes the previous ten icons being displayed
    switchIcons: function(results, searchType) {

        var _SELF = this;
        var lastPoiListPage = -1;
        poiPaging = $(_SELF.getElementID(_SELF.ElementIDs.POIsFound)).html('');
        if (results.features != undefined) {
            $.each(results.features, function(i) {
                var id = i + 1;
                poi = results.features[i]
                poi.Marker = _SELF.processPOI(id, results.features[i])
                _SELF._pois.push(poi);

            });

            Logger.log(results.features.length);

            var maxResultHTML = "<div id='maxResults'> The maximum number <b>100</b> results have been found. Please refine your search</div>";

            if (results.features.length >= 100) {

                $(poiPaging).append(maxResultHTML);

            }

            Logger.log("results");

            $('<div/>').addClass('pagination').appendTo(poiPaging).pagination(
                        results.features.length, {
                            callback: (
                                function(page_index, jq) {
                                    // this has scope of pagination control.
                                    // hide any open popups
                                    _SELF.map.removePopups();

                                    // here we   the last viewed pages poi markers.
                                    if (lastPoiListPage > -1 && lastPoiListPage != page_index) {
                                        var max_elem = Math.min((lastPoiListPage + 1) * this.items_per_page, results.features.length);
                                        for (var i = lastPoiListPage * this.items_per_page; i < max_elem; i++) {
                                            _SELF.map.removeOverlay(results.features[i].Marker);

                                            //do this if tripplanner only
                                            if (searchType == 1) {
                                                results.features[i].Marker.Icon(_SELF.getSecondPoiIcon(i));
                                                _SELF.map.addOverlay(results.features[i].Marker);
                                            }
                                        }

                                    }

                                    // Get number of elements per pagination page from form
                                    var max_elem = Math.min((page_index + 1) * this.items_per_page, results.features.length);
                                    poiList = $(_SELF.getElementID(_SELF.ElementIDs.POIsList)).html('');

                                    if (results.features.length == 0) {
                                        $(_SELF.getElementID(_SELF.ElementIDs.POIsFound)).hide();
                                        var distance = $("#ddlDistance option:selected").text();
                                        poiList = $(_SELF.getElementID(_SELF.ElementIDs.POIsList)).html('<b>There are no Custom Fleet approved merchants found within ' + distance + ' of your address.</b>');
                                    }

                                    var poiCounter = 0;

                                    // Iterate through a selection of the content and build an HTML string
                                    for (var i = page_index * this.items_per_page; i < max_elem; i++) {

                                        var id = i;
                                        poi = results.features[i]
                                        poi.Marker = _SELF.processPOI(id, results.features[i])
                                        //_SELF._pois.push(poi);
                                        _SELF.map.removeOverlay(results.features[i].Marker);
                                        results.features[i].Marker.Icon(_SELF.getMainPoiIcon(i));
                                        _SELF.map.addOverlay(results.features[i].Marker);
                                        var poi = [];
                                        poiCounter++;

                                        // build list item
                                        poi.li = _SELF.processPOIForResultsList.apply(_SELF, [results.features[i], i]);
                                        $(poi.li).appendTo(poiList);
                                    }

                                    _SELF.map.loadBestView();

                                    // store this as the last visited page
                                    lastPoiListPage = page_index;

                                    // Prevent click eventpropagation
                                    return false;
                                }
                            ),
                            items_per_page: 10,
                            num_display_entries: 5,
                            num_edge_entries: 0
                        }
                    );
        }
    },

    // Geocodes each trip field if not autocompleted. 
    geocodeTrip: function(k) {
        var _SELF = this;
        var coords = '';
        var locality = '';
        var locationAddress = '';
        var postalCode = '';
        var region = '';

        // Check to see if it is the last value in array by comparing the number of locations geocoded to the number of locations put in the array during validation
        // If all locations have been geocoded the route will be built
        if (_SELF._tripAddressGeocoded.length != _SELF._tripAddress.length) {

            var txtStreet = $(_SELF.getElementID(_SELF.ElementIDs.TxtTripStreet) + _SELF._tripAddress[k]);
            var streetSearch = true;
            // test if the street input has been entered
            if (txtStreet.val().toLowerCase() == txtStreet.attr("title").toLowerCase()) {
                streetSearch = false;
            }

            var txtSuburb = $(_SELF.getElementID(_SELF.ElementIDs.TxtTripSuburb) + _SELF._tripAddress[k]);

            var autoComplete = autoCompleteFunction.checkAutoComplete(txtSuburb);

            //Test to see if autocomplete has been used and if no street has been filled in. If so use the Coordinates/Suburb/Postcode/State sent back from features
            if (!streetSearch && autoComplete) {
                _SELF._tripCoords.push(new MapDS.LatLng(Number(autoComplete.Position.Latitude), Number(autoComplete.Position.Longitude)));
                _SELF._tripAddressGeocoded.push(autoComplete);
                k++;
                _SELF.geocodeTrip(k);

            } else {

                // Build address for each location
                address = _SELF.buildTripAddressSearch(_SELF._tripAddress[k]);

                // Geocode each address
                _SELF.geocode(address, k, function(geocode, k) { _SELF.addCoords(geocode, k); });
            }
        } else {
            // When all locations have been geocoded build route
            _SELF.getTripDirections();

        }
    },

    // Add coordinates to trip array 
    addCoords: function(geocode, k) {
        var _SELF = this;
        _SELF._tripAddressGeocoded.push(geocode);
        var inputID = this.ElementIDs.TxtTripSuburb + _SELF._tripAddress[k];
        var coords = geocode.Position.Latitude + ', ' + geocode.Position.Longitude;
        autoCompleteFunction.addFieldID(inputID, coords);
        _SELF._tripCoords.push(new MapDS.LatLng(Number(geocode.Position.Latitude), Number(geocode.Position.Longitude)));

        // Add the geocoded address to the suburb field. The application will then use the already stored coordinates if the route is updated. 
        var currentField = $(this.getElementID(this.ElementIDs.TxtTripSuburb) + _SELF._tripAddress[k]);
        var geocodedAddress = geocode.Locality.toProperCase() + ', ' + geocode.PostalCode + ', ' + geocode.Region;
        $(currentField).val(geocodedAddress);
        k++;
        _SELF.geocodeTrip(k);
    },

    // Called from "Get Directions" button on page as well as "getDirections" function. Sets arrays for trip information to be placed. 
    //Calls the trip geocode function if enough fields are populated.
    planTrip: function() {

        var _SELF = this;

        _SELF._tripAddress = [];
        _SELF._tripAddressGeocoded = [];
        _SELF._tripCoords = [];

        if ($(this.getElementID(this.ElementIDs.TripplannerButton)).is('.menu-open')) {
            _SELF.map.clearOverlays();
            $(this.getElementID(this.ElementIDs.StartTitle)).html('');
            $(this.getElementID(this.ElementIDs.EndTitle)).html('');
        }
        else {
            $.each(_SELF._tripVias, function(i, viapoi) {
                _SELF.map.removeOverlay(viapoi.Marker);
            });
        }
        if (!this.validateTripFields()) { return; }
        var k = 0;
        _SELF._routeType = 'trip';
        _SELF.geocodeTrip(k);
    },

    // Updates the route after the input boxes have been dragged.   
    updateTrip: function() {
        var validSuburbNo = 0;
        var _SELF = this;

        // Find if input fields have been filled to avoid planning a trip on sorting without previous trip.
        $('input:text[name=txtTripSuburb]').each(function(i) {

            if (this.value != '' && this.value.toLowerCase() != this.title.toLowerCase()) {
                validSuburbNo = validSuburbNo + 1;
                haveValidSuburb = true;
                sid = i + 1;
            }
        });

        // Show error if there are not enough valid locations
        if (validSuburbNo >= 2) {
            _SELF.planTrip();
        }
    },

    /// Toggles the directions dropdown
    toggleDropdown: function(dropDown) {
        var _SELF = this;
        var A = null;
        var B = null;
        var currentMapWidth = $(_SELF.getElementID(_SELF.ElementIDs.Map)).width();
        var currentMapHeight = $(_SELF.getElementID(_SELF.ElementIDs.Map)).height();

        if (dropDown === 0) {
            $('#ddlService').val('none');
            $('#ddlService').trigger('change');

            //locator button clicked
            $(_SELF.getElementID(_SELF.ElementIDs.LocatorButton)).addClass("menu-open");

            $(_SELF.getElementID(_SELF.ElementIDs.TripplannerButton)).removeClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.TripSearch)).hide();
            $(_SELF.getElementID(_SELF.ElementIDs.TripDirectionsList)).hide();
            $(_SELF.getElementID(_SELF.ElementIDs.Search)).show();
            $(_SELF.getElementID(_SELF.ElementIDs.FiltersButton)).addClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.POIsButton)).removeClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.DirectionsButton)).removeClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.FiltersList)).html('<div class="errMsg">Options to refine your search will automatically appear here after you select a service above</div>');
            $(_SELF.getElementID(_SELF.ElementIDs.FiltersList)).show();
        }
        else if (dropDown === 1) {
            // refine button clicked
            $(_SELF.getElementID(_SELF.ElementIDs.FiltersList)).show();
            $(_SELF.getElementID(_SELF.ElementIDs.POIsList)).hide();
            $(_SELF.getElementID(_SELF.ElementIDs.POIsFound)).hide();
            $(_SELF.getElementID(_SELF.ElementIDs.TripDirectionsList)).hide();
            $(_SELF.getElementID(_SELF.ElementIDs.FiltersButton)).addClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.POIsButton)).removeClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.DirectionsButton)).removeClass("menu-open");

        } else if (dropDown === 2) {
            // results button clicked
            $(_SELF.getElementID(_SELF.ElementIDs.POIsButton));
            $(_SELF.getElementID(_SELF.ElementIDs.FiltersButton)).removeClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.POIsButton)).addClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.DirectionsButton)).removeClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.FiltersList)).hide();
            $(_SELF.getElementID(_SELF.ElementIDs.TripDirectionsList)).hide();
            $(_SELF.getElementID(_SELF.ElementIDs.POIsList)).show();
            $(_SELF.getElementID(_SELF.ElementIDs.POIsFound)).show();

        } else if (dropDown === 3) {
            // Directions button clicked
            $(_SELF.getElementID(_SELF.ElementIDs.FiltersButton)).removeClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.POIsButton)).removeClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.DirectionsButton)).addClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.FiltersList)).hide();
            $(_SELF.getElementID(_SELF.ElementIDs.POIsList)).hide();
            $(_SELF.getElementID(_SELF.ElementIDs.POIsFound)).hide();
            $(_SELF.getElementID(_SELF.ElementIDs.TripDirectionsList)).show();
        }
        else if (dropDown === 4) {
            //tripplanner button clicked
            $(_SELF.getElementID(_SELF.ElementIDs.Search)).hide();
            $(_SELF.getElementID(_SELF.ElementIDs.TripSearch)).show();
            $(_SELF.getElementID(_SELF.ElementIDs.TripDirectionsList)).hide();
            $(_SELF.getElementID(_SELF.ElementIDs.LocatorButton)).removeClass("menu-open");

            if (Locator.country == 'AU') {

                $('#ddlService').val('Service station');
                $('#ddlService').trigger('change');
            }
            else {
                $('#ddlNzService').val('Service station');
                $('#ddlNzService').trigger('change');
            }

            $(_SELF.getElementID(_SELF.ElementIDs.POIsList)).hide();
            $(_SELF.getElementID(_SELF.ElementIDs.POIsFound)).hide();

            $(_SELF.getElementID(_SELF.ElementIDs.TripplannerButton)).addClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.FiltersButton)).addClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.POIsButton)).removeClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.DirectionsButton)).removeClass("menu-open");
            $(_SELF.getElementID(_SELF.ElementIDs.LocatorButton)).removeClass("menu-open");
        }
    },


    // Opens the printer friendly page.   
    printerFriendly: function() {
        var _SELF = this;
        var newWin;
        if (_SELF._tripCoords != '') {
            $(_SELF.getElementID(_SELF.ElementIDs.HiddenCoords)).val(_SELF._tripCoords);
        }
        newWin = window.open("PrintPage.aspx", "kid", 'resizable=yes,menubar=1,toolbar=1,scrollbars=yes,width=900,height=650,toolbar=no');
    },


    /// This method is hooked into the window.onload within the init method.
    initMap: function(lat, lng, zoom) {
        var _SELF = this;
        if (Locator.country == 'AU') {
            _SELF.map = new MapDS.Maps.Map(_SELF.getElementID(_SELF.ElementIDs.Map, false), { zoom: _SELF.InitialZoom, centre: _SELF.InitialCentre });
            $('.hdn-newzealand').hide();
        }
        else {
            _SELF.map = new MapDS.Maps.Map(_SELF.getElementID(_SELF.ElementIDs.Map, false), { zoom: _SELF.InitialNzZoom, centre: _SELF.InitialNzCentre });
            $('.hdn-australia').hide();
            _SELF.geocoder.setCountryCode("NZ");
        }
        _SELF.tripHelper = new MapDS.Maps.Directions(_SELF.map, (_SELF.ElementIDs.DrivingDirectionsList ? document.getElementById(_SELF.ElementIDs.DrivingDirectionsList) : null));


        MapDS.Events.addListener(_SELF.tripHelper, "load", function() {
            // can perform a features request parsing in the 
            // route poyline using - this.getPolyline().toEncoded();

            if ($('#fuelLoc').attr('checked') == true) {

                //   if ($(this.getElementID(this.ElementIDs.TripplannerButton)).is('.menu-open')) {
                _SELF.findTripPOIs(1);
            }
            //  }

        });




        _SELF._lastCentre = _SELF.map.getCentre();
        _SELF._lastZoom = _SELF.map.getZoom();




    },

    /// The main initialisation method for the Locator object.
    init: function() {
        var _SELF = this;
        var searchClear = false;
        var searchActive = false;
        var txtSuburb = $(_SELF.getElementID(_SELF.ElementIDs.SearchSuburb));
        $().ready(function() {

            // Grab all anchor elements on the page that have an href and target is external. Set their target to blank.
            $('a[rel="external"]').filter('[href!=""]').each(function() { this.target = "_blank"; });
            $(_SELF.getElementID(_SELF.ElementIDs.LocatorButton)).click(function() { _SELF.toggleDropdown(0); $('#ddlService').val(Locator.LastLocatorSearchType); $('#ddlService').trigger('change'); });
            $(_SELF.getElementID(_SELF.ElementIDs.TripplannerButton)).click(function() { setLastLocatorSearchType(); _SELF.toggleDropdown(4); $('#fuelLoc').attr('checked', true); $('#ddlService').val('Service station'); $('#ddlService').trigger('change'); });
            $(_SELF.getElementID(_SELF.ElementIDs.SearchButton)).click(function() { _SELF.searchActive = true; _SELF.findAddress(); });
            $(_SELF.getElementID(_SELF.ElementIDs.TripSearchButton)).click(function() { $(_SELF.getElementID(_SELF.ElementIDs.TripplannerButton)).addClass("menu-open"); _SELF.planTrip(); });
            $(_SELF.getElementID(_SELF.ElementIDs.ResetButton)).click(function() { _SELF.reset(); _SELF.resetSearchFields(); });
            $(_SELF.getElementID(_SELF.ElementIDs.ResetTripButton)).click(function() { _SELF.reset(); _SELF.resetTripSearchFields(); });
            $(_SELF.getElementID(_SELF.ElementIDs.DirectionsButton)).click(function() { _SELF.toggleDropdown(3); });
            $(_SELF.getElementID(_SELF.ElementIDs.POIsButton)).click(function() { _SELF.toggleDropdown(2); });
            $(_SELF.getElementID(_SELF.ElementIDs.FiltersButton)).click(function() { _SELF.toggleDropdown(1); });
            $(_SELF.getElementID(_SELF.ElementIDs.PrintLink)).click(function() { _SELF.printerFriendly(); });
            $(_SELF.getElementID(_SELF.ElementIDs.HideInputs)).click(function() { _SELF.hideInputs(); });
            $(_SELF.getElementID(_SELF.ElementIDs.ShowInputs)).click(function() { _SELF.hideInputs(); });
            $(_SELF.getElementID(_SELF.ElementIDs.HideFilters)).click(function() { $(_SELF.getElementID(_SELF.ElementIDs.HideFilters)).toggle(); $(_SELF.getElementID(_SELF.ElementIDs.ShowFilters)).toggle(); $(_SELF.getElementID(_SELF.ElementIDs.FiltersList)).toggle(); });
            $(_SELF.getElementID(_SELF.ElementIDs.ShowFilters)).click(function() { $(_SELF.getElementID(_SELF.ElementIDs.HideFilters)).toggle(); $(_SELF.getElementID(_SELF.ElementIDs.ShowFilters)).toggle(); $(_SELF.getElementID(_SELF.ElementIDs.FiltersList)).toggle(); });
            $(_SELF.getElementID(_SELF.ElementIDs.CloseSidebar)).click(function() { $(_SELF.getElementID(_SELF.ElementIDs.Sidebar)).toggle(); $(_SELF.getElementID(_SELF.ElementIDs.CloseSidebar)).toggleClass('toggleSidebarOpen'); $(_SELF.getElementID(_SELF.ElementIDs.Map)).toggleClass('mapResultsOpen'); });

            // Init Autocomplete fields
            autoCompleteFunction.initAutoComplete($(_SELF.getElementID(_SELF.ElementIDs.SearchSuburb)));
            autoCompleteFunction.initAutoComplete($(_SELF.getElementID(_SELF.ElementIDs.TxtTripSuburb) + "1"));
            autoCompleteFunction.initAutoComplete($(_SELF.getElementID(_SELF.ElementIDs.TxtTripSuburb) + "2"));

            // need to have the current text blanked on focus, reset on blur...
            $(_SELF.getElementID(_SELF.ElementIDs.Search) + ' input[title!=""]').keypress(function(evt) { _SELF._lastFieldFocussed = this; if (evt.keyCode == 13) { $(_SELF.getElementID(_SELF.ElementIDs.SearchButton)).click(); } }).hint();
            // ensure that Enter presses on the form don't cause a submit
            $("form").keypress(function(e) { if (e.keyCode == 13) { return false; } });

            // need to have the current text blanked on focus, reset on blur...
            $(_SELF.getElementID(_SELF.ElementIDs.TripSearch) + ' input[title!=""]').keypress(function(evt) { _SELF._lastFieldFocussed = this; }).hint();

            var country = getUrlVars()["country"];
            if (country != undefined && country.toUpperCase() == 'NZ') {
                Locator.country = 'NZ';
                $(_SELF.getElementID(_SELF.ElementIDs.SearchService)).hide();
            }
            else {
                $(_SELF.getElementID(_SELF.ElementIDs.SearchNzService)).hide();
            }

            $(_SELF.getElementID(_SELF.ElementIDs.FiltersList)).html('<b>Options to refine your search will automatically appear here after you select a service above</b>');

            // attach the exception dialog
            $(_SELF.getElementID(_SELF.ElementIDs.ExceptionDialog)).dialog({
                bgiframe: true,
                modal: true,
                draggable: false,
                resizable: false,
                autoOpen: false,
                zIndex: 99999,
                close: function(evt, ui) {
                    if (_SELF._lastFieldFocussed) {
                        _SELF._lastFieldFocussed.focus();
                    }
                },
                buttons: { OK: function() { $(this).dialog('close'); } }
            });

            // attach the filters dialog
            $(_SELF.getElementID(_SELF.ElementIDs.FiltersDialog)).dialog({
                bgiframe: true,
                modal: false,
                draggable: true,
                resizable: false,
                autoOpen: false,
                zIndex: 99999
            });

            // attach the multiple results dialog.
            $(_SELF.getElementID(_SELF.ElementIDs.MultipleAddressDialog)).dialog({
                bgiframe: true,
                height: 300,
                width: 400,
                modal: true,
                draggable: false,
                resizable: false,
                autoOpen: false,
                zIndex: 99999,
                buttons: {
                    'Use Address': function() {

                        var txtSuburb = $(Locator.getElementID(Locator.ElementIDs.SearchSuburb));
                        var option = $('#ddlMultipleAddresses').find(':selected').text();


                        if ($(Locator.getElementID(Locator.ElementIDs.LocatorButton)).is('.menu-open')) {
                            txtSuburb.attr("value", option);
                        }


                        var idx = $(this).find(_SELF.getElementID(_SELF.ElementIDs.MultipleAddresses)).attr('selectedIndex');
                        var tripSearch = $(this).find(_SELF.getElementID(_SELF.ElementIDs.TripSearchHidden)).val();
                        var k = $(this).find(_SELF.getElementID(_SELF.ElementIDs.LocationID)).val();
                        if (idx != 0) {
                            // go back one to get correct array location.
                            idx--;
                            // Call FindNearest....

                            if (tripSearch != "tripSearch") {
                                var pt = new MapDS.LatLng(Number(_SELF._foundLocations[idx].Position.Latitude), Number(_SELF._foundLocations[idx].Position.Longitude));
                                _SELF.findNearest(_SELF._foundLocations[idx], idx);
                            } else {
                                _SELF.addCoords(_SELF._foundLocations[idx], k);
                            }
                        }
                        $(this).dialog('close');
                    },
                    Cancel: function() { $(this).dialog('close'); }
                }
            });

            // handle the resizing of the browser window.
            var currentMapWidth = $(_SELF.getElementID(_SELF.ElementIDs.Map)).width();
            var currentMapHeight = $(_SELF.getElementID(_SELF.ElementIDs.Map)).height();
            $(window).wresize(function() {
                /*var w = $( window );
                var H = w.height();
                var W = w.width();*/
                var mW = $(_SELF.getElementID(_SELF.ElementIDs.Map)).width();
                var mH = $(_SELF.getElementID(_SELF.ElementIDs.Map)).height();
                if (mW !== currentMapWidth || mH !== currentMapHeight) {
                    currentMapWidth = mW;
                    currentMapHeight = mH;
                    if (_SELF.map instanceof MapDS.Maps.Map) {
                        _SELF.map.setCentre(_SELF.map.getCentre(), _SELF.map.getZoom(), true);
                    }
                }
            });

            // show fuel loc checkbox changes
            $("#fuelLoc").click(function() {

                if ($('#fuelLoc').attr('checked') == true) {
                    $('#ddlService').val('Service station');
                    $('#ddlService').trigger('change');
                }
                else {
                    $(_SELF.getElementID(_SELF.ElementIDs.FiltersList)).html('<b>Please select ‘show fuel locations’ above to see available refine filters</b>');
                }

            });

            //filter dropdown changes
            $("#ddlService").change(function() {
                $(_SELF.getElementID(_SELF.ElementIDs.FiltersButton)).addClass("menu-open");
                $(_SELF.getElementID(_SELF.ElementIDs.POIsButton)).removeClass("menu-open");
                $(_SELF.getElementID(_SELF.ElementIDs.DirectionsButton)).removeClass("menu-open");

                var selectedFilterType = $("#ddlService").val();
                var filtershtml = "";
     

                if (selectedFilterType == "Service station") {

                    //if nz selected

               if (Locator.country == "NZ") {
                        filtershtml = "<h2>Outlet type</h2><table>";
                        filtershtml = filtershtml + addFilterRow('BP', 'BP', 'Caltex', 'Caltex', '1');
                        filtershtml = filtershtml + addFilterRow('Shell', 'Shell', 'Mobil', 'Mobil', '1');
                        //filtershtml = filtershtml + addFilterRow('Gull', 'Gull', 'G.A.S', 'GAS', '1');
                        filtershtml = filtershtml + "</table><h2>Fuel Type</h2><table>";
                        filtershtml = filtershtml + addFilterRow('Unleaded', 'Unleaded 91', 'PremiumUnleaded', 'Premium Unleaded', '2');
                        filtershtml = filtershtml + addFilterRow('Diesel', 'Diesel', 'Autogas', 'LPG', '2');
                        // filtershtml = filtershtml + addFilterRow('CNG', 'CNG', 'SuperDiesel', 'Bio Diesel', '2');
                        filtershtml = filtershtml + addFilterRow('SuperDiesel', 'Bio Diesel', '', '', '2');
                        filtershtml = filtershtml + "</table><h2>Other Services</h2><table>";
                        filtershtml = filtershtml + addFilterRow('Carwash', 'Car wash', 'Restaurant', 'Cafe/Food', '3');
                    }
                    else {
                        //if default or AU
  
                        filtershtml = "<h2>Outlet type</h2><table>";
                        filtershtml = filtershtml + addFilterRow('Shell', 'Shell', 'Ampol', 'Ampol', '1');
                        filtershtml = filtershtml + addFilterRow('BP', 'BP', 'Mobil', 'Mobil', '1');
                        filtershtml = filtershtml + addFilterRow('Caltex', 'Caltex', 'Independent', 'Independent', '1');
                        filtershtml = filtershtml + "</table><h2>Fuel Type</h2><table>";
                        filtershtml = filtershtml + addFilterRow('Unleaded', 'Unleaded', 'Diesel', 'Diesel', '2');
                        filtershtml = filtershtml + addFilterRow('PremiumUnleaded', 'Premium unleaded', 'Autogas', 'LPG', '2');
                        filtershtml = filtershtml + "</table><h2>Other Services</h2><table>";
                        filtershtml = filtershtml + addFilterRow('carwash', 'Car wash', 'Detailing', 'Detailing', '3');
                    }
                }



                else if (selectedFilterType == "Car wash") {
                    filtershtml = "<div class='errMsg'>There are no refine search filters available for this service type</div>";
                }
                else if (selectedFilterType == "Smash repairs") {
                    filtershtml = "<h2>Site Type</h2><table>";
                    filtershtml = filtershtml + addFilterRow('AccMmentPre', 'Accident Management', '', '', '1');
                }
                else if (selectedFilterType == "Repairs") {
                    filtershtml = "<h2>Outlet type</h2><table>";
                    filtershtml = filtershtml + addFilterRow('KmartTyreAuto', 'Kmart Tyre &amp; Auto', 'Ultratune', 'Ultratune', '1');
                    filtershtml = filtershtml + "<tr colspan=2><td><h2>Services</h2></td></tr>";
                    filtershtml = filtershtml + addFilterRow('AlarmRadioAirCon', 'Alarm, Radio &amp; Air-conditioning', 'AutoElec', 'Auto Electrical', '2');
                    filtershtml = filtershtml + addFilterRow('AutoTrans', 'Auto Transmission', 'Batteries', 'Batteries', '2');
                    filtershtml = filtershtml + addFilterRow('BrakeClutch', 'Brake &amp; Clutch', 'Exhaust', 'Exhaust', '3');
                    filtershtml = filtershtml + addFilterRow('LPGFittingMaintenance', 'LPG Fitting &amp; Maintenance', 'MobileService', 'Mobile Service', '2');
                    filtershtml = filtershtml + addFilterRow('RadiatorRepairs', 'Radiator Repairs', 'Windowtinting', 'Window Tinting', '2');
                    filtershtml = filtershtml + addFilterRow('Towing', 'Towing', '', '', '2');
                }
                else if (selectedFilterType == "Motor dealership") {
                    filtershtml = "<h2>Brand</h2><table>";
                    filtershtml = filtershtml + addFilterRow('Ford', 'Ford', 'Holden', 'Holden', '1');
                    filtershtml = filtershtml + addFilterRow('Honda', 'Honda', 'Hyundai', 'Hyundai', '1');
                    filtershtml = filtershtml + addFilterRow('Mazda', 'Mazda', 'Mitsubishi', 'Mitsubishi', '1');
                    filtershtml = filtershtml + addFilterRow('Nissan', 'Nissan', 'Subaru', 'Subaru', '1');
                    filtershtml = filtershtml + addFilterRow('Toyota', 'Toyota', 'Volkswagon', 'VW', '1');
                    filtershtml = filtershtml + "<tr><td><h2><div class=\"clickable\"><a href = \"javascript:Locator.toggleHidden();\" class=\"showMore\"> Show more...</a></div></h2></td><td></td></tr>"
                    filtershtml = filtershtml + addFilterRow('AlfaRomeo', 'Alfa Romeo', 'Audi', 'Audi', '1', true);
                    filtershtml = filtershtml + addFilterRow('BMW', 'BMW', 'Chrysler', 'Chrysler', '1', true);
                    filtershtml = filtershtml + addFilterRow('Citroen', 'Citroen', 'Daewoo', 'Daewoo', '1', true);
                    filtershtml = filtershtml + addFilterRow('Daihatsu', 'Daihatsu', 'Eunos', 'Eunos', '1', true);
                    filtershtml = filtershtml + addFilterRow('Freightliner', 'Freightliner', 'Hino', 'Hino', '1', true);
                    filtershtml = filtershtml + addFilterRow('International', 'International', 'Isuzu', 'Isuzu', '1', true);
                    filtershtml = filtershtml + addFilterRow('Jaguar', 'Jaguar', 'Kenworth', 'Kenworth', '1', true);
                    filtershtml = filtershtml + addFilterRow('Kia', 'Kia', 'LandRover', 'LandRover', '1', true);
                    filtershtml = filtershtml + addFilterRow('Lexus', 'Lexus', 'Mack', 'Mack', '1', true);
                    filtershtml = filtershtml + addFilterRow('MercedesBenz', 'Mercedes Benz', 'UDNissan', 'UD Nissan', '1', true);
                    filtershtml = filtershtml + addFilterRow( 'Peugeot', 'Peugeot', 'Porsche', 'Porsche', '1', true);
                    filtershtml = filtershtml + addFilterRow( 'Proton', 'Proton', 'Renault', 'Renault',  '1', true);
                    filtershtml = filtershtml + addFilterRow('Rover', 'Rover', 'Saab', 'Saab', '1', true);
                    filtershtml = filtershtml + addFilterRow('Scania', 'Scania', 'Seat', 'Seat', '1', true);
                    filtershtml = filtershtml + addFilterRow( 'Ssangyong', 'Ssangyong', 'Suzuki', 'Suzuki', '1', true);
                    filtershtml = filtershtml + addFilterRow( 'Volvo', 'Volvo', 'WesternStar', 'WesternStar', '1', true);
                    $('.hideable').hide();
                }
                else if (selectedFilterType == "Tyres") {
                    filtershtml = "<h2>Outlet Type</h2><table>";
                    filtershtml = filtershtml + addFilterRow('Beaurepaires', 'Beaurepaires', 'BobJane', 'Bob Jane', '1');
                    filtershtml = filtershtml + addFilterRow('BoralTyres', 'Boral Tyres', 'Bridgestone', 'Bridgestone', '1');
                    filtershtml = filtershtml + addFilterRow('Goodyear', 'Goodyear', 'IanDiffen', 'Ian Diffen', '1');
                    filtershtml = filtershtml + addFilterRow('KmartTyreAuto', 'Kmart Tyre &amp; Auto', 'MarshallBatteries', 'Marshall Batteries', '1');
                    filtershtml = filtershtml + addFilterRow('McLeodTyres', 'McLeod Tyres', 'MidasMufflers', 'Midas Mufflers', '1');
                    filtershtml = filtershtml + addFilterRow('PeddersSuspension', 'Pedders Suspension', 'Tyrepower', 'Tyrepower', '1');
                    filtershtml = filtershtml + addFilterRow('Ultratune', 'Ultratune', 'Jax', 'Jax', '1');
                    filtershtml = filtershtml + addFilterRow('InstantWindscreens', 'Instant Windscreens', 'AustAutoglass', 'Australian Autoglass', '1');
                    filtershtml = filtershtml + addFilterRow('ProtectorWindscreens', 'Protector Windscreens', 'Novus', 'Novus', '1');
                    filtershtml = filtershtml + addFilterRow('WindscreensOBrien', 'Windscreens O’Brien', '', '', '1');
                    filtershtml = filtershtml + "</table><h2>Services</h2><table>";
                    filtershtml = filtershtml + addFilterRow('Tyres', 'Tyres', 'Batteries', 'Batteries', '2');
                    filtershtml = filtershtml + addFilterRow('Windscreens', 'Windscreens', 'Windowtinting', 'Window tinting', '2');
                }

                else if (selectedFilterType == "none") {
                    filtershtml = "<b>Options to refine your search will automatically appear here after you select a service above</b>";
                }
                if (selectedFilterType != "none" && selectedFilterType != "Car wash") {
                    filtershtml = filtershtml + "</table><div><input type=button id='btnApply' title='search'  value='Apply' OnClick='javascript:Locator.applyFilters();' /></div>";
                }
                _SELF.toggleDropdown(1);
                $(_SELF.getElementID(_SELF.ElementIDs.FiltersList)).html(filtershtml);
                $(_SELF.getElementID(_SELF.ElementIDs.FiltersList)).show();
            });

            $(".showMore").click(function() {
                $('.hideable').show();
            });

            $("#ddlNzService").click(function() {
                $(_SELF.getElementID(_SELF.ElementIDs.FiltersButton)).addClass("menu-open");
                $(_SELF.getElementID(_SELF.ElementIDs.POIsButton)).removeClass("menu-open");
                $(_SELF.getElementID(_SELF.ElementIDs.DirectionsButton)).removeClass("menu-open");

                var selectedFilterType = $("#ddlNzService").val();
                var filtershtml = "";
                if (selectedFilterType == "Service station") {
                    filtershtml = "<h2>Outlet type</h2><table>";
                    filtershtml = filtershtml + addFilterRow('BP', 'BP', 'Caltex', 'Caltex', '1');
                    filtershtml = filtershtml + addFilterRow('Shell', 'Shell', 'Mobil', 'Mobil', '1');
                    //filtershtml = filtershtml + addFilterRow('Gull', 'Gull', 'G.A.S', 'GAS', '1');
                    filtershtml = filtershtml + "</table><h2>Fuel Type</h2><table>";
                    filtershtml = filtershtml + addFilterRow('Unleaded', 'Unleaded 91', 'PremiumUnleaded', 'Premium Unleaded', '2');
                    filtershtml = filtershtml + addFilterRow('Diesel', 'Diesel', 'Autogas', 'LPG', '2');
                    // filtershtml = filtershtml + addFilterRow('CNG', 'CNG', 'SuperDiesel', 'Bio Diesel', '2');
                    filtershtml = filtershtml + addFilterRow('SuperDiesel', 'Bio Diesel', '', '', '2');
                    filtershtml = filtershtml + "</table><h2>Other Services</h2><table>";
                    filtershtml = filtershtml + addFilterRow('Carwash', 'Car wash', 'Restaurant', 'Cafe/Food', '3');
                }
                else if (selectedFilterType == "Car wash") {
                    filtershtml = "<div class='errMsg'>There are no refine search filters available for this service type</div>";
                }
                else if (selectedFilterType == "Panelbeaters") {
                    filtershtml = "<div class='errMsg'>There are no refine search filters available for this service type</div>";
                }

                else if (selectedFilterType == "Repairs") {
                    filtershtml = "<h2>Services</h2><table>";
                    filtershtml = filtershtml + addFilterRow('AlarmRadioAirCon', 'Alarm, Radio &amp; Air-conditioning', 'AutoElec', 'Auto Electrical', '1');
                    filtershtml = filtershtml + addFilterRow('AutoTrans', 'Auto Transmission', 'Batteries', 'Batteries', '1');
                    filtershtml = filtershtml + addFilterRow('BrakeClutch', 'Brake &amp; Clutch', 'Exhaust', 'Exhaust', '1');
                    filtershtml = filtershtml + addFilterRow('LPGFittingMaintenance', 'LPG Fitting &amp; Maintenance', 'MobileService', 'Mobile Service', '1');
                    filtershtml = filtershtml + addFilterRow('RadiatorRepairs', 'Radiator Repairs', 'Windowtinting', 'Windowtinting', '1');
                    filtershtml = filtershtml + addFilterRow('Towing', 'Towing', 'ScheduledService', 'Scheduled service', '1');
                    filtershtml = filtershtml + addFilterRow('Detailing', 'Grooming/detailing', '', '', '1');
                }
                else if (selectedFilterType == "Motor dealership") {
                    filtershtml = "<h2>Brand</h2><table>";
                    filtershtml = filtershtml + addFilterRow('Ford', 'Ford', 'Holden', 'Holden', '1');
                    filtershtml = filtershtml + addFilterRow('Honda', 'Honda', 'Hyundai', 'Hyundai', '1');
                    filtershtml = filtershtml + addFilterRow('Mazda', 'Mazda', 'Mitsubishi', 'Mitsubishi', '1');
                    filtershtml = filtershtml + addFilterRow('Nissan', 'Nissan', 'Subaru', 'Subaru', '1');
                    filtershtml = filtershtml + addFilterRow('Suzuki', 'Suzuki', 'Toyota', 'Toyota', '1');
                    filtershtml = filtershtml + "<tr><td><h2><div class=\"clickable\"><a href = \"javascript:Locator.toggleHidden();\" class=\"showMore\"> Show more...</a></div></h2></td><td></td></tr>"
                    filtershtml = filtershtml + addFilterRow('AlfaRomeo', 'Alfa Romeo', 'Audi', 'Audi', '1', true);
                    filtershtml = filtershtml + addFilterRow('BMW', 'BMW', 'Chrysler', 'Chrysler', '1', true);
                    filtershtml = filtershtml + addFilterRow('Citroen', 'Citroen', 'Daihatsu', 'Daihatsu', '1', true);
                    filtershtml = filtershtml + addFilterRow('Dodge', 'Dodge', 'Freightliner', 'Freightliner', '1', true);
                    filtershtml = filtershtml + addFilterRow('GreatWall', 'Great Wall', 'Hino', 'Hino', true);
                    filtershtml = filtershtml + addFilterRow('International', 'International', 'Isuzu', 'Isuzu', '1', true);
                    filtershtml = filtershtml + addFilterRow('Jaguar', 'Jaguar', 'Jeep', 'Jeep', '1', true);
                    filtershtml = filtershtml + addFilterRow('Kenworth', 'Kenworth', 'Kia', 'Kia', '1', true);
                    filtershtml = filtershtml + addFilterRow('LandRover', 'LandRover', 'Lexus', 'Lexus', '1', true);
                    filtershtml = filtershtml + addFilterRow('Mack', 'Mack', 'MercedesBenz', 'Mercedes Benz', '1', true);
                    filtershtml = filtershtml + addFilterRow('UDNissan', 'UD Nissan', 'Peugeot', 'Peugeot', '1', true);
                    filtershtml = filtershtml + addFilterRow('Porsche', 'Porsche', 'Proton', 'Proton', '1', true);
                    filtershtml = filtershtml + addFilterRow('Renault', 'Renault', 'Rover', 'Rover', '1', true);
                    filtershtml = filtershtml + addFilterRow('Saab', 'Saab', 'Scania', 'Scania', '1', true);
                    filtershtml = filtershtml + addFilterRow('Seat', 'Seat', 'Ssangyong', 'Ssangyong', '1', true);
                    filtershtml = filtershtml + addFilterRow('Suzuki', 'Suzuki', 'Volvo', 'Volvo', '1', true);
                    filtershtml = filtershtml + addFilterRow('WesternStar', 'WesternStar', 'Volkswagon', 'VW', '1', true);
                }
                else if (selectedFilterType == "Tyres") {
                    filtershtml = "<h2>Services</h2><table>";
                    filtershtml = filtershtml + addFilterRow('Tyres', 'Tyres', 'MarshallBatteries', 'Batteries', '1');
                    filtershtml = filtershtml + addFilterRow('Windscreens', 'Windscreens', 'Windowtinting', 'Window tinting', '1');
                    filtershtml = filtershtml + "</table><h2>Outlet Type</h2><table>";
                    filtershtml = filtershtml + addFilterRow('Bridgestone', 'Bridgestone', 'Firestone', 'Firestone', '2');
                    filtershtml = filtershtml + addFilterRow('MarshallBatteries', 'Marshall batteries', 'SmithAutoglass', 'Smith & Smith autoglass', '2');
                }
                else if (selectedFilterType == "Accessories") {
                    filtershtml = "<h2>Services</h2><table>";
                    filtershtml = filtershtml + addFilterRow('Canopy', 'Canopy', 'Fitout', 'Van fitout', '1');
                    filtershtml = filtershtml + addFilterRow('Signage', 'Signage', 'Bluetooth', 'Bluetooth', '1');
                    filtershtml = filtershtml + addFilterRow('Alloys', 'Alloys', 'Upholstry', 'Upholstery Leather', '1');
                    filtershtml = filtershtml + addFilterRow('Towbars', 'Towbars / Bullbars', 'FlatDecks', 'Flat Decks', '1');
                }
                else if (selectedFilterType == "WOF/COF/RUC") {
                    filtershtml = "</table><h2>Outlet Type</h2><table>";
                    filtershtml = filtershtml + addFilterRow('VTNZ', 'Vehicle Testing NZ (VTNZ)', '', '', '1');
                    filtershtml = filtershtml + "<h2>Services</h2><table>";
                    filtershtml = filtershtml + addFilterRow('WOF', 'Warrant of fitness', 'COF', 'Certificate of Fitness', '2');
                    filtershtml = filtershtml + addFilterRow('RUC', 'Road User Charges', '', '', '2');
                }
                else if (selectedFilterType == "Trucks") {
                    filtershtml = "</table><h2>Outlet Type</h2><table>";
                    filtershtml = filtershtml + addFilterRow('TruckStop', 'Truck Stops', '', '', '1');
                    filtershtml = filtershtml + "<h2>Services</h2><table>";
                    filtershtml = filtershtml + addFilterRow('ScheduledServiceTrucks', 'Routine service', 'Maintenance', 'Maintenance', '2');
                    filtershtml = filtershtml + addFilterRow('Repairs', 'Repairs', '', '', '2');
                }
                else if (selectedFilterType == "none") {
                    filtershtml = "<b>Options to refine your search will automatically appear here after you select a service above</b>";
                }
                if (selectedFilterType != "none" && selectedFilterType != "Car wash" && selectedFilterType != "Panelbeaters") {
                    filtershtml = filtershtml + "</table><div><input type=button id='btnApply' title='search' value='Apply' OnClick='javascript:Locator.applyFilters();' /></div>";
                }
                _SELF.toggleDropdown(1);
                $(_SELF.getElementID(_SELF.ElementIDs.FiltersList)).html(filtershtml);
                $(_SELF.getElementID(_SELF.ElementIDs.FiltersList)).show();

            });

            function silentErrorHandler() { return true; }
            window.onerror = silentErrorHandler;

            function setLastLocatorSearchType() {
                if (Locator.country == "AU") {
                    Locator.LastLocatorSearchType = $("#ddlService").val();
                } else {
                    Locator.LastLocatorSearchType = $("#ddlNzService").val();
                }
            }


            function addFilterRow(val1, display1, val2, display2, group, hideable) {
                var html = "";
                if (hideable) {
                    html = "<tr class='hideable'><td class='filterCol'><label><input type='checkbox' name='{4}' value='{0}' />{1}</label></td><td class='filterCol'>".format(val1, display1, val2, display2, group);

                } else {
                    var html = "<tr><td class='filterCol'><label><input type='checkbox'  name='{4}' value='{0}' />{1}</label></td><td class='filterCol'>".format(val1, display1, val2, display2, group);
                }
                if (val2 != '') {
                    html = html + "<label><input type='checkbox' name='{2}' value='{0}' />{1}</label></td></tr>".format(val2, display2, group);
                }
                else {
                    html = html + "</td></tr>"
                }
                return html;
            }
            function getUrlVars() {
                var vars = [], hash;
                var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                for (var i = 0; i < hashes.length; i++) {
                    hash = hashes[i].split('=');
                    vars.push(hash[0]);
                    vars[hash[0]] = hash[1];
                }
                return vars;
            }



            // Initiate sortable functionality
            $(function() {
                $(_SELF.getElementID(_SELF.ElementIDs.TripFieldsInputs)).sortable({
                    axis: 'y',
                    stop: function(event, ui) { addFields.updateTripFields(); _SELF.updateTrip(); }
                });
            });

            _SELF.reset();
            // need to wrap the call in a function so we can maintain scope
            window.onload = function() {
                _SELF.initMap.apply(_SELF);
            };
            _SELF.toggleDropdown(0);
        });
    }
};
Locator.init();


