﻿var statusOK = 200;
var statusSessionExpired = 300;


//$(document).ajaxError(function()
//{
//    alert(arguments);
//    if (window.console && window.console.error)
//    {
//        console.error(arguments);
//    }
//});

//Stuff that runs when the page is loaded
$(document).ready(function()
{
    updateSidebarUser();
    loadGroupID();
    getPlanLogos();

    //This creates rollover buttons.  By using the live() function, it'll bind the events later for controls that aren't on the page yet.r
    $('a.roll').live("mouseover",
        function()
        {
            img = $(this).find('img');
            img.attr('src', img.attr('src').replace("_off", "_on"));
        })
    .live("mouseout",
        function()
        {
            img = $(this).find('img');
            img.attr('src', img.attr('src').replace("_click", "_off").replace("_on", "_off"));
        })
    .live("mousedown",
        function()
        {
            img = $(this).find('img');
            img.attr('src', img.attr('src').replace("_off", "_click").replace("_on", "_click"));
        })
    .live("mouseup",
        function()
        {
            img = $(this).find('img');
            img.attr('src', img.attr('src').replace("_click", "_on"));
        });
});

// Clears all the options out of a select box.  Usage: $("#mySelect").clearSelect();
$.fn.clearSelect = function()
{
    return this.each(function()
    {
        if (this.tagName == 'SELECT')
        {
            this.options.length = 0;
        }
    });
};

//Loads a select box with an array of Name and Value.  Usage: $("#mySelect").fillSelect(data) or $("#mySelect").fillSelect(data, "Select one of these")
$.fn.fillSelect = function(data, emptyTopRowText)
{
    return this.clearSelect().each(function()
    {
        if (this.tagName == 'SELECT')
        {
            var list = this;
            if (emptyTopRowText !== null && emptyTopRowText !== undefined)
            {
                var option = new Option(emptyTopRowText, '');
                if ($.browser.msie)
                {
                    list.add(option);
                }
                else
                {
                    list.add(option, null);
                }
            }

            $.each(data, function(index, optionData)
            {
                var option = new Option(optionData.Name, optionData.Value);
                //list.append(option);
                if ($.browser.msie)
                {
                    list.add(option);
                }
                else
                {
                    list.add(option, null);
                }
            });
        }
    });
};

//Generic close and open functions for page elements, so that I could keep calling 'close()' but change the specific eye candy.
// Usage: $("#someElement").open(data)
$.fn.close = function(data)
{
    return this.each(function()
    {
        $(this).fadeOut('fast');
        //$(this).slideUp('slow');
    });
};

$.fn.open = function(data)
{
    return this.each(function()
    {
        $(this).fadeIn('fast');
        //$(this).slideDown('slow');
    });
};

// Fades the background color of an element quickly to the start color, then slowly to the end color.
// Usage: $('something').highlightFade('#ffde00', '#ffffff')
//There may be something 
$.fn.highlightFade = function(startcolor, endcolor)
{
    return this.each(function()
    {
        $(this).stop().animate({ backgroundColor: startcolor }, "fast").animate({ backgroundColor: endcolor }, 5000).css("background-color", "");
    });
};

//Saw it, liked it, might need it someday.  Usage: if($('#object').exists()) {...}
jQuery.fn.exists = function() { return (this.size() > 0); };

//Replace function.  Gets rid of target 1 and shows target 2.
//Although if target 1 is not showing, it'll reverse them and show target 1 and hide target 2.
//This could be rewritten to use open() and close() so that the effects are consistent without having to rewrite both,
//but it's not that big a deal.
function replace(target1, target2, callback)
{
    var display = $(target1).css("display");
    if (display == 'none')
    {
        replace(target2, target1, callback);
        return;
    }
    $(target1).fadeOut('fast', function() { $(target2).fadeIn('fast', callback); });
    //other animation effects:
    //$(target1).hide('slow', function() { $(target2).show('slow'); });
    //$(target1).slideUp('slow', function() { $(target2).slideDown('slow'); });
}

// AJAX CALLS
// See http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/ 
// for more details on calling web methods in an ASPX page using JQuery.

// When the user types in the plan and zip code and clicks the button.
function enterPlan()
{
    //Get the data from the form fields
    var plan = $("#identify .stepcontent #PlanID").val();
    var zip = $("#identify .stepcontent #ZIP").val();
    var matchingPlan = $('#MatchingPlans').val();

    $.ajax({
        //For calling ASP.NET web methods, the first four parameters probably won't ever need to be changed.
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/ValidatePlan",
        data: "{"
                    + "plan: '" + plan + "'"
                    + ", zip: '" + zip + "'"
                    + ", groupPlan: '" + matchingPlan + "'"
                    + "}",
        success: function(result)
        {
            enterPlanCallback(result);
        }
    });
}

