//contains any js helper functions to do with the map
var map, mapIsSet, popup, geocoder, itin, itinList, routeManager,selectedCarParkId,selectedCarPark, selectedCarParkAddress, poiPopup, cpPopup, mapType, cityid, citySelected, regionid, regionSelected, poiselected, servicesfilter, streetAddress, suburbAddress, stateAddress, carParksOnMap, routeDirection, prevPage, startZoomLevel, geocodeErrorMessage, possibleRouteAddressList, selectedHomeAddress, possibleHomeAddressList, carParksNearbyShown, rtHandle;

mapIsSet = false;
selectedCarParkId = 0;
mapType = "city";
prevPage = '';
routeDirection = 'from';
servicesfilter = new Array();
carParksOnMap = new Array(); //contains an array of carparks currently visible on the map
itinList = new Array();
possibleRouteAddressList = new Array();
possibleHomeAddressList = new Array();
geocodeErrorMessage = '';
carParksNearbyShown = false; //whether carparks nearby are shown
startZoomLevel = 16 // the zoom level to start at

function createMap(div, enableZoom) {

    map = new EMS.Services.Map(div, 
        {controls:
            [
            new EMS.Control.Scale(),
            new EMS.Control.Copyright()
            ]
        });
    
    if (enableZoom) {    
        map.addControl(new EMS.Control.ZoomBar(map.whereis_street_wms,map.whereis_photo_wms, map.whereis_hybrid_wms));
        map.addControl(new EMS.Control.MouseDefaults());
        map.addControl(new EMS.Control.PanButton('e'));
        map.addControl(new EMS.Control.PanButton('n'));
        map.addControl(new EMS.Control.PanButton('w'));
        map.addControl(new EMS.Control.PanButton('s'));
    }

    itin = new EMS.Services.Itin();
    geocoder = new EMS.Services.Geocoder();
    routeManager = new EMS.Services.RouteManager(map); 
}


//centres the map on the passed longitude and latitudes in WGS84 coordinates
function centreMap(lon, lat) {
    map.setCenter(new EMS.LonLat(lon, lat));
}

//helper function to see if a WGS 84 long/lat coordinate is on the map at this zoom
function isLonLatInView(longitude, latitude) {
    var bounds = map.getExtent();
    pointLonLat = new EMS.LonLat(longitude, latitude);
    
    return bounds.containsLonLat(pointLonLat);
}

//helper function to set the zoom level of the map
function setZoom(zoomLevel) {
    if (map) {
        map.zoomTo(zoomLevel);
    }
}

//helper function to set the lat, long and zoom of the map
function setMapView(longitude, latitude, zoom) {
    setZoom(zoom);
    centreMap(longitude, latitude);
}

