﻿var _docListXML;
var _docListXMLForMap;
var _docListSource;
var _docListXSLTemplate;
var _docListCount;
var _recordsPerPage; //This may seem like it belongs in the xsl, but the map needs to know this too. So that's why it's here.
var _recordCount;
var _currentPage;

var _docDetailSource;
var _docDetailXSLTemplate;
var _docDetailXMLArray = [];

var _mapBalloonXSLTemplate;
var _mapBalloonXSLTemplateArray = [];
var _mapBalloonTabNames;
var _mapBalloonTabNameArray = [];

var _waitingHTMLTemplate;
var _searchPanelHTMLTemplate;
var _mailSendXSLTemplate;
var _mailSendSource;

var _directionsHTMLTemplate;

var _searchAddressLat;
var _searchAddressLong;

var _displayMap;
var _displayDocList;
var _mapIconPrimaryColor = "#ff0000";
var _mapIconStrokeColor = "#000000";
var _mapIconLabelColor = "#FFFFFF";

var _productID;
var _yahooGeoAppID;

var map;

var scrollbarPosition = 0;
var docListFirstView = true;    // set to false when user clicks on sort
var directions_accountNumber = '';
var directions_displayName = '';
var email_accountNumber = '';
var email_displayName = '';








/*** 
*** 
*** "PUBLIC" FUNCTIONS
*** This are the functions that will be called by the templates.
*** 
    
These are essentially the "Public" Functions that will be called by outside events.
The XSL stylesheets for example will calls some of these.
A javascript function outside this control but on the aspx page itself can all these.
    
***/



/*Doctor List Related
function docListPanelLoad(searchText, searchType, _productID, searchRadius) {
extendFunction("docListPanelLoad", "start");
        
loadPageFromAddress_Pt1_GetGeoCode(searchType, _productID, searchRadius, searchText);
}*/

function docListPanelLoadbyZip(searchRadius, zipCode, productID, sortBy, arg0) {
    var searchType = "1";
    if (productID == null) {
        productID = _productID;
    }

    extendFunction("docListPanelLoad", "start");

    loadPageFromAddress_Pt1_GetGeoCode(searchType, productID, searchRadius, zipCode, "", "", "", "", "", sortBy, arg0);
}

function docListPanelLoadbyCityState(city, state, productID, arg0, searchRadius, sortBy) {
    var searchType = "2";
    //var searchRadius = "25";
    if (searchRadius == null) {

        searchRadius = "25";
    }

    if (productID == null) {
        productID = _productID;
    }
    extendFunction("docListPanelLoad", "start");
    loadPageFromAddress_Pt1_GetGeoCode(searchType, productID, searchRadius, "", city, state, "", "", "", sortBy, arg0);
}

function docListPanelLoadbyDoctorCityState(firstName, lastName, city, state, productID, sortBy, arg0) {
    var searchType = "3";
    var searchRadius = "25";
    if (productID == null) {
        productID = _productID;
    }
    extendFunction("docListPanelLoad", "start");

    loadPageFromAddress_Pt1_GetGeoCode(searchType, productID, searchRadius, "", city, state, firstName, lastName, "", sortBy, arg0);
}

function docListPanelLoadbyOfficeCityState(office, city, state, productID, sortBy, arg0) {
    var searchType = "3.5";
    var searchRadius = "25";
    if (productID == null) {
        productID = _productID;
    }
    extendFunction("docListPanelLoad", "start");

    loadPageFromAddress_Pt1_GetGeoCode(searchType, productID, searchRadius, "", city, state, "", "", office, sortBy, arg0);
}