function enterPlanCallback(result)
{
    if (result.d.Success === true)
    {
        //They successfully identified their plan and zip.

        //Clear/reset the fields in this form in case the user hits the reset plan button and gets back here
        $("#identify .stepcontent #PlanID").val('');  //Clear the plan ID text box for next time
        $("#identify .stepcontent #ZIP").val(''); //Clear the ZIP text box for next time
        $('#PlanError').html('');   //Clear any error message that might have been previously shown
        $('#PlanError').close();    //Hide the plan error line
        $('#GroupCollisionRow').close();    //Close the group collision line if it had been shown

        //Then, do the overall page updates
        clearCategoriesAndProcedures();
        $('#PlanName').html(result.d.PlanName); //Insert their new plan name into the line for the collapsed step 1
        $('#identify .steptitle img').attr('src', '/WebPages/images/box_checked.gif'); //mark this section with a check box
        //Update the plan logo
        //replace('#introheader', '#introclosed');    //collapse the intro section
        $('#introclosed').open();
        $('#introheader').close();
        //replace('#identify .stepcontent', '#identify .stepdone');    //collapse the identify section
        replace('#identify .stepcontent', '#identify .stepdone', function() { $.scrollTo($('.stepseparator:eq(1)'), 800, {axis:'y'}); });    //collapse the identify section
        $('#selproc .stepcontent').open();                //open the next section to select the procedure
        getPlanLogos();
        $('#sbHealthGradesLink').show();
        $('#sbHealthGrades').hide();
        //$.scrollTo($('.stepseparator:eq(1)'), 800);
    }
    else
    {
        //They didn't successfully identify their plan and zip, so we have an error message to show.
        $('#PlanError').html(result.d.ErrorMessage); //Insert the error message into the HTML
        $('#PlanError').open(); //show the error message
        if (result.d.GroupCollision)
        {
            //If they entered in a group number, and a couple of plans used that same group number
            //(ask Jim or Andrew to explain group collisions)
            //we need to show them a dropdown list of plans that have that group number.
            $("#GroupCollisionRow div:first").html(result.d.plans);
            $('#GroupCollisionRow').open();
        }
        else
        {
            //If it's not a group collision, we need to make sure that dropdown isn't shown.
            $("#GroupCollisionRow div:first").html('');
            $('#GroupCollisionRow').close();
        }
    }
}

//This is where the user clicked 'reset', which either logs them off or clears their plan.
//We need to hit the server so that we can clear their session, then reset everything to step 1.
//This calls the LogOut webmethod.
function logOut()
{
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/LogOut",
        data: "{}",
        success: function(result)
        {
            logOutCallback(result);
        }
    });

}

//Once we've come back from the server, we need to reset pretty much the whole page.
function logOutCallback(result)
{
    $('#PlanName').html('');    //Clear out the "Your plan is..." field

    //These two lines originally worked to set step 1 to incomplete, 
    //but now that they could be logging out from the sidebar while step 1 was incomplete,
    //logging out has the opposite effect.
    //This'll be fixed when I add the feature to build the page in progress on Page_Load.
    //replace('#introclosed', '#introheader');    //Expand out the intro section, or do we want to leave it collapsed after the first time?
    //replace('#identify .stepdone', '#identify .stepcontent');   //Expand the identify section so that the enter plan and login forms are visible again
    $('#introclosed').open();
    $('#introheader').close();
    $('#identify .stepdone').close();
    $('#identify .stepcontent').open();   //Expand the identify section so that the enter plan and login forms are visible again

    $('.steptitle img').attr('src', '/WebPages/images/box_empty.gif'); //Shortcut: since this is step 1, we can reset ALL the check boxes.

    $('.stepcontent:gt(0), .stepdone:gt(0)').close(); //Close any step content or step finished div after the first one
    $("#planlogos").html('');
    updateSidebarUser();
    $('#sbHealthGradesLink').hide();
    $('#sbHealthGrades').show();
    $('#createPortal').close();
    clearHospitalDetails();
    showmap();    
}

function logIn()
{
    //Get the data from the form fields
    var user = $("#identify .stepcontent #MemberID").val();
    var password = $("#identify .stepcontent #Password").val();

    $.ajax({
        //For calling ASP.NET web methods, the first four parameters probably won't ever need to be changed.
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/ValidateLogin",
        data: "{"
                    + "user: '" + user + "'"
                    + ", password: '" + password + "'"
                    + "}",
        success: function(result)
        {
            logInCallback(result);
        }
    });
}

function logInCallback(result)
{
    if (result.d.Success === true)
    {
        //They successfully identified their plan and zip.

        //Clear/reset the fields in this form in case the user hits the reset plan button and gets back here
        $("#identify .stepcontent #MemberID").val('');  //Clear the plan ID text box for next time
        $("#identify .stepcontent #Password").val(''); //Clear the ZIP text box for next time
        $('#LoginError').html('').close();   //Clear any error message that might have been previously shown, and close it

        //Then, do the overall page updates
        clearCategoriesAndProcedures();
        $('#PlanName').html(result.d.PlanName); //Insert their new plan name into the line for the collapsed step 1
        $('#identify .steptitle img').attr('src', '/WebPages/images/box_checked.gif'); //mark this section with a check box
        getPlanLogos();
        replace('#introheader', '#introclosed');    //collapse the intro section
        replace('#identify .stepcontent', '#identify .stepdone');   //collapse the identify section
        $('#selproc .stepcontent').open();                //open the next section to select the procedure
        updateSidebarUser();
        $('#sbHealthGradesLink').show();
        $('#sbHealthGrades').hide();
    }
    else
    {
        //They didn't successfully identify their plan and zip, so we have an error message to show.
        $('#LoginError').html(result.d.ErrorMessage).open(); //Insert the error message into the HTML, and show it
    }
}