//map setup
function initialiseMap() {
    //hide routing div
    $('#detailed-route').hide();
    
    //get map setup vars
    $('#map-content :input').each(function() {
        switch (this.id.toLowerCase()) {
            case 'selectedcarparkid' :
                selectedCarParkId = this.value;
            break;
            
            case 'cityid' :
                cityid = this.value;
            break;
            
            case 'regionid' :
                regionid = this.value;
            break;
            
            case 'maptype' :
                mapType = this.value;
            break;
            
            case 'poiselected' :
                poiselected = this.value;
            break;
            
            case 'servicesfilter' :
                $(this.value.replace(' ','').split(',')).each(function () {
                    if (this.length > 0 && !isNaN(this)) {
                        servicesfilter.push(this);
                    }
                });
            break;
            
            case 'streetaddress' :
                streetAddress = this.value;
            break;
            
            case 'suburbaddress' :
                suburbAddress = this.value;
            break;
            
            case 'stateaddress' :
                stateAddress = this.value;
            break;
            
            case 'routedirection' :
                routeDirection = this.value.toLowerCase() == 'to' ? 'to' : 'from';    
            break;
            
            case 'prevpage' :
                prevPage = this.value;
            break
        }
    });

    
    
    if (!mapType) {
        mapType = "city";
    }
    
    
    
    ///******************************///
    ///                              ///
    /// This section is the setup    ///
    //  of each different type of    ///
    /// map.                         ///
    ///                              ///
    ///******************************///
    switch(mapType.toLowerCase()){
        
        case "city" :
            createMap('mapdiv', false);
            
            //add the cities on to the map
            for (var i=0;i<cityArray.length;i++) {
                if ((cityArray[i].longitude) && (cityArray[i].latitude)) {               
                
                    var lonlat = new EMS.LonLat(cityArray[i].longitude, cityArray[i].latitude);
                    addCarParkMarker(lonlat, cityArray[i], true);
                }
            }
            addPointerCursors();
            
        break;
        
        case "region" :
        
        
        //set the zoom level and location for this city
        citySelected = findCityById(cityid);
        
        if (citySelected) {
            if (citySelected.staticmap) {
                var img = document.createElement('img');
                img.src = citySelected.altimage;
                img.alt = citySelected.alttext;
                $('#mapdiv').append(img);
            }
            else
            {
                createMap('mapdiv', true);
                setMapView(citySelected.longitude, citySelected.latitude, citySelected.zoomlevel);
                showAllCarParks(false);
                addPointerCursors();
            }
        }
            
        break;
        
        case "carparklist" :

        
        //set the zoom level and location for this city.       
        if (regionSelected) {
            if (regionSelected.staticmap) {
                var img = document.createElement('img');
                img.src = regionSelected.altimage;
                img.alt = regionSelected.alttext;
                $('#mapdiv').append(img);
                
                //hide the poi search     
                $('#regionPoiHeader').hide();
                $('#regionPoiModule').hide();
                
                //hide the advanced tools
                $('#advancedTools').hide();   
                
                //add the carparks in the region to the sidebar
                AddRegionalCarParks();
            }
            else { 
                //use the whereis map
                createMap('mapdiv', true);
                setMapView(regionSelected.longitude, regionSelected.latitude, regionSelected.zoomlevel);
                
                //show filter cancel if there is a filter
                if (servicesfilter.length > 0) {
                    $('#advancedTools').show();
                } else {
                    $('#advancedTools').hide();
                }
                AddRegionalCarParks();
                
                //initially hide the not found div
                var poiNotFoundDiv = $('#poiNotFoundCP');
                if (poiNotFoundDiv) {
                    poiNotFoundDiv.hide();
                }
                
                //if there is a poi requested, add it
                if (poiselected.length > 0)
                {
                    //try to set the ddl to the val
                    var ddl = document.getElementById('placeofinterestCP');
                    if (ddl) {
                        for (var i=0;i<ddl.options.length;i++) {
                            if (ddl.options[i].text.toLowerCase() == poiselected.toLowerCase()) {
                                ddl.options[i].selected = true;
                            }
                        }
                    }
                    
                    displayPOI();
                }
                
                $('#btnCarParkListShowPOI').click(function() {
                    displayPOI();
                    return false;
                });
                
                $('#clearFilter').click(function() {
                    $('#advancedTools').hide();
                    servicesfilter.length = 0;
                    AddRegionalCarParks();
                });
                
                addPointerCursors();
            }
        }
        else
        {
            $('#mapdiv').innerHTML = "Sorry, this region map cannot be found.";
            return;
        }
         
        break;
    
        case "carpark" :
            var imagePath = "";
            var poiNotFoundDiv = $('#poiNotFound');
            if (poiNotFoundDiv) {
                poiNotFoundDiv.hide();
            }
            
            $('#carparkNearbyHeader').hide();
            $('#carparkNearbyModule').hide();
        
            selectedCarPark = findCarParkById(selectedCarParkId);
            if (selectedCarPark == null)
            {
                $('#mapdiv').html('<div class="maperror">Sorry but this car park is not available. Please try again using our handy <a href="citymap.aspx">Find Parking Tool</a>.</div>');
            }
            else
            {     
                   
                //show the route to and from links
                var linkTo = $('#routeto');
                if (linkTo) {
                    linkTo.click(function() {
                        document.location.href = "route.aspx?carparkid=" + selectedCarPark.identity + "&direction=to&prev=2";
                        return false;
                    });
                }
                var linkFrom = $('#routefrom');
                if (linkFrom) {
                    linkFrom.click(function() {
                        document.location.href = "route.aspx?carparkid=" + selectedCarPark.identity + "&direction=from&prev=2";
                        return false;
                    });
                }
                
                if (selectedCarPark.staticmap) //use the default map, not the whereis map
                {
                    if (document.location.href.indexOf("preview=1") > -1)
                    {
                        imagePath = "cmsimages/previews/";
                    }
                    else
                    {
                        imagePath = "cmsimages/carparks/";
                    }
                    
                    var img = document.createElement('img');
                    img.alt = selectedCarPark.alttext;
                    img.src = imagePath + selectedCarPark.defaultimage;
                    img.id = "carparkImage";
                    $('#mapdiv').append(img);
                    
                    //hide the whereis map specific info
                    $('#map-sidebar').hide();
                }
                else
                {
                    createMap('mapdiv', true);
                    setMapView(selectedCarPark.maplongitude, selectedCarPark.maplatitude, selectedCarPark.zoomlevel);
                    
                    var lonlat = new EMS.LonLat(selectedCarPark.longitude, selectedCarPark.latitude);
                    addCarParkMarker(lonlat, selectedCarPark, false);
                    //add the events for searching
                    $('#btnCarparkPOISearch').click(function() {
                        displayPOI();
                        return false;
                    });
                    
                    $('#btnShowNearbyCarParks').click(function() {
                        showNearByCarParks();
                        addPointerCursors();
                        return false;
                    });
                    
                    $('#btnResetCarParkMap').click(function() {
                        resetCarParkMap();
                        addPointerCursors();
                        return false;
                    });
                    
                    
                }
            }
        break;
        
        case 'streetsearch' :
            createMap('mapdiv', true);            
            
            //do the search on loading if all was specified.
            if (validateAddress()) {
                doAddressSearch();   
            }
            else
            {
                $('#streetSearchError').html(geocodeErrorMessage);
            }
            
            $('#btnStreetSearchConfirmAddress').click(function() {                        
                        $('#divStreetSearchPossibleAddress ul li :checked').each(function() {
                            var selectedId = '';
                            if (this.checked) {
                                selectedId = this.id;
                            }
                            
                            if (selectedId != '') {
                                
                                var addressId = this.id.substring(21);
                                selectedHomeAddress = possibleHomeAddressList[addressId];
                                $('#divStreetSearchAddressList').hide();
                                showHomeAddress();
                                return false;
                            }
                            
                        });
                        
                        return false;
                    });
            
           
            
        break;
        
        case 'route' :
        
            //hide the printmap div for init
            if ($('#mapdivprintview')) { $('#mapdivprintview').hide(); }
            
            //if no prev page, hide the cancel button
            if (prevPage.length == 0) {
                $('#routeButtons #routeCancel').hide();
            }
            
            $('#divAddressConfirmation').hide();
            
            selectedCarPark = findCarParkById(selectedCarParkId);
            if (!selectedCarPark || typeof selectedCarPark == 'undefined')
            {
                $('#mapdiv').html('<div class="maperror">Sorry, this car park map cannot be found. Please try again using our handy <a href="citymap.aspx">Find Parking Tool</a>.</div>');
            }
            else
            {
                if (selectedCarPark.staticmap) { 
                    $('#mapdiv').html('<div class="maperror">Sorry, routing is not possible with this car park.</div>');
                }
                else
                {
                    
                    createMap('mapdiv', true);
                    setMapView(selectedCarPark.maplongitude, selectedCarPark.maplatitude, selectedCarPark.zoomlevel);
                    
                    var lonlat = new EMS.LonLat(selectedCarPark.longitude, selectedCarPark.latitude);
                    addCarParkMarker(lonlat, selectedCarPark, false);
                    $('#pCarParkAddress').html(selectedCarPark.getShortDetails());
                    
                    //no state stored so have a go at finding it from postcode
                    var cpstate = '';
                    
                    if (selectedCarPark.postcode && selectedCarPark.postcode.length > 0) {
                        switch (selectedCarPark.postcode.substring(0,1)) {
                            
                            case "2" :
                                cpstate = 'NSW';
                                break;
                            
                            case "3" :
                                cpstate = 'VIC';
                                break;
                                
                            case "4" :
                                cpstate = 'QLD';
                                break;
                                
                            case "5" :
                                cpstate = 'SA';
                                break;
                        
                        }
                    } 
                   
                    //get the geocode of the carpark and store it //selectedCarPark.street
                    geocoder.findAddress(
                        selectedCarPark.street, 
                        selectedCarPark.suburb,
                        cpstate, 
                        processCarParkSearch);
                    
                    //add it to selectedCarParkAddress
                    
                    var headerText = 'Choose your ';
                    var addressText = 'Your ';
                    var headerConfirmText = 'Confirm your ';
                    
                    switch (routeDirection.toLowerCase()) {
                        case 'to' :
                            headerText += 'start';
                            addressText += 'destination';
                            headerConfirmText += 'start';
                            
                            //show the avoid tolls box
                            $('#olAvoidTolls').show();                          
                        break;
                        
                        case 'from' :
                            headerText += 'destination';
                            addressText += 'start';
                            headerConfirmText += 'destination'; 
                            
                            //hide the avoid tolls box for walking
                            $('#olAvoidTolls').hide();    
                        break;
                    }     
                    
                    headerText += ' address';
                    addressText += '  address:';
                    headerConfirmText += '  address:';
                    
                    if (routeDirection.toLowerCase() == 'from') {
                        //headerText += '<br/>NOTE : YOU WILL ONLY BE ABLE TO CREATE A WALKING ROUTE WITHIN 10KM OF THE CARPARK';
                        headerText += '<br/>Note : You will only be able to create a walking route within 10km of the carpark';
                    }

                    $('#legendRoute').text(headerText);
                    $('#headerRoute').html(headerText);
                    $('#carparkAddress #headerCarParkAddress').html(addressText);
                    $('#divAddressConfirmation #headerAddressConfirmation').html(headerConfirmText);
                    
                    var cpText = selectedCarPark.name + ', ';
                    cpText += selectedCarPark.street + ', ';
                    cpText += selectedCarPark.suburb + ', ';
                    cpText += selectedCarPark.postcode + ', ';
                    
                    if (cpText.substring(selectedCarPark.length - 2) == ', ') {
                        cpText = cpText.substring(0, selectedCarPark.length - 2)
                    }
                    
                    
                    $('#routeSideBar #pCarParkAddress').html(cpText);
                    
                    
                    //add the clearing events to the text fields
                    $('#addressform #street').focus(function() {
                        if ($('#addressform #street').val().toLowerCase() == 'street') {
                            $('#addressform #street').val('');
                        }
                    }); 

                    $('#addressform #suburb').focus(function() {
                        if ($('#addressform #suburb').val().toLowerCase() == 'suburb') {
                            $('#addressform #suburb').val('');
                        }
                    });

                    //and the resetting events
                    $('#addressform #street').blur(function() {
                        if ($('#addressform #street').val() == '') {
                            $('#addressform #street').val('Street');
                        }
                    }); 

                    $('#addressform #suburb').blur(function() {
                        if ($('#addressform #suburb').val() == '') {
                            $('#addressform #suburb').val('Suburb');
                        }
                    }); 
                    
                    $('#routeButtons #routeView').click(function() {
                    
                        //reset the map view if print view has been shown previously
                        $('#mapdivprintview').hide();
                        $('#mapdiv').show();
                    
                        streetAddress = $('#addressform #street').val();
                        suburbAddress = $('#addressform #suburb').val();
                        stateAddress = $('#addressform #stateList').val();
                        if (validateAddress()) {
                                                        
                            //do the geocode on this address
                            geocoder.findAddress(
                                streetAddress, 
                                suburbAddress,
                                stateAddress, 
                                processRouteSearch);

                        }
                        else
                        {
                            $('#routeError').html(geocodeErrorMessage);
                        }
                        
                        return false;
                    });
                    
                    $('#routeButtons #routeCancel').click(function() {
                        if (prevPage.length > 0) {
                            var url = document.location.href;
                            var urlArr = url.split('//');                            
                            var hostNameArr = urlArr[1].split('/');
                            
                            var host = urlArr[0] + "//" + hostNameArr[0];
                            var redirectUrl = host + (prevPage[0] == "/" ? prevPage : "/" + prevPage);
                            document.location.href=redirectUrl;
                            return false;
                        }
                    });
                    
                    $('#addressConfirmButtons #routeConfirm').click(function() {                        
                        $('#divPossibleAddress ul li :checked').each(function() {
                            var selectedId = '';
                            if (this.checked) {
                                selectedId = this.id;
                            }
                            
                            if (selectedId != '') {
                                 $('#divPlanRoute').show();
                                $('#divAddressConfirmation').hide();
                                showRoute(this.id.substring(13));
                                return false;
                            }
                            
                        });
                        
                        return false;
                    });
                    
                    $('#addressConfirmButtons #routeSearchAgain').click(function() {
                        $('#divPlanRoute').show();
                        $('#divAddressConfirmation').hide();
                        
                        return false;
                    });
                    
                    $('#btnRoutePrint').click(function() {
                        var handle;
                        if (rtHandle != null) {
                            handle = rtHandle;
                        }
                        else {
                            handle = "";
                        }
                        
                        map.print2(handle,displayPrintResult,{});
                        return false;
                    });
                    
                }
            }
        break;
    }
}