function loadDocListPanel(sortByType, arg0) {
    var sortColumn = 0;
    var orderBy = "ascending";
    var dataType = "number";

    switch (sortByType) {
        case 'PointsEarned':
            sortColumn = 30;
            dataType = "number";
            orderBy = "descending";
            break;
        case 'Distance':
            sortColumn = 27;
            dataType = "number";
            orderBy = "ascending";
            break;
        case 'DisplayName':
            sortColumn = 3;
            dataType = "text"
            orderby = "descending";
            break;
    }
    // if a sort checkbox is checked then resort the list
    if (sortColumn != 0) {

        // if sorting on PointsEarned column, convert the value to int then sort in descending order
        if (sortColumn == 30) {
            _docListXMLForMap = _docListXMLForMap.sort(function (a, b) {
                // IE uses nodeTypedValue whereas Firefox and Chrome use textContent.  Also, IE has 1/2 of the number of nodes
                var value1 = (a.childNodes[sortColumn].nodeTypedValue != null) ? a.childNodes[sortColumn].nodeTypedValue : a.childNodes[sortColumn * 2 + 1].textContent;
                var value2 = (b.childNodes[sortColumn].nodeTypedValue != null) ? b.childNodes[sortColumn].nodeTypedValue : b.childNodes[sortColumn * 2 + 1].textContent;

                return parseInt(value1) > parseInt(value2) ? -1 : 1;
            });
        }
        else {
            _docListXMLForMap = _docListXMLForMap.sort(function (a, b) {
                // IE uses nodeTypedValue whereas Firefox and Chrome use textContent.  Also, IE has 1/2 of the number of nodes
                var value1 = (a.childNodes[sortColumn].nodeTypedValue != null) ? a.childNodes[sortColumn].nodeTypedValue : a.childNodes[sortColumn * 2 + 1].textContent;
                var value2 = (b.childNodes[sortColumn].nodeTypedValue != null) ? b.childNodes[sortColumn].nodeTypedValue : b.childNodes[sortColumn * 2 + 1].textContent;

                if (sortColumn == 27) {
                    return parseFloat(value1) > parseFloat(value2) ? 1 : -1;
                }
                else {
                    return value1 > value2 ? 1 : -1;
                }
            });
        }

        $.each(_docListXMLForMap, function (index, value) {
            if (value.childNodes[0].nodeTypedValue != null) {
                value.childNodes[0].nodeTypedValue = (index + 1).toString();
            }
            else {
                value.childNodes[1].textContent = (index + 1).toString();
            }
        });
    }
    $('#docListPanel').getTransform(_docListXSLTemplate, _docListXML, { params: { sortBy: sortByType, orderBy: orderBy, dataType: dataType }, eval: false });
    if (_displayMap) {
        extendFunction("docListPanelLoad", "preMap");
        reloadMap();
    }
}

/*Doctor Detail Panel Related*/
function docDetailsPanelLoad(shipToBioId) {
    extendFunction("docDetailsPanelLoad", "start");

    docDetailsGenericLoad("ForDocDetailPanel", shipToBioId, null);
}

function docDetailsBalloonLoad(shipToBioId, docIndex) {
    extendFunction("docDetailsBalloonLoad", "start");

    docDetailsGenericLoad("ForBalloon", shipToBioId, null, docIndex);
}

function docDetailsPanelAndBalloonLoad(shipToBioId, docIndex) {
    extendFunction("docDetailsPanelAndBalloonLoad", "start");

    docDetailsGenericLoad("ForDocDetailPanelAndBalloon", shipToBioId, null, docIndex);
}

/* Mail Related */

function mailForm_reset() {
    $('#mailForm_firstName').val('');
    $('#mailForm_lastName').val('');
    $('#mailForm_email').val('');
    $('#mailForm_phone').val('');
    $("input[name='mailForm_desiredProducts']:checked").attr('checked', '');
}