function logIn2()
{
    //Get the data from the form fields
    var user = $("#MemberID2").val();
    var password = $("#Password2").val();

    $.ajax({
        //For calling ASP.NET web methods, the first four parameters probably won't ever need to be changed.
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/ValidateLogin",
        data: "{"
                    + "user: '" + user + "'"
                    + ", password: '" + password + "'"
                    + "}",
        success: function(result)
        {
            logInCallback2(result);
        }
    });
}

function logInCallback2(result)
{
    if (result.d.Success === true)
    {
        //They successfully identified their plan and zip.

        //Clear/reset the fields in this form in case the user hits the reset plan button and gets back here
        $("#MemberID2").val('');  //Clear the plan ID text box for next time
        $("#Password2").val(''); //Clear the ZIP text box for next time
        $('#LoginError2').html('');    //Clear any error message that might have been previously shown, and close it
        $('#LoginError2').parent().close();

        //Then, do the overall page updates
        clearCategoriesAndProcedures();
        $('#PlanName').html(result.d.PlanName); //Insert their new plan name into the line for the collapsed step 1
        $('#identify .steptitle img').attr('src', '/WebPages/images/box_checked.gif'); //mark this section with a check box
        getPlanLogos();
        replace('#introheader', '#introclosed');    //collapse the intro section
        replace('#identify .stepcontent', '#identify .stepdone');   //collapse the identify section
        $('#selproc .stepcontent').open();                //open the next section to select the procedure
        $('#sbHealthGradesLink').show();
        $('#sbHealthGrades').hide();
        updateSidebarUser();
    }
    else
    {
        //They didn't successfully identify their plan and zip, so we have an error message to show.
        $('#LoginError2').html(result.d.ErrorMessage); //Insert the error message into the HTML, and show it
        $('#LoginError2').parent().open(); //Insert the error message into the HTML, and show it
    }
}

function updateSidebarUser()
{
    $.ajax({
        //For calling ASP.NET web methods, the first four parameters probably won't ever need to be changed.
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetUserName",
        data: "{}",
        success: function(result)
        {
            $('#sbLogin input').empty();
            $('#sbLogin div:eq(1)').hide();
            if (result.d === null || result.d === '')
            {
                $('#sbLogin').show();
                $('#sbLogout').hide();
            }
            else
            {
                $('#sbUserName').text(result.d);
                $('#sbLogin').hide();
                $('#sbLogout').show();
                $('#sbHealthGradesLink').show();
                $('#sbHealthGrades').hide();
            }
        }
    });
}

function loadGroupID()
{
    $.ajax({
        //For calling ASP.NET web methods, the first four parameters probably won't ever need to be changed.
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetGroupID",
        data: "{}",
        success: function(result)
        {
            $('#PlanID').val(result.d);
        }
    });
    $.ajax({
        //For calling ASP.NET web methods, the first four parameters probably won't ever need to be changed.
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetZIPCode",
        data: "{}",
        success: function(result)
        {
            if (result.d != '')
            {
                $('#ZIP').val(result.d);
            }
        }
    });
}

function getPlanLogos()
{
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetPlanLogos",
        data: "{}",
        success: function(result)
        {
            $("#planlogos").html(result.d);
        }
    });
}

function clearCategoriesAndProcedures()
{
    $('#medterms2, #bodyareas2').attr('value', '');
    loadMedTerms(true);
    loadBodyAreas(true);
    loadProcedures(true);
}

//Load the list of procedure category medical terms.
function loadMedTerms(clear)
{
    medterm = '';
    bodyarea = '';
    if (!clear)
    {
        medterm = $("#medterms2").attr('value');
        bodyarea = $('#bodyareas2').attr('value');
    }

    //$("#medterms2").prepend('<img class="loading" style="float: left; position: relative; top: -10px; left: 0px;" src="/WebPages/images/arrows20.gif" />');    
    $("#medterms2").css("position", "relative").append('<img class="loading" style="display: block; position: absolute;z-index: 1; left:-1px;top: -1px;" src="/WebPages/images/arrows20.gif" />');
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetMedTerms",
        data: "{"
                    + "MedTerm: '" + medterm + "'"
                    + ", BodyArea: '" + bodyarea + "'"
                    + "}",
        success: function(result)
        {
            //Clear and reload the list with the new values, then set the selected one back to what it was.
            if (result.d.Status == statusOK)
            {
                $('#medterms2').html(result.d.Value);
            }
            else if (result.d.Status == statusSessionExpired)
            {
                processSessionExpired();
            }
            else
            {
                processOtherError(result.d.Status, result.d.Message);
            }
        },
        complete: function()
        {
            $('#medterms2 .loading').remove();
            $("#medterms2").css("position", "")
        }
    });

}