function displayPrintResult(result){
    var src = "http://ems.whereis.com/v1/web/json/print/output?printId=" + escape(result.id);
    
    $('#mapdivprintview').html("<img src='" + src + "' width='528' height='310' />");
    $("#mapdiv").hide();
    $('#mapdivprintview').show();
    window.print();
}

//sets the geocode object for the carpark
function processCarParkSearch(addresses) {
    selectedCarParkAddress = null;
    if (addresses.results.length > 0) {
        selectedCarParkAddress = addresses.results[0].address;
    }
    else
    {
        $('#routeError').html('Sorry, we could not find that car park. Please try a different car park.');
    }
}

//callback function to process the results of the route address search
function processRouteSearch(addresses){
    possibleRouteAddressList.length = 0;
    
    if(addresses.results.length >0){
        
        //if there is just one result, just go ahead and do the search
        if (addresses.results.length == 1) {
            possibleRouteAddressList.push(addresses.results[0].address);
            showRoute(0);
        }
        else 
        {
        //more than one result, so let the user choose the correct one
            $('#divPlanRoute').hide();
            $('#divAddressConfirmation').show();
                            
            $('#divPossibleAddress').empty();
            var ul = document.createElement('ul');
            $('#divPossibleAddress').append(ul);
            
            for (var i=0;i<addresses.results.length;i++) {
                possibleRouteAddressList.push(addresses.results[i].address);
                
                var li = document.createElement('li');                
                $(ul).append(li);
                
                var input;
                
                //IE cant cope with dynamically added radios.
                if ($.browser.msie) {
                    input = document.createElement('<input id="possibleRoute' + i + '" type="radio" class="radio" name="possibleRoute" />');
                }
                else
                {
                    input = document.createElement('input');
                    input.type = 'radio';
                    input.name = 'possibleRoute';
                    $(input).addClass('radio');
                    input.id='possibleRoute' + i;
                }
                
                
                
                $(li).append(input);
                
                var label = document.createElement('label');
                //label.for = 'possibleRoute' + i; /errors in IE
                $(label).text(formatAddress(addresses.results[i].address));
                $(li).append(label);
                
            }
        }
    }
    else
    {
        $('#routeError').html('Sorry, we could not find that address. Please try a different address.');
    }
}