function mailForm_validateFields() {
    var inputOK = true;

    // check for empty fields and invalid email/phone format
    if (jQuery.trim($('#mailForm_firstName').val()).length == 0) {
        alert('First name is required.');
        $('#mailForm_firstName').focus();
        inputOK = false;
    }
    else if (jQuery.trim($('#mailForm_lastName').val()).length == 0) {
        alert('Last name is required.');
        $('#mailForm_lastName').focus();
        inputOK = false;
    }
    else if (jQuery.trim($('#mailForm_email').val()).length == 0) {
        alert('Email is required.');
        $('#mailForm_email').focus();
        inputOK = false;
    }
    else if (mailForm_isValidEmailAddress($('#mailForm_email').val()) == false) {
        alert('Invalid email format');
        $('#mailForm_email').focus();
        inputOK = false;
    }
    else if (jQuery.trim($('#mailForm_phone').val()).length == 0) {
        alert('Phone is required.');
        $('#mailForm_phone').focus();
        inputOK = false;
    }
    else if (mailForm_isValidPhoneNumber($('#mailForm_phone').val()) == false) {
        alert('Invalid phone format');
        $('#mailForm_phone').focus();
        inputOK = false;
    }
    return inputOK;
}

function mailForm_isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

function mailForm_isValidPhoneNumber(ph) {
    if (ph == null) {
        return false;
    }
    var stripped = ph.replace(/[\s()+-]|ext\.?/gi, "");
    // 10 is the minimum number of numbers required
    return ((/\d{10,}/i).test(stripped));
}

function mailForm_close() {
    raiseLights();
    $('#sendMailPanel').hide();
}

function mailForm_sendMail(shipToBioId) {
    // if input not valid, bail.
    if (mailForm_validateFields() == false) {
        return;
    }

    var mailForm_desiredProducts = '';
    var numOfProducts = $("input[name='mailForm_desiredProducts']:checked").length;

    // if no product selected, bail.
    if (numOfProducts == 0) {
        alert("Please select at least one product");
        return;
    }

    $("input[name='mailForm_desiredProducts']:checked").each(function (index, item) {

        // if not last product, append comma
        // if last product prepend "and" and append "."
        // if only one product, omit "and"
        if (index != (numOfProducts - 1)) {
            mailForm_desiredProducts += $(this).val() + ", ";
        }
        else {
            mailForm_desiredProducts += ((numOfProducts != 1) ? " and " : "") + $(this).val() + ".";
        }
    });

    // set the text in email confirmation panel
    $('#productsInterested').text(mailForm_desiredProducts);

    var mailBody = '<div id="mailBody">A  customer requested a consultation through VIVITÉ® FindADoctor website for<br/>';
    mailBody += '{0} <br/><br/>';
    mailBody += "The patient's name is {1} {2}.<br/>";
    mailBody += 'Patient email: {3}<br/>';
    mailBody += 'Patient phone: {4}<br/><br/>';
    mailBody += 'The patient is interested in information about {5}<br/>';

    // if an appointment is needed, provide contact method and contact time.
    if ($('#mailForm_appointment').is(':checked')) {
        mailBody += '<br/>Yes, the patient would like your office to contact them to schedule an appointment.<br/><br/>';
        mailBody += 'Patients preferred contact method: {6}<br/>';
        mailBody += 'Patients preferred contact time: {7}';

        mailBody = format(mailBody,
                $('#mailForm_provider').val(),
                $('#mailForm_firstName').val(),
                $('#mailForm_lastName').val(),
                $('#mailForm_email').val(),
                $('#mailForm_phone').val(),
                mailForm_desiredProducts,
                $("input:radio[name=mailForm_wayToContact]:checked").val(),
                $("input:radio[name=mailForm_timeToContact]:checked").val()
                );
    }
    else {
        mailBody = format(mailBody,
                $('#mailForm_provider').val(),
                $('#mailForm_firstName').val(),
                $('#mailForm_lastName').val(),
                $('#mailForm_email').val(),
                $('#mailForm_phone').val(),
                mailForm_desiredProducts
                );
    }

    // if vivite was selected, show vivite message in the confirmation
    if ($('#mailForm_vivite').is(':checked')) {
        mailBody += "<br/><br/>Vivite® is a non prescription product available only through physician offices.<br/>";
    }

    // wrap the mail body
    mailBody += "<br/></div><hr/>";

    // replace special characters with proprietary tags.
    // we need to do this because we're sending the mail body as a page request parameter
    mailBody = mailForm_replaceSpecialCharacters(mailBody);

    sendDocMailWithCallback(shipToBioId, 'Consultation Request', mailBody, mailForm_requestWasSent);
}