//Load the list of procedure categories body areas.
function loadBodyAreas(clear)
{
    medterm = '';
    bodyarea = '';
    if (!clear)
    {
        medterm = $("#medterms2").attr('value');
        bodyarea = $('#bodyareas2').attr('value');
    }

    $("#bodyareas2").css("position", "relative").append('<img class="loading" style="display: block; position: absolute;z-index: 1; left:-1px;top: -1px;" src="/WebPages/images/arrows20.gif" />');
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetBodyAreas",
        data: "{"
                    + "MedTerm: '" + medterm + "'"
                    + ", BodyArea: '" + bodyarea + "'"
                    + "}",
        success: function(result)
        {
            if (result.d.Status == statusOK)
            {
                $('#bodyareas2').html(result.d.Value);
            }
            else if (result.d.Status == statusSessionExpired)
            {
                processSessionExpired();
            }
            else
            {
                processOtherError(result.d.Status, result.d.Message);
            }
        },
        complete: function()
        {
            $('#bodyareas2 .loading').remove();
            $("#bodyareas2").css("position", "")
        }
    });
}

function selectCategory(target, value)
{
    $(target).parent().children().css({ "background-color": "", "color": "" });
    $(target).css({ "background-color": "#003399", "color": "White" });
    $("#medterms2").attr('value', value);
    loadBodyAreas(); 
    loadProcedures();
}

function selectBodyArea(target, value)
{
    $(target).parent().children().css({ "background-color": "", "color": "" });
    $(target).css({ "background-color": "#003399", "color": "White" });
    $("#bodyareas2").attr('value', value);
    loadMedTerms();
    loadProcedures();
}

//Load the procedures based on the currently selected category and/or body area
function loadProcedures(clear)
{
    medterm = '';
    bodyarea = '';
    if (!clear)
    {
        medterm = $("#medterms2").attr('value');
        bodyarea = $('#bodyareas2').attr('value');
    }

    $("#procedures2").css("position", "relative").append('<img class="loading" style="display: block; position: absolute;z-index: 1; left:-1px;top: -1px;" src="/WebPages/images/arrows20.gif" />');
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetProcedures",
        data: "{"
                    + "MedTerm: '" + medterm + "'"
                    + ", BodyArea: '" + bodyarea + "'"
                    + "}",
        success: function(result)
        {
            if (result.d.Status == statusOK)
            {
                $('#procedures2 div table').html(result.d.Value);
                hideProcedureDetails(); //We just reloaded the procedures list, so we should get rid of the details from the last one selected.
            }
            else if (result.d.Status == statusSessionExpired)
            {
                processSessionExpired();
            }
            else
            {
                processOtherError(result.d.Status, result.d.Message);
            }
            
        },
        complete: function()
        {
            $('#procedures2 .loading').remove();
            $("#procedures2").css("position", "")
        }
    });
}

//Close the procedure details and clear the text.
function hideProcedureDetails()
{
    $("#proceduredetails").close().empty();
    $('#selectProcedure').close();
}

function showProcedureDetails(target, value)
{
    $(target).parent().parent().find("td").css({ "background-color": "", "color": "" });
    $(target).css({ "background-color": "#003399", "color": "White" });
    $("#procedures2").attr('value', value);
    $("#procedures2").attr('procedureName', $(target).text());
    var procedureID = value;

    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetProcedureDetails",
        data: "{"
                    + "ProcedureID: '" + procedureID + "'"
                    + "}",
        success: function(result)
        {
            $("#proceduredetails").html(result.d);
            $("#proceduredetails").open();
            $('#selectProcedure').open();
            //if the 'Next Step' button to select the procedure is below the bottom of the screen, scroll down so that it's just visible at the bottom.
            //Or let's just do it all the time.
            var item = $('#selectProcedure');
            var pos = item.position().top + item.height() - pageHeight();
            //if (pos > posTop())
            //{
            $.scrollTo(pos + 'px', 800, { axis: 'y' });
            //}
            //$.scrollTo($('#selectProcedure'), 800);       //this didn't work 'cause it scrolled the item to the top of the page
            //document.getElementById('selectProcedure').scrollIntoView(false);    //this didn't work 'cause it popped the page without scrolling, which was confusing
        }
    });
}

// Hit the server so that we can get the selected procedure ID into the session
function selectProcedure()
{
    procedureID = $("#procedures2").attr('value');
    procedureName = $("#procedures2").attr('procedureName');

    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/SelectProcedure",
        data: "{"
                    + "ProcedureID: '" + procedureID + "'"
                    + "}",
        success: function(result)
        {
            if (result.d.Status == statusOK)
            {
                $('#ProcedureName').html(procedureName);
                selProc();
            }
            else if (result.d.Status == statusSessionExpired)
            {
                processSessionExpired();
            }
            else
            {
                processOtherError(result.d.Status, result.d.Message);
            }
        }
    });
}

//Once they've selected a procedure, close that step and open the next step.
//Also, load the map with all the hospitals on this user's plan 
function selProc()
{
    //replace('#selproc .stepcontent', '#selproc .stepdone');
    replace('#selproc .stepcontent', '#selproc .stepdone', function() { $.scrollTo($('.stepseparator:eq(2)'), 800, {axis:'y'}); });    //collapse the identify section
    
    $('#selproc .steptitle img').attr('src', '/WebPages/images/box_checked.gif');
    $('#selhosp .stepcontent').open();
    getFacilitiesByName();
    getFacilitiesByLocation();
    hmap = generateBaseMap('divHospitalsMap', 300, 500);
    getHospitalMapMarkers();
}