function showRoute(addressId) {
    var fastestRoute,useTolls,transportType;
    itinList.length = 0;    
    
    fastestRoute = true;                 //get fastest route. False is shortest route
    useTolls = false;                  //Use tolls - true or false
    transportType = "ALL_VEHICLES";     //"ALL_VEHICLES" || "PEDESTRIAN"
    
    fastestRoute = $("#routeMethod ol li :radio[@name='routeMethod']:checked").val();
    useTolls = $('#routeAvoidTolls').is(':checked') ? false : true;
    
    if (routeDirection.toLowerCase() == 'from') {
        $('#liStartAddress').html('Start Address : ' + formatAddress(selectedCarParkAddress));
        $('#liDestinationAddress').html('Destination Address : ' + formatAddress(possibleRouteAddressList[addressId]));
        $('#routeInstructionsTitle').html('Detailed route instructions from Car Park by foot');
        
        transportType = "PEDESTRIAN";
        itinList.push(selectedCarParkAddress);
        itinList.push(possibleRouteAddressList[addressId]);
    }
    else
    {
        $('#liStartAddress').html('Start Address : ' + formatAddress(possibleRouteAddressList[addressId]));
        $('#liDestinationAddress').html('Destination Address : ' + formatAddress(selectedCarParkAddress));
        $('#routeInstructionsTitle').html('Detailed route instructions to Car Park by car');
        
        transportType = "ALL_VEHICLES";
        itinList.push(possibleRouteAddressList[addressId]);
        itinList.push(selectedCarParkAddress);
    }
    
    if(itinList.length<2) {
        $('#routeError').html('Two address nodes are required. Please try searching again.');
        return;
    }
    
    //check no two consecutive points are the same
    for(var i=1;i<itinList.length;i++){
        
        if(itinList[i].coordinates.longitude==itinList[i-1].coordinates.longitude
        &&
        itinList[i].coordinates.latitude==itinList[i-1].coordinates.latitude) {
            $('#routeError').html('Please choose an address different to the carpark address.');
            return;
        }
    }
    
    //add the destination link
    addHomeMarker(possibleRouteAddressList[addressId].coordinates.longitude, possibleRouteAddressList[addressId].coordinates.latitude);
    
    routeManager.route(
        itinList, 
        fastestRoute, 
        useTolls, 
        transportType, 
        map.vlayer,
        {onComplete: displayRoute});
}