// this function converts special characters into proprietary tags so we can use convert them back
// after sending as one of the GET parameters.  These special tags will be converted to HTML code
// on the other end.
//  If you can find a better way to do this, please let me know.
function mailForm_replaceSpecialCharacters(strText) {
    var returnText;

    returnText = strText.replace(/%/g, "xPercent");
    returnText = returnText.replace(/é/g, "xeacute");
    returnText = returnText.replace(/É/g, "xEacute");
    returnText = returnText.replace(/®/g, "xReg");
    returnText = returnText.replace(/'/g, "xSQuote");
    returnText = returnText.replace(/©/g, "xCopy");

    return returnText;
}

function mailForm_simpleCallback() {
    $('#mailForm_message').val('Success');
    $("#waitingScreenText").html('Thank you.<br/> Your email has been sent.');
    $("#waitPanel").fadeIn("slow").fadeOut(3000);
    $("#waitingScreenText").html('Loading...');
    mailForm_close();
}

function mailForm_requestWasSent() {
    $('#btnClose').css('background-image', 'url(../Controls/FindADoc/images/EmailToProviderConfirmed.png)');
    // hide the main panel and show the show the confirmation panel
    $('#mailForm_form').hide();

    // if vivite was selected, show vivite message in the confirmation
    if ($('#mailForm_vivite').is(':checked')) {
        $('#viviteMessage').show();
    }
    SC_logEmailSubmitted(email_accountNumber, email_displayName);
    $('#mailForm_requestSentScreen').show();
}


function sendMailPanelLoad(shipToBioId) {
    extendFunction("sendMailPanelLoad", "start");

    sendMailGenericLoad_pt1(shipToBioId);
}

function sendDocMail(shipToBioId, subject, message) {
    sendMailtoWebService(shipToBioId, subject, message, null);
}

function sendDocMailWithCallback(shipToBioId, subject, message, callBackFunction) {
    sendMailtoWebService(shipToBioId, subject, message, callBackFunction);
}

/* Utilities*/

function getAccountNumbers() {
    var accountNumbers = [];
    var i = 0;

    $(_docListXMLForMap).each(function () {
        var doctor = $(this);
        accountNumbers[i] = doctor.find("AccountNumber").text() + "|" + doctor.find("DisplayName").text();
        i++;

    });
    return accountNumbers;
}

function dimLights(isEmailPanel) {
    //alert($('#searchPanel').css("z-index"));
    $('#searchColumn').hide();
    $('#bdColumnOuter').hide();
    $('#fadePanel').css("height", (isEmailPanel != null && isEmailPanel == true) ? "3000px" : $(document).height());
    //$('#fadePanel').css("width", "1500px");
    $('#fadePanel').show();
    scrollbarPosition = $(window).scrollTop();  // remember the scroll bar position (so we can restore it)
    $(window).scrollTop(0); // scroll the window up to the top
}

function raiseLights() {
    $('#searchColumn').show();
    $('#bdColumnOuter').show();
    $('#fadePanel').hide();
    $(window).scrollTop(scrollbarPosition); // scroll back to the previous position
}

/*** END "PUBLIC" FUNCTIONS ***/



/**************************************************************************************************/
/**************************************************************************************************/
/**************************************************************************************************/



/* "PRIVATE"   INTERNAL FUNCTIONS */


function tester() {
    alert('hey');
}

function sendMailtoWebService(shipToBioId, subject, message, callBackFunction) {
    var mailData = "ShipToBioID={0}&subject={1}&message={2}";
    mailData = format(mailData, shipToBioId, subject, message);

    $.ajax({
        type: "GET",
        url: _mailSendSource,
        dataType: 'xml',
        data: mailData,
        error: function (a, b) {
            alert(format('Error loading Send Mail Return XML Document. \nError in Javascript Function: sendMailtoWebService. \nParameters:  ShipToBioID={0}&subject={1}&message={2} \nThe Attempted Webservice URL: {3}', shipToBioId, subject, message, _mailSendSource));
            waitingOff();
        },
        success: function (xml) {
            if (callBackFunction != null) {
                callBackFunction();
            }

        }
    });

}

function sendMailGenericLoad_pt1(shipToBioId) {

    if (_docDetailXMLArray[shipToBioId]) {
        sendMailGenericLoad_pt2(_docDetailXMLArray[shipToBioId]);
    }
    else {
        $.ajax({
            type: "GET",
            url: _docDetailSource,
            dataType: 'xml',
            data: 'shipToBioId=' + shipToBioId,
            error: function () {
                alert(format('Error loading Mail Form Load (trying to retrieve Doc Details XML). \nError in Javascript Function: sendMailGenericLoad_pt1. \nParameters:  ShipToBioID={0} \nThe Attempted Webservice URL: {1}', shipToBioId, _docDetailSource));
                waitingOff();
            },
            success: function (xml) {
                _docDetailXMLArray[shipToBioId] = xml;
                sendMailGenericLoad_pt2(_docDetailXMLArray[shipToBioId]);
            }
        });
    }

}

function sendMailGenericLoad_pt2(xml) {

    $('#sendMailPanel').getTransform(_mailSendXSLTemplate, xml);

    $('#sendMailPanel').show("slow", function () { extendFunction("sendMailPanelLoad", "end"); });

}

function docDetailsBalloonLoadFromPoint(shipToBioId, point, docIndex) {
    docDetailsGenericLoad("ForBalloonFromPoint", shipToBioId, point, docIndex);
}

function docDetailsGenericLoad(commandType, shipToBioId, point, docIndex) {
    /*
    _docDetailXMLArray[docID] is a caching mechanism.  
    It allows us to avoid repeated calls to the web service.
    It caches the Doc Details by put them in an array (_docDetailXMLArray) whose index number is the shipToBioId
    It will first try to read the value from this array, if it can't find it, it goes to the web service.
    When it does go to the web service for the XML, it then writes it to the _docDetailXMLArray for future calls.
    Note that this same caching mechanism is used by the Google Info Window ("Balloon") too. 
    That way the two can share the data between the two. 
    */

    if (_docDetailXMLArray[shipToBioId]) {
        switch (commandType) {
            case "ForBalloonFromPoint":
                docDetailsGenericLoad_ForBalloonFromPoint(_docDetailXMLArray[shipToBioId], point, docIndex);
                break;
            case "ForDocDetailPanel":
                docDetailsGenericLoad_ForDocDetailPanel(_docDetailXMLArray[shipToBioId]);
                break;
            case "ForBalloon":
                docDetailsGenericLoad_ForBalloon(_docDetailXMLArray[shipToBioId], shipToBioId, docIndex);
                break;
            case "ForDocDetailPanelAndBalloon":
                docDetailsGenericLoad_ForDocDetailPanel(_docDetailXMLArray[shipToBioId]);
                docDetailsGenericLoad_ForBalloon(_docDetailXMLArray[shipToBioId], shipToBioId, docIndex);
                break;
        }

    }
    else {

        $.ajax({
            type: "GET",
            url: _docDetailSource,
            dataType: 'xml',
            data: 'shipToBioId=' + shipToBioId,
            error: function () {
                alert(format('Error loading Doc Details XML. \nError occurred in Javascript Function: docDetailsGenericLoad. \nParameters:  commandType={0}, ShipToBioID={1},  point={2}  \nThe Attempted Webservice URL: {3}', commandType, shipToBioId, point, _docDetailSource));
                waitingOff();
            },
            success: function (xml) {
                _docDetailXMLArray[shipToBioId] = xml;
                switch (commandType) {
                    case "ForBalloonFromPoint":
                        docDetailsGenericLoad_ForBalloonFromPoint(_docDetailXMLArray[shipToBioId], point, docIndex);
                        break;
                    case "ForDocDetailPanel":
                        docDetailsGenericLoad_ForDocDetailPanel(_docDetailXMLArray[shipToBioId]);
                        break;
                    case "ForBalloon":
                        docDetailsGenericLoad_ForBalloon(_docDetailXMLArray[shipToBioId], shipToBioId, docIndex);
                        break;
                    case "ForDocDetailPanelAndBalloon":
                        docDetailsGenericLoad_ForDocDetailPanel(_docDetailXMLArray[shipToBioId]);
                        docDetailsGenericLoad_ForBalloon(_docDetailXMLArray[shipToBioId], shipToBioId, docIndex);
                        break;
                }
            }
        });
    }
}

function docDetailsGenericLoad_ForBalloonFromPoint(xml, point, docIndex) {
    var tabs = [];
    for (var i = 0; i < _mapBalloonXSLTemplateArray.length; i++) {

        $('#balloonHelper').getTransform(_mapBalloonXSLTemplateArray[i], xml, { params: { pointId: docIndex }, eval: false });
        tabs[i] = new GInfoWindowTab(_mapBalloonTabNameArray[i], $('#balloonHelper').html());
    }
    map.openInfoWindowTabsHtml(point, tabs);
}

function docDetailsGenericLoad_ForDocDetailPanel(xml) {
    $('#docDetailsPanel').getTransform(_docDetailXSLTemplate, xml);
    $('#docDetailsPanel').show("slow", function () { extendFunction("docDetailsPanelLoad", "end"); });
}

function docDetailsGenericLoad_ForBalloon(xml, shipToBioId, docIndex) {
    var xmlDoc = _docDetailXMLArray[shipToBioId];
    var lat = $(xmlDoc).find("Latitude").text();
    var lng = $(xmlDoc).find("Longitude").text();
    var point = new GLatLng(lat, lng);
    map.panTo(point);
    map.setZoom(13);
    docDetailsGenericLoad_ForBalloonFromPoint(xml, point, docIndex);

    extendFunction("docDetailsBalloonLoad", "end");
}



function format(str) {
    for (i = 1; i < arguments.length; i++) {
        str = str.replace('{' + (i - 1) + '}', arguments[i]);
    }
    return str;
}


function loadPageFromAddress_Pt1_GetGeoCode(searchType, productID, radius, zip, city, state, firstName, lastName, officeName, sortBy, arg0) {
    //Since this uses some async processes, group together the ones that need to happen in a particular order
    //1. Get GeoCode Address
    //2. When that completes get the Doc List XML
    //3. Then that completes run the DocList display and the MapList display (each one will render if the flag is set to true)
    //alert("sortBy = " + sortBy);
    var geoAddress = "";
    switch (searchType) {
        case "1":
            geoAddress = zip;
            break;
        case "2":
            geoAddress = format("{0}, {1}", city, state);
            break;
        case "3":
        case "3.5":
            geoAddress = "Kansas City, MO";

            if (state != '') {
                geoAddress = format("{0}, {1}", state, "USA");
            }

            if ((city != '') && (state != '')) {
                geoAddress = format("{0}, {1}", city, state);
            }
            break;

    }

    if (_displayMap) {
        $('#mapPanel').show("slow");
    }
    waitingOn();
    var geocoder = new GClientGeocoder();

    geocoder.getLatLng(
            geoAddress,
            function (point) {
                if (!point) {
                    alert(geoAddress + " not found");
                    waitingOff();
                    // if not able to obtain point from Google, try Yahoo!
                    //loadPageFromAddress_Pt1_1Alternate_UseYahooForGeoCode(searchType, geoAddress, productID, radius, zip, city, state, drFirstName, sortBy, arg0);
                }
                else {
                    _searchAddressLat = point.lat();
                    _searchAddressLong = point.lng();
                    docListFirstView = true;    // on every new search set this flag to true
                    //Run Get XML List using address, searchType, lat, long
                    loadPageFromAddress_Pt2_GetDocListXML(searchType, _searchAddressLat, _searchAddressLong, productID, radius, zip, city, state, firstName, lastName, officeName, sortBy, arg0);
                }
            });
}

function loadPageFromAddress_Pt1_1Alternate_UseYahooForGeoCode(searchType, geoAddress, productID, radius, zipCode, city, state, firstName, lastName, officeName, sortBy, arg0) {
    var yahooGeoCodeURL = 'http://local.yahooapis.com/MapsService/V1/geocode';

    jQuery.support.cors = true; // allow cross-site scripting

    _yahooGeoAppID = 'df14W5jV34HG2ItfzxFXWKMeEp8j7p3P4mzq4xP1zM8AbeA83_PK__s.iTN_cFBKlHg-';
    var yahooGeoData = format('appid={0}&location={1}', _yahooGeoAppID, geoAddress);
    $.ajax({
        type: "GET",
        url: yahooGeoCodeURL,
        dataType: 'xml',
        data: yahooGeoData,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(format('Error Yahoo GeoCode. \nError occurred in Javascript Function: loadPageFromAddress_Pt1_1Alternate_UseYahooForGeoCode. \nParameters:  searchType={0}, geoAddress={1}, geoAddress={2}, productID={3}, radius={4}, zipCode={5}, city={6}, state={7}, drFirstName={8}, sortBy={9}, arg0={10}  \nThe Attempted Webservice URL: {11}\nError Thrown {12}', searchType, geoAddress, geoAddress, productID, radius, zipCode, city, state, drFirstName, sortBy, arg0, yahooGeoCodeURL, errorThrown));
            waitingOff();
        },
        success: function (xml) {
            _searchAddressLat = $('Latitude', xml).text();
            _searchAddressLong = $('Longitude', xml).text();
            loadPageFromAddress_Pt2_GetDocListXML(searchType, _searchAddressLat, _searchAddressLong, productID, radius, zip, city, state, firstName, lastName, officeName, sortBy, arg0);
        }
    });
}