//Hit the server to get the selected procedure ID out of the session, and update the page.
function resetProc()
{
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/ResetProc",
        data: "{}",
        success: function(result)
        {
            replace('#selproc .stepcontent', '#selproc .stepdone');
            $('.steptitle img:gt(1)').attr('src', '/WebPages/images/box_empty.gif');  //Reset all but the first check box
            $('.stepcontent:gt(1), .stepdone:gt(1)').close(); //Reset all steps after this one
            $('#createPortal').close();
            $('#FacilityChosen').html('');
            clearHospitalDetails();
            showmap();
        }
    });

}

//Get the list of map markers for hospitals matching the user's plan and selected procedure (already stored in the session).
function getHospitalMapMarkers()
{
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetHospitalMarkers",
        data: "{}",
        success: function(result)
        {
            loadHospitalMarkers(result.d);
        }
    });
}

//Load the markers as overlays on the Google map.
function loadHospitalMarkers(markers)
{
    hmap.clearOverlays();
    $.each(markers, function(index, marker)
    {
        mapPoint = new GLatLng(marker.lat, marker.lon);
        var icon;
        if (marker.type == "h")
        {
            icon = hmap.HospitalIcon;
            HospitalMarker[HospitalMarker.length] = new GMarker(mapPoint, icon);
            hmap.addOverlay(HospitalMarker[HospitalMarker.length - 1]);
            HospitalMarker[HospitalMarker.length - 1].markup = marker.markup;
            HospitalMarker[HospitalMarker.length - 1].hospid = marker.ID;
            GEvent.addListener(HospitalMarker[HospitalMarker.length - 1], 'click', function() { this.openInfoWindowHtml(this.markup); });
        }
        if (marker.type == "u")
        {
            //The overlay for the user's home zip code or address is just an icon, and doesn't get an infowindow popup attached to it.
            icon = hmap.HomeIcon;
            var home = new GMarker(mapPoint, { icon: hmap.HomeIcon, zIndexProcess: orderOfCreation });
            GEvent.addListener(home, 'click', function() { this.openInfoWindowHtml('Your location.'); });
            hmap.addOverlay(home);
        }
    });
}

function orderOfCreation(marker, b)
{
    return -1000000000;
}

function getFacilitiesByName()
{
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetFacilitiesByName",
        data: "{}",
        success: function(result)
        {
            $("#facbyname").fillSelect(result.d, 'Click to select');
        }
    });
}

function getFacilitiesByLocation()
{
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetFacilitiesByLocation",
        data: "{}",
        success: function(result)
        {
            $("#facbyloc").fillSelect(result.d, 'Click to select');
        }
    });
}

//When you select from one list or click the map, we're going to keep the others in sync.
//This variable will prevent recursively calling the getHospitalDetails function. 
var inHospitalDetails = false;

//This will hold the tabs object so that we can use it later (the 'Learn more about your benefit' link will switch to the benefit tab)
var $hosptabs;

//Get the hospital details for the selected hospital.
//The GetHospitalDetails control is going to get the content by creating an instance of the HospitalDetails.ascx control on the fly,
//rendering the control to text, and passing that HTML back.
//On the callback, we will 
//  * load the hospital details markup in the right spot,
//  * show the details div, 
//  * initialize the tabs, 
//  * set the Lytebox effect for any hospital or hotel images,
//  * initialize the hospital details map (the one with the selected hospital and the associated hotels and airports, not the map of all hospitals)
//  * load the markers for the hospital and the associated hotels and airports into this map
function getHospitalDetails(hospitalID)
{
    //Avoid recursion by avoiding recursion.
    if (inHospitalDetails)
    {        
        return;
    }

    if (hospitalID === '')
    {
        inHospitalDetails = true;
        $('#facbyname, #facbyloc').val(''); //Clear both select lists
        hmap.closeInfoWindow(); //Reset the map
        fitMapToPoints(hmap); //Reset the map
        hmap.savePosition(); //This saves the position and zoom for later, so if the user clicks on the hand icon, it'll reset.
        clearHospitalDetails(); ///Clear the hospital details
        inHospitalDetails = false;
        return;
    }

    inHospitalDetails = true;
    //Depending on whether the user selected from a dropdown or by clicking on the map,
    //we want to make sure that everything is synced.
    $('#facbyname, #facbyloc').val(hospitalID);
    hidemap();    
    jQuery.each(HospitalMarker, function()
    {
        if (this.hospid == hospitalID)
        {
            //If this marker's info window isn't already open, open it now
            if (hmap.getInfoWindow() === null || hmap.getInfoWindow().getPoint() != this.getPoint())
            {
                this.openInfoWindowHtml(this.markup);
            }
            return false;  //break out of the loop
        }
        else
        {
            return true; //continue looping
        }
    }
    );
    inHospitalDetails = false;

    //$("#hospitaldetails").css("position", "relative").append('<img class="loading" style="display: block; position: absolute;z-index: 1; left:-1px;top: -1px;" src="/WebPages/images/arrows60.gif" />');
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetHospitalDetails",
        data: "{"
                    + "HospitalID: '" + hospitalID + "'"
                    + "}",
        success: function(result)
        {
            if (result.d.Status == statusOK)
            {
                $("#hospitaldetails").html(result.d.Value);
                $("#hospitaldetails").open();
                $hosptabs = $("#tabs").tabs(
                    {
                        cache: true,
//                        fx:
//                        {
//                            opacity: 'toggle' //, height: 'toggle', duration: 'fast'
//                        }
                        load: function(event, ui)
                        {
                            var selected = $('#tabs').tabs('option', 'selected');
                            if (selected == 6)
                            {
                                getHospitalDetailMapMarkers(hospitalID);
                            }
                        }
                    });
                myLytebox.updateLyteboxItems();
                //hosptabs.tabs("add", '#bob', 'test');
                //getHospitalDetailMapMarkers(hospitalID);
            }
            else if (result.d.Status == statusSessionExpired)
            {
                processSessionExpired();
            }
            else
            {
                processOtherError(result.d.Status, result.d.Message);
            }

        },
        complete: function()
        {
            //$('#hospitaldetails .loading').remove();
            //$("#hospitaldetails").css("position", "")
        }        
    });
}

