﻿
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 _searchAddressLat;
    var _searchAddressLong;

    var _displayMap;
    var _displayDocList;
    var _mapIconPrimaryColor = "#ff0000";
    var _mapIconStrokeColor = "#000000";
    var _mapIconLabelColor = "#FFFFFF";


    var _productID;
    var _yahooGeoAppID;

    var map;



   






    /*** 
    *** 
    *** "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, BreastSurgeonType, productID, arg0) {
        var searchType = "1";
        if (productID == null) {
            productID = _productID;
        }
        
        extendFunction("docListPanelLoad", "start");

        loadPageFromAddress_Pt1_GetGeoCode(searchType, productID, searchRadius, zipCode, "", "", "", arg0, BreastSurgeonType);
    }

    function docListPanelLoadbyCityState(city, state, productID, arg0, searchRadius, BreastSurgeonType) {
        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, "", arg0, BreastSurgeonType);
    }

    function docListPanelLoadbyDoctor(DrName, BreastSurgeonType, productID, arg0) {
        var searchType = "3";
        var searchRadius = "25";
        if (productID == null) {
            productID = _productID;
        }
        extendFunction("docListPanelLoad", "start");

        loadPageFromAddress_Pt1_GetGeoCode(searchType, productID, searchRadius, "", "", "", DrName, arg0, BreastSurgeonType);
    }

    function docListPanelLoadbyDoctorCityState(DrName, city, state, BreastSurgeonType, productID, arg0 ) {
        var searchType = "3";
        var searchRadius = "25";
        if (productID == null) {
            productID = _productID;
        }
        extendFunction("docListPanelLoad", "start");

        loadPageFromAddress_Pt1_GetGeoCode(searchType, productID, searchRadius, "", city, state, DrName, arg0, BreastSurgeonType);
    }

    function loadDocListPanelByPageNum(pageNum, arg0) {
        _currentPage = pageNum;
        
        if (arg0 == null) {
            arg0 = '';
        }
        $('#docListPanel').getTransform(_docListXSLTemplate, _docListXML, { params: { pageNumber: pageNum, recordCount: _recordCount, recordsPerPage: _recordsPerPage, extraArgs: arg0} , eval:false});
        $('#docListPanel').show();
        if (_displayMap) {
            extendFunction("docListPanelLoad", "preMap");
            reloadMapwithPageNum(pageNum);
        }
    }

    /*Doctor Detail Panel Related*/
    function docDetailsPanelLoad(shipToBioId) {
        extendFunction("docDetailsPanelLoad", "start");
        
        docDetailsGenericLoad("ForDocDetailPanel", shipToBioId, null);
    }

    function docDetailsBalloonLoad(shipToBioId) {
        extendFunction("docDetailsBalloonLoad", "start");
        
        docDetailsGenericLoad("ForBalloon", shipToBioId, null);
    }

    function docDetailsPanelAndBalloonLoad(shipToBioId) {
        extendFunction("docDetailsPanelAndBalloonLoad", "start");
        
        docDetailsGenericLoad("ForDocDetailPanelAndBalloon", shipToBioId, null);
    }

    /* Mail Related */

    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 getAccountNumbersByPage(pageNum) {
        var startRec = (pageNum * _recordsPerPage) + 1;
        var endRec = startRec + _recordsPerPage - 1;
        if (endRec > _recordCount) {
            endRec = _recordCount;
        }
        var accountNumbers = [];
        var i = 0;
        var rowCount = 1;

        $(_docListXMLForMap).each(function() {
            var doctor = $(this);
            if ((startRec <= rowCount) & (rowCount <= endRec)) {
                accountNumbers[i] = doctor.find("AccountNumber").text();
                i++;
            }
            rowCount++;
        });
        return accountNumbers;
    }

    /*** 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() {
            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));
            },
            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));
            
                },
                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) {
        docDetailsGenericLoad("ForBalloonFromPoint", shipToBioId, point);
    }

    function docDetailsGenericLoad(commandType, shipToBioId, point) {
        /*
        _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);
                    break;
                case "ForDocDetailPanel":
                    docDetailsGenericLoad_ForDocDetailPanel(_docDetailXMLArray[shipToBioId]);
                    break;
                case "ForBalloon":
                    docDetailsGenericLoad_ForBalloon(_docDetailXMLArray[shipToBioId], shipToBioId);
                    break;
                case "ForDocDetailPanelAndBalloon":
                    docDetailsGenericLoad_ForDocDetailPanel(_docDetailXMLArray[shipToBioId]);
                    docDetailsGenericLoad_ForBalloon(_docDetailXMLArray[shipToBioId], shipToBioId);
                    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));
                },
                success: function(xml) {
                    _docDetailXMLArray[shipToBioId] = xml;
                    switch (commandType) {
                        case "ForBalloonFromPoint":
                            docDetailsGenericLoad_ForBalloonFromPoint(_docDetailXMLArray[shipToBioId], point);
                            break;
                        case "ForDocDetailPanel":
                            docDetailsGenericLoad_ForDocDetailPanel(_docDetailXMLArray[shipToBioId]);
                            break;
                        case "ForBalloon":
                            docDetailsGenericLoad_ForBalloon(_docDetailXMLArray[shipToBioId], shipToBioId);
                            break;
                        case "ForDocDetailPanelAndBalloon":
                            docDetailsGenericLoad_ForDocDetailPanel(_docDetailXMLArray[shipToBioId]);
                            docDetailsGenericLoad_ForBalloon(_docDetailXMLArray[shipToBioId], shipToBioId);
                            break;
                    }
                }
            });
        }
    }
    
    function docDetailsGenericLoad_ForBalloonFromPoint(xml, point) {
        var tabs = [];
        for(var i=0; i < _mapBalloonXSLTemplateArray.length; i++)
        {
        
            $('#balloonHelper').getTransform(_mapBalloonXSLTemplateArray[i], xml);
            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) {
        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);

        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, drFirstName, arg0, BreastSurgeonType) {
        //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)
        var geoAddress = "";
        switch (searchType) {
            case "1":
                geoAddress = zip;
                break;
            case "2":
                geoAddress = format("{0}, {1}", city, state);
                break;
            case "3":
                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");
                    loadPageFromAddress_Pt1_1Alternate_UseYahooForGeoCode(searchType, geoAddress, productID, radius, zip, city, state, drFirstName, arg0, BreastSurgeonType);
                }
                else {
                    _searchAddressLat = point.lat();
                    _searchAddressLong = point.lng();

                    //Run Get XML List using address, searchType, lat, long
                    loadPageFromAddress_Pt2_GetDocListXML(searchType, _searchAddressLat, _searchAddressLong, productID, radius, zip, city, state, drFirstName, arg0, BreastSurgeonType);
                }
            });
    }
    function loadPageFromAddress_Pt1_1Alternate_UseYahooForGeoCode(searchType, geoAddress, productID, radius, zip, city, state, drFirstName, arg0, BreastSurgeonType) {
        var yahooGeoCodeURL = 'http://local.yahooapis.com/MapsService/V1/geocode';

        _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() {
            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}, arg0={9}  \nThe Attempted Webservice URL: {10}', searchType, geoAddress, geoAddress, productID, radius, zipCode, city, state, drFirstName, arg0, yahooGeoCodeURL));
            },
            success: function(xml) {
                _searchAddressLat = $('Latitude', xml).text();
                _searchAddressLong = $('Longitude', xml).text();
                loadPageFromAddress_Pt2_GetDocListXML(searchType, _searchAddressLat, _searchAddressLong, productID, radius, zip, city, state, drFirstName, arg0, BreastSurgeonType);
            }
        });
    }
    function loadPageFromAddress_Pt2_GetDocListXML(searchType, lat, lon, productID, radius, zipCode, city, state, drFirstName, arg0, BreastSurgeonType) {
        var geoData = "";
        
        switch (searchType) {
            case "1":
                geoData = "SearchType={0}&CenterLatitude={1}&CenterLongitude={2}&Radius={3}&ProductID={4}&ZipCode={5}&BreastSurgeonType={6}";
                geoData = format(geoData, searchType, lat, lon, radius, productID, zipCode, BreastSurgeonType);
                break;
            case "2":
                geoData = "SearchType={0}&CenterLatitude={1}&CenterLongitude={2}&Radius={3}&ProductID={4}&City={5}&StateName={6}&BreastSurgeonType={7}";
                geoData = format(geoData, searchType, lat, lon, radius, productID, city, state, BreastSurgeonType);
                break;
            case "3":
                geoData = "SearchType={0}&CenterLatitude={1}&CenterLongitude={2}&Radius={3}&ProductID={4}&DrFirstName={5}&City={6}&StateName={7}&BreastSurgeonType={8}";
                geoData = format(geoData, searchType, lat, lon, radius, productID, drFirstName, city, state, BreastSurgeonType);
                break;

        }

        geoData = geoData + "&SortBy=4&showPictureID=true";

        $.ajax({
            type: "GET",
            url: _docListSource,
            dataType: 'xml',
            data: geoData,
            error: function() {
            alert(format('Error loading Doc List XML. \nError occurred in Javascript Function: loadPageFromAddress_Pt2_GetDocListXML. \nParameters:  searchType={0}, lat={1}, lon={2}, productID={3}, radius={4}, zipCode={5}, city={6}, state={7}, drFirstName={8}, arg0={9}  \nThe Attempted Webservice URL: {10}', searchType, lat, lon, productID, radius, zipCode, city, state, drFirstName, arg0, _docListSource));
            },
            success: function(xml) {
                _docListXML = xml;
                _docListXMLForMap = $("doctor", _docListXML);
                _recordCount = $('doctor', xml).size();
                if (_displayDocList) {
                    loadPageFromAddress_Pt3_LoadDocList(searchType, state, arg0);
                }

            }
        });
           
    }
    function loadPageFromAddress_Pt3_LoadDocList(searchType, state, arg0) {
        loadDocListPanelByPageNum(0, arg0);
        waitingOff();
        if ((searchType == 3) && (state == '')) {
            map.setZoom(3);
        }
    }


    function reloadMapwithPageNum(pageNum) {
        map = new GMap2(document.getElementById("mapPanel"));
       
        var startRec = (pageNum * _recordsPerPage) +1;
        var endRec = startRec + _recordsPerPage - 1;
        if (endRec > _recordCount) {
            endRec = _recordCount;
        }
        
        var rowCounter = 1;
        var point0 = new GLatLng(_searchAddressLat, _searchAddressLong);
        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();
            if ((startRec <= rowCounter) & (rowCounter <= endRec)) {
                
                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 = isDouble(point) ;
            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());
            }); 
            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");
    }