function displayRoute(routeResult) {
    $('#detailed-route').show();
    $('#detailed-directions').empty();
    
    //resize to bounding box
    map.zoomToExtent(new EMS.Bounds(
        routeResult.boundingBox.left,
        routeResult.boundingBox.bottom,
        routeResult.boundingBox.right,
        routeResult.boundingBox.top));
        
    //add the instructions
    var route, seg;
    for(var j=0;j<routeResult.routes.length;j++){
        
        route=routeResult.routes[j];
        
        //set the route handle for printing
        rtHandle = routeResult.routeHandle;
        
        var distanceKm = (routeResult.distanceMetres*1)/1000;
        var timeMins = Math.floor((routeResult.routeDuration*1)/60);
        
        $('#liTotalDistance').html('<strong>Total distance:</strong> ' + distanceKm + 'km');
        $('#liTotalTime').html('<strong>Total estimated journey time:</strong> ' + timeMins + ' mins');
                   
        for(var i=0;i<route.routeSegments.length;i++){
            var li = document.createElement('li');
            var span = document.createElement('span');
            seg=route.routeSegments[i];
            
            if (i==0) {
                if (routeDirection.toLowerCase() == 'to') {
                $(span).addClass('icon start'); //home icon
                }
                else
                {
                    $(span).addClass('icon stop'); //carpark logo
                }
            }
            else if (i==route.routeSegments.length -1) {
                if (routeDirection.toLowerCase() == 'to') {
                    $(span).addClass('icon stop');
                }
                else
                {
                    $(span).addClass('icon start');
                }
            } 
            else {
                switch (seg.routeDirection.toLowerCase()) {
                    case 'left' :
                        $(span).addClass('icon left');
                    break;
                    
                    case 'right' :
                        $(span).addClass('icon right');
                    break;
                    
                    case 'straight' :
                        $(span).addClass('icon straight');
                    break;
                    
                    case 'roundabout' :
                        $(span).addClass('icon round');
                    break;
                }
            }
            
            $(span).text(seg.routeDirection);
            $(li).append(span);
            
            var segDistanceKm = (seg.metres*1)/1000;
            var segTimeMins = Math.floor((seg.travelTime*1)/60);
            
            $(li).html(seg.textualInstruction.replace(/_(\w)/g, "<strong>$1").replace(/(\w)_/g, "$1</strong>") + " - " + segDistanceKm + "km (" + segTimeMins + " mins)");
            $(li).prepend(span);
            $('#detailed-directions').append(li);
        }
    }
}