//Gets the markers for a hospital by ID, along with the associated hotels and airports.
function getHospitalDetailMapMarkers(hospitalID)
{
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetHospitalDetailMarkers",
        data: "{"
            + "HospitalID: '" + hospitalID + "'"
            + "}",
        success: function(result)
        {
            hospmap = generateBaseMap('divExpMap', 320, 600);
            //This map needs to be initialized with a specified height and width.
            //GMaps can't calculate the size now 'cause the div is hidden, so it has no size.
            //See http://docs.jquery.com/UI/Tabs#...my_slider.2C_Google_Map.2C_etc._not_work_when_placed_in_a_hidden_.28inactive.29_tab.3F
            //Also, the reason this generateBaseMap call is here is because, in IE, even though we specify the size when we initialize the GMaps2 object,
            //when we do an ajax call, for some reason the size goes back to zero.
            loadHospitalDetailMarkers(result.d);
            fitMapToPoints(hospmap);
            hospmap.savePosition(); //This saves the position and zoom for later, so if the user clicks on the hand icon, it'll reset.        
        }
    });
}

//Put the markers for a hospital and its hotels and airports on the map.
function loadHospitalDetailMarkers(markers)
{
    var hotelMarkers = [];
    var airportMarkers = [];
    var mapPoints = [];
    hospmap.clearOverlays();
    $.each(markers, function(index, marker)
    {
        mapPoint = new GLatLng(marker.lat, marker.lon);
        var icon;
        if (marker.type == "h")
        {
            icon = hospmap.HospitalIcon;
            hospmap.HospitalMarker = new GMarker(mapPoint, icon);
            hospmap.addOverlay(hospmap.HospitalMarker);
            hospmap.HospitalMarker.markup = marker.markup;
            hospmap.HospitalMarker.hospid = marker.ID;
            GEvent.addListener(hospmap.HospitalMarker, 'click', function() { this.openInfoWindowHtml(this.markup); });
            mapPoints[mapPoints.length] = mapPoint;
        }
        else if (marker.type == "hotel")
        {
            icon = hospmap.HotelIcon;
            hotelMarkers[hotelMarkers.length] = new GMarker(mapPoint, icon);
            hospmap.addOverlay(hotelMarkers[hotelMarkers.length - 1]);
            hotelMarkers[hotelMarkers.length - 1].markup = marker.markup;
            hotelMarkers[hotelMarkers.length - 1].hospid = marker.ID;
            GEvent.addListener(hotelMarkers[hotelMarkers.length - 1], 'click', function() { this.openInfoWindowHtml(this.markup); });
            mapPoints[mapPoints.length] = mapPoint;


            //            var directions = new GDirections();
            //            GEvent.addListener(directions,"load", function() {
            //                    dist = directions.getDistance().meters;
            //                    alert(dist + " meters\n" + 
            //                            (dist * 3.2808399) + " feet\n" + 
            //                            (dist / 1609.344) + " miles");
            //                  });

            //            //loadFromWaypoints needs 2 or more waypoints (lat, lon) in the format "47.620635, -122.32050"
            //            var pointsArray = [hospmap.HospitalMarker.getPoint().toUrlValue(),mapPoint.toUrlValue()];
            //            alert("Trying to get directions from " + pointsArray[0].toString() + " to " + pointsArray[1].toString());
            //            
            //            directions.loadFromWaypoints(pointsArray);


        }
        else if (marker.type == "a")
        {
            icon = hospmap.AirportIcon;
            airportMarkers[airportMarkers.length] = new GMarker(mapPoint, icon);
            hospmap.addOverlay(airportMarkers[airportMarkers.length - 1]);
            airportMarkers[airportMarkers.length - 1].markup = marker.markup;
            airportMarkers[airportMarkers.length - 1].hospid = marker.ID;
            GEvent.addListener(airportMarkers[airportMarkers.length - 1], 'click', function() { this.openInfoWindowHtml(this.markup); });
            mapPoints[mapPoints.length] = mapPoint;
        }
    });
    hospmap.hotelMarkers = hotelMarkers;
    hospmap.airportMarkers = airportMarkers;
    hospmap.mapPoints = mapPoints;
}

