﻿var originalSearchCriteria;

function dentistResults() {

    $("[id$='_litMultipleResults']").hide();
    $("[id$='_litNoFound']").hide();

    originalSearchCriteria = $("[id$='_txtFindADentist']").val();
    var DTO = { 'searchCriteria': originalSearchCriteria };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/services/FindADentist.asmx/GetSearchSubstitution",
        data: JSON.stringify(DTO),
        dataType: "json",
        success: function(results) {
            var address = results.d;
            var regionCode = "GB";
            var northEastBound = new google.maps.LatLng(63.16, 3.20);       // north-east corner of Great Britain
            var southWestBound = new google.maps.LatLng(48.58, -17.06);     // south-west corner of Great Britain
            
            geocodeLocation(address, regionCode, northEastBound, southWestBound);
        },
        error: AjaxSendError
    });

}

function geocodeLocation(address, regionCode, northEastBound, southWestBound) {

    var geocoder;               
    var latLngBounds = new google.maps.LatLngBounds(southWestBound, northEastBound);

    geocoder = new google.maps.Geocoder();          // initialise the Google geocoder

    geocoder.geocode({
        'address': address + ', ' + regionCode,
        'bounds': latLngBounds,
        'region': regionCode
    },
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var dentistLocations = results;
                showClientLocations(address, regionCode, dentistLocations);
            } else {
                storeNoFoundSearch(address);
                $("[id$='_litNoFound']").show();
            }
        }
    );

}

function showClientLocations(address, regionCode, dentistLocations) {

    // use this function if the call to Google has been made client-side
    if (dentistLocations != null) {
        gbDentistLocations = includeLocationsWithRegionCode(dentistLocations, regionCode);    // only select the GB dentists
        if (gbDentistLocations.length == 1) {
            window.location = "find-a-dentist/results.aspx?js=1&long=" + gbDentistLocations[0].geometry.location.lng() + "&lat=" + gbDentistLocations[0].geometry.location.lat() + "&pl=" + originalSearchCriteria;  //dentistLocations[0].location;
        } else if (gbDentistLocations.length > 0) {
            $("[id$='_spnSearchCriteria']").html($("[id$='_txtFindADentist']").val());
            var multiples = "<ul>";
            for (i = 0; i < gbDentistLocations.length; i++) {
                multiples += "<li><a href=\"find-a-dentist/results.aspx?js=1&long=" + gbDentistLocations[i].geometry.location.lng() + "&lat=" + gbDentistLocations[i].geometry.location.lat() + "&pl=" + gbDentistLocations[i].formatted_address + "\">" + gbDentistLocations[i].formatted_address + "</a></li>";
            }
            multiples += "</ul>";
            $("[id$='_multiples']").html(multiples);
            $("[id$='_litMultipleResults']").show();
        } else {
            storeNoFoundSearch(address);
            $("[id$='_litNoFound']").show();
        }
    }
    else {
        storeNoFoundSearch(address);
        $("[id$='_litNoFound']").show();
    }
}

function storeNoFoundSearch(searchCriteria) {

    var DTO = { 'searchCriteria': searchCriteria };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/services/FindADentist.asmx/StoreInvalidSearch",
        data: JSON.stringify(DTO),
        dataType: "json"
    });

}

function setupControls() {
    hideFallbackControls();
    $("[id$='_litMultipleResults']").hide();
    $("[id$='_litNoFound']").hide();

    $("[id$='_txtFindADentist']").bind("keydown", function(event) {
        // track enter key
        var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
        if (keycode == 13) { // keycode for enter key
            // force the 'Enter Key' to implicitly click the Update button
            $("form").submit();
            return false;
        } else {
            return true;
        }
    });  // end of function
}

function hideFallbackControls() {
    $('.noscript').hide();
    $('#buttonSubmit').removeClass('scriptonly');
    $('#buttonSubmit').attr('style', '"display: block !important"');
}

function readCurrentQS() {

    // Detect whether this is a redirect from a previous FAD version and send it on its way...
    if (querySt("long") != null) {
        window.location = "find-a-dentist/results.aspx?js=1&long=" + querySt("long") + "&lat=" + querySt("lat") + "&pl=" + querySt("pl") + "&filter=" + querySt("filter");
    } else if (querySt("lon") != null) {
        window.location = "find-a-dentist/results.aspx?js=1&long=" + querySt("lon") + "&lat=" + querySt("lat") + "&pl=" + querySt("place") + "&filter=" + querySt("filter");
    } else if (querySt("Static") != null) {

        if (querySt("Static") == "IsleOfMan") {
            $("[id$='_txtFindADentist']").val("Isle Of Man");
            dentistResults();
        } else {
            $("[id$='_txtFindADentist']").val("Static");
            dentistResults();
        }
    } else if (querySt("pc") != null) {
        $("[id$='_txtFindADentist']").val("pc");
        dentistResults();
    }

}

// filter out any dentists which don't have the matching region code
function includeLocationsWithRegionCode(sourceDentistLocations, regionCode) {
    var filteredDentistLocations = new Array();
    for (i = 0; i < sourceDentistLocations.length; i++) {
        for (j = 0; j < sourceDentistLocations[i].address_components.length; j++) {
            if (sourceDentistLocations[i].address_components[j].types[0] == "country" && sourceDentistLocations[i].address_components[j].short_name == regionCode) {
                filteredDentistLocations[filteredDentistLocations.length] = sourceDentistLocations[i];
            }
        }
    }
    return filteredDentistLocations;
}

// Generic AJAX Error Handler
function AjaxSendError() {
    swapDialogClass('stateFailure');
    $('.dialog').dialog('open');
}

$(document).ready(function() {

    setupControls();
    readCurrentQS();

    $("#btnSubmit").click(function() {
        $("form").submit();
    });
    $("form").validate({
        errorPlacement: function(error, element) {
        $("[id$='_litNoFound']").html(error);
        $("[id$='_litNoFound']").show();
        },
        errorClass: "enquiryError",
        showErrors: function(errorMap, errorList) {
            $("#messageBox").html("Your form contains "
                                       + this.numberOfInvalids()
                                       + " error(s), see details below.");
            this.defaultShowErrors();
        },
        submitHandler: dentistResults
    });
});