function showNearByCarParks() {
    carParksNearbyShown = true;
    showAllCarParks(false);
}

//helper function to format a EMS address object to a string
function formatAddress(address) {
    var strAddress = '';
    if (address) {
        //test
        if (address.streetnumber && address.streetnumber.length > 0) {
            strAddress += address.streetnumber + ' ';
        }
    
        if (address.street) {
            if (address.street.fullname && address.street.fullname.length > 0) {
                strAddress += address.street.fullname + ', ';
            }
            else if(address.street.name && address.street.type && address.street.name.length > 0 && address.street.type.length > 0) {
                strAddress += address.street.name + ' ' + address.street.type + ', ';
            }
        }
        
        if (address.suburb && address.suburb.length > 0) {
            strAddress += address.suburb + ', ';
        }
        
        if (address.state && address.state.length > 0) {
            strAddress += address.state;
        }
    }
    return strAddress;
}


//show all the carparks on the map
function showAllCarParks(useFilter) {
    carParksOnMap.length = 0;
    for (var i=0;i<locationsArray.length;i++) {
        if (useFilter && servicesfilter.length > 0) {
            if (locationsArray[i].services.length > 0) {
                var hasAllServices = true;
                for (var j=0;j<servicesfilter.length;j++) {
                    if (!locationsArray[i].hasService(servicesfilter[j])) {
                        hasAllServices = false;
                    }
                }
            }
            
            if (hasAllServices) {
                var lonlat = new EMS.LonLat(locationsArray[i].longitude, locationsArray[i].latitude);
                addCarParkMarker(lonlat, locationsArray[i], true);
                carParksOnMap.push(locationsArray[i]);
            }
        }
        else
        {
            //just add all carparks
            var lonlat = new EMS.LonLat(locationsArray[i].longitude, locationsArray[i].latitude);
            addCarParkMarker(lonlat, locationsArray[i], true);
            carParksOnMap.push(locationsArray[i]);
        }
    }
}

//need to clear the map, recentre and re add the base marker
function resetCarParkMap()
{
    carParksOnMap.length = 0;
    clearMarkers();
    setMapView(selectedCarPark.maplongitude, selectedCarPark.maplatitude, selectedCarPark.zoomlevel);
    
    var lonlat = new EMS.LonLat(selectedCarPark.longitude, selectedCarPark.latitude);
    addCarParkMarker(lonlat, selectedCarPark, false);
    carParksOnMap.push(selectedCarPark);
}

function AddRegionalCarParks() {
    carParksOnMap.length = 0;
    var regionalCarParksArray;
    
    if (regionSelected.isSpecialRegion) {
        regionalCarParksArray = findCarParksBySpecialRegion(regionid);
    }
    else
    {
        regionalCarParksArray = findCarParksByRegion(regionid);
    }
    
    //clear the carpark list
    $('#ulregionalCarParks').empty();
    
    //add the car Parks on to the map
    for (var i=0;i<regionalCarParksArray.length;i++) {
        //if ((regionalCarParksArray[i].longitude) && (regionalCarParksArray[i].latitude)) {               
            
            //if there are any services filters, then only show those
            if (servicesfilter.length > 0)
            {
                var isMatch = true;
                for (var j=0;j<servicesfilter.length;j++) {
                    
                    if (!regionalCarParksArray[i].hasService(servicesfilter[j])) {
                        isMatch = false;
                    }
                }

                if (isMatch) {
                    
                    if (regionSelected) {
                        if (!regionSelected.staticmap) {
                            var lonlat = new EMS.LonLat(regionalCarParksArray[i].longitude, regionalCarParksArray[i].latitude);
                            addCarParkMarker(lonlat, regionalCarParksArray[i], true);
                        }
                    }
                    carParksOnMap.push(regionalCarParksArray[i]);                  
                }                
            }
            else //just add them all
            {
                if (regionSelected) {
                    if (!regionSelected.staticmap) {
                        var lonlat = new EMS.LonLat(regionalCarParksArray[i].longitude, regionalCarParksArray[i].latitude);
                        addCarParkMarker(lonlat, regionalCarParksArray[i], true);
                    }
                }
                carParksOnMap.push(regionalCarParksArray[i]);
            }            
        //}
        
        
    }
    
    if (carParksOnMap.length > 0) {
        for (var i=0;i<carParksOnMap.length;i++) {
            //add the side links
            var linkText = carParksOnMap[i].name.length > 0 ? carParksOnMap[i].name : carParksOnMap[i].street;
                    
            var li = document.createElement('li');
            var link = document.createElement('a');
            link.appendChild(document.createTextNode(linkText));
            link.className = 'carparklink';
            link.href='DisplayCarPark.aspx?carparkid=' + carParksOnMap[i].identity;
            
            li.appendChild(link);
            $('#ulregionalCarParks').append(li);
        }
        
        //add a last li class last for styling
        var liLast = document.createElement('li');
        liLast.className='last';
        $('#ulregionalCarParks').append(liLast);
    }
    else
    {
        var textNode = document.createTextNode('Sorry but we cannot identify any car parks close to your selected location. Please try again using our handy ');
        $('#ulregionalCarParks').append(textNode);
        
        var link = document.createElement('a');
        var linkNodeText = document.createTextNode('Find Parking Tool');
        link.appendChild(linkNodeText);
        link.setAttribute('href', 'citymap.aspx');
        $('#ulregionalCarParks').append(link);        
    }
}