//Close the procedure details and clear the text.
function clearHospitalDetails()
{
    $("#hospitaldetails").close().empty();
}

//Hit the server to put the selected hospital in the session, and update the page on the callback
function selectHospital(hospitalID, hospitalName)
{
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/SelectHospital",
        data: "{"
                    + "HospitalID: '" + hospitalID + "'"
                    + "}",
        success: function(result)
        {
            if (result.d.Status == statusOK)
            {
                $('#FacilityChosen').html('You chose facility ' + hospitalName + '.');
                $('#selhosp .steptitle img').attr('src', '/WebPages/images/box_checked.gif');
                //replace('#selhosp .stepcontent', '#selhosp .stepdone');
                replace('#selhosp .stepcontent', '#selhosp .stepdone', function() { $.scrollTo($('.stepseparator:eq(3)'), 800, {axis:'y'}); });    //collapse the identify section
                $('#nextsteps .stepcontent').open();
                display = $('#sbLogin').css("display");
                if (display != 'none')
                {
                    $('#createPortal').open();
                }
                loadContactForm();
            }
            else if (result.d.Status == statusSessionExpired)
            {
                processSessionExpired();
            }
            else
            {
                processOtherError(result.d.Status, result.d.Message);
            }

        }
    });
}

//The user doesn't want to select the hospital yet, so just advance the page to the final 'contact us' step
function skipHospital()
{
    $('#FacilityChosen').html('No facility selected.');
    $('#selhosp .steptitle img').attr('src', '/WebPages/images/box_checked.gif');
    //We can't use the replace() method like normal, 'cause with the last change, 
    //the .stepcontent step isn't even open yet.  Just use a close and an open to insure that the .stepcontent is closed, and to open the .stepdone 
    //replace('#selhosp .stepcontent', '#selhosp .stepdone');
    replace('#selhosp .stepcontent', '#selhosp .stepdone', function() { $.scrollTo($('.stepseparator:eq(3)'), 800, {axis:'y'}); });    //collapse the identify section
    $('#nextsteps .stepcontent').open();
    display = $('#sbLogin').css("display");
    if (display != 'none')
    {
        $('#createPortal').open();
    }
    loadContactForm();
}

function loadContactForm()
{
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/GetContactData",
        data: "{}",
        success: function(result)
        {
            $('#tbfname').val(result.d.first);
            $('#tblname').val(result.d.last);
            $('#tbphone').val(result.d.phone);
            $('#tbemail').val(result.d.email);
            $('#tbprocedure').val(result.d.procedure);
            $('#tbcarecenter').val(result.d.carecenter);
        }
    });
}


//Get the selected hospital out of the session, and update the page
function resetHospital()
{
    $.ajax({
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,
        url: "/WebPages/explore.aspx/ResetHosp",
        data: "{}",
        success: function(result)
        {
            $('#FacilityChosen').html('');
            showmap();
            $('#selhosp .steptitle img').attr('src', '/WebPages/images/box_empty.gif');
            replace('#selhosp .stepdone', '#selhosp .stepcontent');
            $('#nextsteps .stepcontent').close();
            $('#createPortal').close();
        }
    });

}


//GOOGLE MAPS CODE

var HospitalMarker = [];
var hmap;
var hospmap;

function generateBaseMap(target, height, width)
{
    var mapPoint;

    //Create the GMap2 object.  Normally it will calculate the size based on the container size, 
    //but if you're doing this on a div that's currently hidden, you'll have to specify the size.
    if ((height === null || height == undefined) && (width === null || width == undefined))
    {
        map = new GMap2(document.getElementById(target));
    }
    else
    {
        map = new GMap2(document.getElementById(target), { size: new GSize(width, height) });
    }

    //Add the map controls
    map.addControl(new GLargeMapControl3D());
    map.addControl(new GScaleControl());
    map.addControl(new GMenuMapTypeControl());
    //var ov = new GOverviewMapControl();
    //map.addControl(ov);
    //ov.hide();
    
    //Create a base icon
    var baseIcon = new GIcon();
    baseIcon.iconSize = new GSize(32, 32);
    baseIcon.shadowSize = new GSize(59, 32);
    baseIcon.iconAnchor = new GPoint(16, 32);
    baseIcon.infoWindowAnchor = new GPoint(16, 0);

    //Create some icons and attach them to the GMap2 object for use later.
    map.HospitalIcon = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon46.png");
    map.HospitalIcon.shadow = "http://maps.google.com/mapfiles/kml/pal3/icon46s.png";
    map.HotelIcon = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon28.png");
    map.HotelIcon.shadow = "http://maps.google.com/mapfiles/kml/pal2/icon28s.png";
    map.AirportIcon = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon56.png");
    map.AirportIcon.shadow = "http://maps.google.com/mapfiles/kml/pal2/icon56s.png";
    //map.HomeIcon = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal4/icon47.png");
    //map.HomeIcon.shadow = "http://maps.google.com/mapfiles/kml/pal4/icon47s.png";
    map.HomeIcon = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal3/icon56.png");
    map.HomeIcon.shadow = "http://maps.google.com/mapfiles/kml/pal3/icon56s.png";

    //These two lines used to center the map on the approximate center of the continental US, but this was replaced by the lines below.
    //    mapPoint = new GLatLng(36.623238, -95.147934);
    //    map.setCenter(mapPoint, 3);

    //Create two points for the northwest and southeast points of the continental US.
    //Then, we can call fitMapToPoints to automatically position and zoom the map to fit the continental US based on the size of the map.
    //These may be overridden later for other maps like the hospital details.
    //the important thing is that you MUST call map.setCenter before you call any other function of a GMaps2 object.
    mapPoints = [];
    mapPoints[mapPoints.length] = new GLatLng(49.384472, -124.733055);
    mapPoints[mapPoints.length] = new GLatLng(24.4467, -66.9478);
    map.mapPoints = mapPoints;
    fitMapToPoints(map);
    map.savePosition(); //This saves the position and zoom for later, so if the user clicks on the hand icon, it'll reset.

    return map;
}

