﻿$(document).ready(function() {
   //clear hidden fields
    $('#xcoords').val("");
    $('#ycoords').val("");

    $("#locations").autocomplete("locationlist",
                                        { minChars: 3,
                                            autoFill: true
                                        });

    $("#stationstatus").change(function() {
        if ($('#stationstatus option[@selected]').val() == 7) {
            $('#radius').attr('style', 'display:inline;');
        }
        else { $('#radius').attr('style', 'display:none;'); }

    });

    $("#FindStations").submit(function() {
        strAlert = "";
        if ($('input#locations').val() == "") { strAlert = $('input#locations').attr('title') + "\n"; }
        if ($('#stationstatus option[@selected]').val() == "") { strAlert += "Please select a station type\n"; }
        if (strAlert != "") {
            alert(strAlert);
            return false;
        }
        else {
                       return true;
        }

    });

    var localSearch = new GlocalSearch();
    $("#locations").blur(function() {

        var regEx = new RegExp("[a-zA-Z]{1,2}[0-9][0-9A-Za-z]? [0-9][a-zA-Z]{2}");
        var str = $('#locations').val();
        if (regEx.test(str)) {

            var localSearch = new google.search.LocalSearch();
            localSearch.execute(str + ", UK");
            localSearch.setSearchCompleteCallback(null, function() {
                if (localSearch.results[0]) {                   
                    var xycoords = (LatLongToOSGrid(localSearch.results[0].lat, localSearch.results[0].lng)).split(",");
                    $('#xcoords').val(xycoords[0]);
                    $('#ycoords').val(xycoords[1]);
                }
            })
        }
        else {
            $('#xcoords').val("");
            $('#ycoords').val("");
        }
    });
})