function HTMLEncode(str) {
    str = str.replace(/&/g, "%26");
    str = str.replace(/>/g, "%3e");
    str = str.replace(/</g, "%3c");
    str = str.replace(/"/g, "%22");
    str = str.replace(/'/g, "%27");
    return str;
}

function loadPageFromAddress_Pt2_GetDocListXML(searchType, lat, lon, productID, radius, zipCode, city, state, firstName, lastName, officeName, sortBy, arg0) {
    var geoData = "";

    switch (searchType) {
        case "1":
            geoData = "SearchType={0}&CenterLatitude={1}&CenterLongitude={2}&Radius={3}&ProductID={4}&ZipCode={5}&SortBy={6}";
            geoData = format(geoData, searchType, lat, lon, radius, productID, zipCode, sortBy);
            break;
        case "2":
            geoData = "SearchType={0}&CenterLatitude={1}&CenterLongitude={2}&Radius={3}&ProductID={4}&City={5}&StateName={6}&SortBy={7}";
            geoData = format(geoData, searchType, lat, lon, radius, productID, city, state, sortBy);
            break;
        case "3":
            geoData = "SearchType={0}&CenterLatitude={1}&CenterLongitude={2}&Radius={3}&ProductID={4}&DrFirstName={5}&DrLastName={6}&City={7}&StateName={8}&SortBy={9}";
            geoData = format(geoData, searchType, lat, lon, radius, productID, firstName, lastName, city, state, sortBy);
            break;
        case "3.5":
            var thisSearchType = 3;
            geoData = "SearchType={0}&CenterLatitude={1}&CenterLongitude={2}&Radius={3}&ProductID={4}&officeName={5}&City={6}&StateName={7}&SortBy={8}";
            geoData = format(geoData, thisSearchType, lat, lon, radius, productID, officeName, city, state, sortBy);
            break;

    }

    geoData = geoData + "&showPictureID=true";

    $.ajax({
        type: "GET",
        url: _docListSource,
        dataType: 'xml',
        data: geoData,
        error: function (status, errorText) {
            alert(format('Error loading Doc List XML. \nError occurred in Javascript Function: loadPageFromAddress_Pt2_GetDocListXML. \nError={0}, Parameters:  searchType={1}, lat={2}, lon={3}, productID={4}, radius={5}, zipCode={6}, city={7}, state={8}, firstName={9}, lastName={10}, officeName={11}, SortBy={12}, arg0={13}  \nThe Attempted Webservice URL: {14}', status.statusText, searchType, lat, lon, productID, radius, zipCode, city, state, firstName, lastName, officeName, sortBy, arg0, _docListSource));
            waitingOff();
        },
        success: function (xml) {
            _docListXML = xml;
            _docListXMLForMap = $("doctor", _docListXML);
            _recordCount = $('doctor', xml).size();
            if (_displayDocList) {
                loadPageFromAddress_Pt3_LoadDocList(searchType, arg0);
            }

        }
    });

}

function loadPageFromAddress_Pt3_LoadDocList(searchType, arg0) {
    loadDocListPanel('id', arg0);
    waitingOff();
    if (searchType == 3) {
        map.setZoom(3);
    }
}


function reloadMap() {
    map = new GMap2(document.getElementById("mapPanel"));

    var rowCounter = 1;
    var point0 = new GLatLng(_searchAddressLat, _searchAddressLong);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(point0, 10);
    map.clearOverlays();
    var pointsArray = [];

    //Iterate through XML and add points to a Point Array.
    $(_docListXMLForMap).each(function () {
        var doctor = $(this);
        var id = parseInt(doctor.find("id").text());
        //var shipToBioId = parseInt(doctor.find("ShipToBioId").text());
        var shipToBioId = doctor.find("ShipToBioId").text();
        var lat = doctor.find("Latitude").text();
        var lng = doctor.find("Longitude").text();
        var point = new GLatLng(lat, lng);
        point.thisId = id;
        point.shipToBioId = shipToBioId;
        pointsArray[pointsArray.length] = point;
        rowCounter++;
    });

    //Reverse the order of the Point Array and add them to the map.
    for (var i = pointsArray.length - 1; i >= 0; i--) {
        var point = pointsArray[i]
        var shipToBioId = point.shipToBioId;
        point.addStar = false;
        var newIcon = MapIconMaker.createLabeledMarkerIcon({ addStar: point.addStar, label: point.thisId.toString(), primaryColor: _mapIconPrimaryColor, strokeColor: _mapIconStrokeColor, labelColor: _mapIconLabelColor });
        var marker = new GMarker(point, { icon: newIcon, zIndexProcess: orderOfCreation });
        marker.value = point.thisId;
        marker.shipToBioId = shipToBioId;
        GEvent.addListener(marker, "click", function () {
            docDetailsBalloonLoadFromPoint(this.shipToBioId, this.getLatLng(), this.value.toString());
        });
        map.addOverlay(marker);
    }
}
function orderOfCreation(marker, b) {
    return 1;     //This ensures that the z-indexs are in the order in which they are added to the map.
}
var isDoublePointArray = []
function isDouble(point) {
    var rtnValue = false;
    var index = isDoublePointArray.length;
    for (var i = 0; i < index; i++) {
        if ((point.lat() == isDoublePointArray[i].lat()) && (point.lng() == isDoublePointArray[i].lng())) {
            rtnValue = true;
        }
    }
    isDoublePointArray[index] = point;
    return rtnValue;
}


function waitingOn() {
    $("#waitPanel").fadeIn("slow");
}

function waitingOff() {
    $("#waitPanel").fadeOut("slow");
}