//This assumes that the GMap2 object has a property called mapPoints that's an array of GLatLng objects.
//It'll set the map to the correct center and zoom level to make sure that all of those points are in view,
//based on the current size of the map.
function fitMapToPoints(map)
{
    var bounds = new GLatLngBounds();
    for (var i = 0; i < map.mapPoints.length; i++)
    {
        bounds.extend(map.mapPoints[i]);
    }
    map.setCenter(bounds.getCenter());    
    map.setZoom(map.getBoundsZoomLevel(bounds));
}

function sendMessage()
{
    //First, get the data from the form fields.  
    //You don't need to do this separately, but it makes the stuff below a little easier to read.
    fname = $("#tbfname").noWatermarkVal();
    lname = $("#tblname").noWatermarkVal();
    phone = $("#tbphone").noWatermarkVal();
    email = $("#tbemail").noWatermarkVal();
    procedure = $("#tbprocedure").noWatermarkVal();
    care = $("#tbcarecenter").noWatermarkVal();
    comment = $("#tbcomment").noWatermarkVal();
    inqtype = $("input[@name='rblist_0']:checked").val();


    $.ajax({
        //For calling ASP.NET web methods, the first four parameters probably won't ever need to be changed.
        type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", cache: false,

        // Put in the page path and the name of the web method you're calling.
        url: "/HPAPortal/services/HPAPortalServices.asmx/SendContactInfo",

        //Pass the variables
        data: "{"
                    + "fname: '" + fname + "'"
                    + ", lname: '" + lname + "'"
                    + ", phone: '" + phone + "'"
                    + ", email: '" + email + "'"
                    + ", procedure: '" + procedure + "'"
                    + ", care: '" + care + "'"
                    + ", comment: '" + comment + "'"
                    + ", inqtype: '" + inqtype + "'"
                    + "}",
        success: function(result)
        {
            //sendMessageCallback(result);
            //Call another method, or just use some alerts here for testing.  I'll finish the details later.
            if (result.d.success)
            {
                replace('#sendMessage', '#messageSent');
            }
            else
                $("#ContactError").html(result.d.message).show();

            //            alert( result.d );
            //            alert( result.d.message );
            //            alert( result.d.success );
            ////            alert(result.d);
            //            alert(result.d.Success);
            //            alert(result.d.ErrorMessage);
        }
    });
}

function setWatermarks()
{
    $(".watermark").each(function(i)
    {
        $(this).attr('watermarkText', $(this).val());
        $(this).focus(function()
        {
            if ($(this).val() == $(this).attr('watermarkText'))
            {
                $(this).val("");
            }
        }).blur(function()
        {
            if ($.trim($(this).val()) == "")
            {
                $(this).val($(this).attr('watermarkText'));
            }
        });
    });
}

$.fn.noWatermarkVal = function()
{
    if ($(this).attr('watermarkText') == $(this).val())
    {
        return "";
    }
    else
    {
        return $(this).val();
    }
};

function showmap()
{
    $('#divHospitalsMap').parent().open();
    $('#showmap').close();
}

function hidemap()
{
    $('#divHospitalsMap').parent().close();
    $('#showmap').open();
}

function processSessionExpired()
{
    alert("Your session has expired -- you will need to start over..");
    logOutCallback();
}

function processOtherError(Status, Message)
{
    //alert("Status is " + status + " and Message is " + Message);
}

// Browser Window Size and Position
// copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
// you may copy these functions but please keep the copyright notice as well
function pageWidth() { return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null; }
function pageHeight() { return window.innerHeight != null ? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null ? document.body.clientHeight : null; }
function posLeft() { return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0; }
function posTop() { return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0; } function posRight() { return posLeft() + pageWidth(); } function posBottom() { return posTop() + pageHeight(); }
                    