//shows the selected poi on the map view
function displayPOI() {
    var poiNotFound, selectedPOI;
    
    if (mapType.toLowerCase() == "carpark") {
        poiNotFound = $('#poiNotFound');
        selectedPOI = $('#map-content #placeofinterest').val();
    }
    else
    {
        poiNotFound = $('#poiNotFoundCP');
        selectedPOI = $('#map-content #placeofinterestCP').val();
    }
    
    //set not found initially to hidden
    if (poiNotFound) {
        poiNotFound.show();
    }
    
    if (selectedPOI) {
        var query = new Object();
        query.keyword = selectedPOI;
        query.bounds=map.getExtent().asWGS84(); //searches within current map
        query.size=10;

        geocoder.poiSearch(query, processSearch);
    }
    else
    {
        if (poiNotFound) {
            poiNotFound.show();
        }
    }
    
    return false;
}

function processSearch(poiResults) {
    var poiResultsDiv;
    //clear the view
    clearMarkers();

    switch (mapType.toLowerCase()) {
        case "carpark" :
            
            poiNotFoundDiv = $('#poiNotFound');
            
            if (carParksNearbyShown == true) {
                showNearByCarParks();
                addPointerCursors();
            }
            
            var lonlat = new EMS.LonLat(selectedCarPark.longitude, selectedCarPark.latitude);
            addCarParkMarker(lonlat, selectedCarPark, false);
            
        break;
        case "carparklist" :
            poiNotFoundDiv = $('#poiNotFoundCP');
            //add the carparks again
            AddRegionalCarParks();
        break;
    }
    
    if (poiResults.results.length <= 0) {
        poiNotFoundDiv.show();
        return;
    }
    
    poiNotFoundDiv.hide();
    
    
    for(var i=0;i<poiResults.results.length;i++){
        var thePoi=poiResults.results[i];
        
        addPOIMarker(thePoi, i);
    }
}

//do a geocode search on the street search address provided from the qs
function doAddressSearch() {
    geocoder.findAddress(
        streetAddress, 
        suburbAddress,
        stateAddress, 
        processAddress
    );
}

function showHomeAddress() {
    var zoomRange = 12; //the amount to zoom out to before saying we cannot find any carparks...
    var containsCarPark = false;
    var bounds;
    var top, left, right, bottom, x, y;
    
    if (selectedHomeAddress) {
        var coords = selectedHomeAddress.coordinates;
        setMapView(coords.longitude, coords.latitude, startZoomLevel)
        
        //add the home marker
        addHomeMarker(coords.longitude, coords.latitude);
        
        //add the carparks on, taking account of filter
        showAllCarParks(true);
        
        map.zoomTo(zoomRange);
        bounds = map.getExtent();
        $('#carParksFoundUl').empty();
        
        //this is now zooming straight out to the specified zoomRange
        for (var i=0;i<carParksOnMap.length;i++) {                   
            pointLonLat = new EMS.LonLat(carParksOnMap[i].longitude, carParksOnMap[i].latitude);

            top = bounds.top;
            bottom = bounds.bottom;
            left = bounds.left;
            right = bounds.right;
            x = pointLonLat.lon;
            y = pointLonLat.lat;
            //if (bounds.contains(pointLonLat)) //this does not work
            if (top > y && bottom < y && left < x && right > x) {
                containsCarPark = true;
                
                //add it to the list
                var cpLi = document.createElement('li');
                var cpLink = document.createElement('a');
                cpLi.id = 'cpli' + carParksOnMap[i].identity;
                cpLink.id = 'cpa' + carParksOnMap[i].identity;
                cpLink.setAttribute('class', 'streetSearchLink');
                cpLink.innerHTML = carParksOnMap[i].street + ', ' + carParksOnMap[i].suburb;
                cpLink.href = 'displaycarpark.aspx?carparkid=' + carParksOnMap[i].identity;
                cpLi.appendChild(cpLink);
                $('#carParksFoundUl').append(cpLi);
            }
        }
        
        //zoom out until can see one
        //woah not any more. Just zoom straight out to the zoomRange
//        var containsCarPark = false;
//        var bounds = map.getExtent();
//        var top, left, right, bottom, x, y;
//        while ((startZoomLevel-1) >= zoomRange) {
//        
//            if (!containsCarPark) {
//                map.zoomTo(--startZoomLevel);
//                bounds = map.getExtent();
//            }
//            else //found a carpark on the map, so stop zooming out
//            {
//                break;
//            }
//            
//            $('#carParksFoundUl').empty();
//            
//            for (var i=0;i<carParksOnMap.length;i++) {                   
//                pointLonLat = new EMS.LonLat(carParksOnMap[i].longitude, carParksOnMap[i].latitude);

//                top = bounds.top;
//                bottom = bounds.bottom;
//                left = bounds.left;
//                right = bounds.right;
//                x = pointLonLat.lon;
//                y = pointLonLat.lat;
//                //if (bounds.contains(pointLonLat)) //this does not work
//                if (top > y && bottom < y && left < x && right > x) {
//                    containsCarPark = true;
//                    
//                    //add it to the list
//                    var cpLi = document.createElement('li');
//                    var cpLink = document.createElement('a');
//                    cpLi.id = 'cpli' + carParksOnMap[i].identity;
//                    cpLink.id = 'cpa' + carParksOnMap[i].identity;
//                    cpLink.setAttribute('class', 'streetSearchLink');
//                    cpLink.innerHTML = carParksOnMap[i].street + ', ' + carParksOnMap[i].suburb;
//                    cpLink.href = 'displaycarpark.aspx?carparkid=' + carParksOnMap[i].identity;
//                    cpLi.appendChild(cpLink);
//                    $('#carParksFoundUl').append(cpLi);
//                }
//            }
//            
//            
//        }
        
        addPointerCursors(); 
        
        if (!containsCarPark)
        {
            $('#streetSearchError').html('Sorry but we cannot identify any car parks close to your selected location. Please try again using our handy <a href=\"citymap.aspx\">Find Parking Tool</a>.');
        }
    }
    else
    {
        $('#streetSearchError').html('Sorry but that address could not be found. Please try again using our handy <a href=\"citymap.aspx\">Find Parking Tool</a>.');
    }
}

//processes the results of the geocoder on the address search
function processAddress(addresses){

    $('#streetSearchError').html(''); //clear the error box
    $('#divStreetSearchAddressList').hide();
    
    if(addresses.results.length >0){
        if (addresses.results.length == 1) {
            selectedHomeAddress = addresses.results[0].address;
            showHomeAddress();
            
        }
        else
        {
            $('#divStreetSearchAddressList').show();
            //add the list of possible addresses to an array
            
            $('#divStreetSearchPossibleAddress').empty();
            var ul = document.createElement('ul');
            $('#divStreetSearchPossibleAddress').append(ul);
            
            for (var i=0;i<addresses.results.length;i++) {
                possibleHomeAddressList.push(addresses.results[i].address);
                
                var li = document.createElement('li');                
                $(ul).append(li);
                
                var input;
                
                //IE cant cope with dynamically added radios.
                if ($.browser.msie) {
                    input = document.createElement('<input id="possibleStreetAddress' + i + '" type="radio" class="radio" name="possibleStreetAddress" />');
                }
                else
                {
                    input = document.createElement('input');
                    input.type = 'radio';
                    input.name = 'possibleStreetAddress';
                    $(input).addClass('radio');
                    input.id='possibleStreetAddress' + i;
                }
                
                
                
                $(li).append(input);
                
                var label = document.createElement('label');
                //label.for = 'possibleRoute' + i; //errors in IE
                $(label).text(formatAddress(addresses.results[i].address));
                $(li).append(label);
                
            }           
        }
        
    }
    else
    {
        $('#streetSearchError').html('Sorry but that address could not be found. Please try again using our handy <a href=\"citymap.aspx\">Find Parking Tool</a>.');
    }
}

//validates the search address fields
function validateAddress() {
    var errorMessage = '';
    var isValid = true;
    if (streetAddress == '' || streetAddress.toLowerCase() == 'street') {
        errorMessage += 'Street Address is required<br/>';
        isValid = false;
    }
    
    if (suburbAddress == '' || suburbAddress.toLowerCase() == 'suburb') {
        errorMessage += 'Suburb Address is required<br/>';
        isValid = false;
    }
    
    if (stateAddress == '' || stateAddress.toLowerCase() == 'state') {
        errorMessage += 'State is required<br/>';
        isValid = false;
    }
    
    if (!isValid) {
        geocodeErrorMessage = errorMessage;
        //$('#streetSearchError').html(errorMessage);
        
    }
    return isValid;
}

//Error Handling
window.onerror = showError ;

function showError(desc, page, line) {
    if (desc.length > 200) {
        alert("ERROR: " + desc + "\n\nPage: " + page + "\n\nLine: " + line);
    }
    else
    {
        //window.location.href('error.aspx?error=' + desc);
        $('#mapdiv').text(desc);
    }
}

