/* ---------------------------------------------------------------------------
    snap_search.js
    Copyright (C) 2007 SNAPforSeniors, Inc.
    
    A library of JavaScript functions which enable remote SNAPforSeniors 
    searches which direct the user to the SNAPforSeniors home page.
    
    Modification History
    --------------------
    2007-01-20 created by John Vinyard (john dot vinyard at snapforseniors dot com)
    
    2007-03-28 modifed by Ed Vinyard (ed dot vinyard at snapforseniors dot com)
        integrated new snap_friendlyurl.js function calls to replace parameter
        parsing and URL construction that were previously done in this file;
        also, this file is now used in both the home page search HTML fragment
        and the search results page HTML fragment.
    
   --------------------------------------------------------------------------- */

// images
var BASE_IMG_URL = SiteBaseUrl(window.location.href) + "/Portals/0/UI/";

var PLUS_IMG_SRC = BASE_IMG_URL + "plus.gif";
var MINUS_IMG_SRC = BASE_IMG_URL + "minus.gif";
var SECTION_IMG_SRC_COLLAPSED_GREEN = BASE_IMG_URL + "button-COLLAPSED-ON.gif";
var SECTION_IMG_SRC_COLLAPSED_GREY = BASE_IMG_URL + "button-COLLAPSED-OFF.gif";
var SECTION_IMG_SRC_EXPANDED_GREEN = BASE_IMG_URL + "button-EXPANDED-ON.gif";
var SECTION_IMG_SRC_EXPANDED_GREY = BASE_IMG_URL + "button-EXPANDED-OFF.gif";

// div visibility 
var COLLAPSED = "none";
var EXPANDED = "block"; 
var RADIO_TOGGLE_ID_SUFFIX = "_Toggle_s";

// cookie handling
var cookieDelimiter = "|";
var cookieName = "SnapForSeniorsSearch";

// input element default values
var LOCATION_DEFAULT_TEXT = "e.g., Seattle, WA or 98116 or King Co, WA";
var NAME_DEFAULT_TEXT = "Enter Facility Name or ID#";
var CHAIN_DEFAULT_TEXT = "Enter Chain Name";

// input element IDs
var LocationID = "l_s";
var NameID = "n_s";
var ChainID = "ch_s";
var VacanciesFirstID = "vf_s";
var AssistedLivingID = "AL_s";
var SkilledNursingID = "SN_s";
var IndependentLivingID = "IL_s";
var ContinuingCareID = "CC_s";

var DefaultCheckboxValues = new Object();
DefaultCheckboxValues[VacanciesFirstID] = true;
DefaultCheckboxValues[AssistedLivingID] = true;
DefaultCheckboxValues[SkilledNursingID] = true;
DefaultCheckboxValues[IndependentLivingID] = true;
DefaultCheckboxValues[ContinuingCareID] = false;

var INPUT = "INPUT";
var Sections = new Array("LivingSpaceanyof_s","PaymentAccepted_s","RespiteCare_s","PersonalAssistance_s",
                        "Transportation_s","SpecializedCare_s","NursingCare_s","DietaryOptions_s","Languages_s");
var attrbsToGet = new Array("style");
var interval;
var helpBox;
var helpTextContainer;

var owol = window.onload;
var owoul = window.onunload;

window.onload = function() {if (owol) owol(); RestoreState(); }
window.onunload = function() {if (owoul) owoul(); Serialize(); }

function SetImgSrc(img, src) {
    img.src = SiteBaseUrl() + src;
}

var MAP_INPUT_ID_TO_DEFAULT_TEXT = new Object();
MAP_INPUT_ID_TO_DEFAULT_TEXT[NameID] = NAME_DEFAULT_TEXT;
MAP_INPUT_ID_TO_DEFAULT_TEXT[LocationID] = LOCATION_DEFAULT_TEXT;
MAP_INPUT_ID_TO_DEFAULT_TEXT[ChainID] = CHAIN_DEFAULT_TEXT;

function InitializeTextInputFontStyles() {
    for (var id in MAP_INPUT_ID_TO_DEFAULT_TEXT) {
        var inputElement = document.getElementById(id);
        if (inputElement) {
            if (inputElement.value == MAP_INPUT_ID_TO_DEFAULT_TEXT[id]) {
                inputElement.style.fontStyle = "italic";
            } else {
                inputElement.style.fontStyle = "normal";
            }
        }
    }        
}    
    
function FocusTextInput(focusedInput) {
    var ch_div = document.getElementById("FacilityChainSearch");
    var IsChainSearch = (ch_div && ch_div.style && (ch_div.style.display == "block"));
    
    for (var id in MAP_INPUT_ID_TO_DEFAULT_TEXT) {
        var inputElement = document.getElementById(id);
        DisableKeyboardSubmitOn(inputElement);

        if (id == focusedInput.id) {
            inputElement.style.fontStyle = "normal";
            
            if (inputElement.value == MAP_INPUT_ID_TO_DEFAULT_TEXT[id]) {
                inputElement.value = "";
            }
        } else {
            if (!IsChainSearch || (inputElement.value == "")) {
                inputElement.style.fontStyle = "italic";
                inputElement.value = MAP_INPUT_ID_TO_DEFAULT_TEXT[id];
            }
        }
    }

    EnableKeyboardSubmitOn(focusedInput);
}

function EnableKeyboardSubmitOn(element) {
    if (!element) return;
    if (/Apple/.test(navigator.userAgent)) {
        window.onkeydown = window.onkeyup = function(kbd) {
            if (kbd.keyCode == 13) {
                Submit();
                return false;
            }
        }
        
    } else if (isIE) {
        element.onkeypress = function() {
            if (window.event.keyCode == 13) {
                Submit();
                return false;
            }
        }
    } else {
        window.onkeyup = function(kbd) {
            if (kbd.keyCode == 13) {
                Submit();
            }
        }
    }
}

function DisableKeyboardSubmitOn(element) {
    if (!element) return;
    if (/Apple/.test(navigator.userAgent)) {
        window.onkeydown = window.onkeyup = null;
    } else if (isIE) {
        element.onkeypress = null;
    } else { 
        window.onkeyup = undefined; 
    }
}

function IsSectionExpanded(imgSrc) {
    return -1 < imgSrc.search(/button-EXPANDED-(ON|OFF).gif$/i);
}

function IsSectionOn(imgSrc) {
    return -1 < imgSrc.search(/button-(EXPANDED|COLLAPSED)-ON.gif$/i);
}

function GetSectionImgSrc(isExpanded, isOn) {
    var expandedState = isExpanded ? 'E' : 'C';
    var onState = isOn ? 'ON' : 'OFF';
    var sources = {
        E: {    
            ON : SECTION_IMG_SRC_EXPANDED_GREEN,
            OFF : SECTION_IMG_SRC_EXPANDED_GREY
        },
        C: {
           ON : SECTION_IMG_SRC_COLLAPSED_GREEN,
           OFF : SECTION_IMG_SRC_COLLAPSED_GREY
        }
    };
    return sources[expandedState][onState];
}


function RestoreState() {
    //get reference to hidden div
    var helpContainer = document.getElementById("helpBox");
    var helpTextContainer = document.getElementById("helpTextContainer");
    //get the SnapForSeniorsSearch cookie if it has been set
    var stateCookie = GetCookie(cookieName);
    
    SetCheckboxes(GetParams());
    
    // Hide the chain search switcher link if we're already locked into an aff param
    var ps = GetParams();
    if (ps["aff"] != null) {
        if (typeof(HideChainSearch) != undefined)
            HideChainSearch();
    } else {
        // Switch to the chain search if it's in the query string
        if (ps["ch"] != null) {
            if (typeof(ToggleChainSearch) != undefined)
                ToggleChainSearch();
        }
    }
    
    
    if (stateCookie) {
        var nodes = GetSerializedTags();
        var states = stateCookie.split(cookieDelimiter);
        states.reverse();
        for (var q = 0; q < nodes.length; q++) {
            var tmpNode = nodes[q];
            for (var i = 0; i < attrbsToGet.length; i++) {
                var tmpNodeId = tmpNode.id.split('_');
                
                Restore:
                if (tmpNodeId[tmpNodeId.length - 1] != "Title") {
                    var tmpValue = tmpNode[attrbsToGet[i]];
                    if (typeof(tmpValue) == "object") {
                        if (tmpValue.display != "") {
                            tmpValue.display = states.pop();
                        }
                        break Restore;
                    }
                    if (tmpValue != null && tmpValue != undefined && tmpValue != "" ) {
                        tmpNode[attrbsToGet[i]] = states.pop();
                        break Restore;
                    }
                }
            }
        }
    }
    
    for (var q = 0; q < Sections.length; q++) {
        var sectionElement = document.getElementById(Sections[q]);
        if (sectionElement) {
            SetSrc(sectionElement);
            
            inputElements = sectionElement.getElementsByTagName(INPUT);

            if (inputElements.length > 0) {
                ToggleRadioButton(inputElements[0]);
            }
        }
    }
    
    InitializeTextInputFontStyles();
    
    if (typeof(QuickSearchRestoreState) != "undefined")
        QuickSearchRestoreState();
}

function SetCheckboxes(dict) {
    var catIsInQueryString = false;
    var categories = new Array(AssistedLivingID,IndependentLivingID,SkilledNursingID,ContinuingCareID);
    for (var x in dict) {
        if (x == "cat") {
            catIsInQueryString = true;
            cats = dict[x].split('-');
            for (var i = 0; i < categories.length; i++) {
                var box = document.getElementById(categories[i]);
                if (!box) continue;
                if (Contains(cats,categories[i].split('_')[0])) {
                    box.checked = true;
                } else {
                    box.checked = false;
                }
            }
        } else {
            element = document.getElementById(FormatParamKey(x));
            if (element) {
                if (element.type == "checkbox") {
                    if (dict[x].toUpperCase() == "TRUE") {
                        element.checked = true;
                    }
                    else if (dict[x].toUpperCase() == "FALSE") {
                        element.checked = false;
                    }
                    
                    if (element.id != VacanciesFirstID) {
                        ToggleRadioButton(element);
                    }
                }
                if (element.type == "text") {
                    element.value = decodeURIComponent(dict[x]);
                }
            }
        }
    }
    
    // Is there's no active search, set the checkboxes to their default values
    if (!catIsInQueryString) {
        for (var i = 0; i < categories.length; i++) {
            var checkbox = document.getElementById(categories[i]);
            checkbox.checked = DefaultCheckboxValues[categories[i]];
        }
    }
}

// ---------------------------------------------------------------------------
// Given a query parameter key, return the corresponding search criteria 
// element ID.
// ---------------------------------------------------------------------------
function FormatParamKey(key) {
    var splt = key.split('-');
    var idName = "";
    for (var q = 0; q < splt.length; q++) {
        if (q != 0) {
            splt[q] = splt[q].substring(0,1).toUpperCase() + splt[q].substring(1);
        }
        idName += splt[q];
    }
    idName += "_s";
    return idName;
}

// ---------------------------------------------------------------------------
// check for cookie
// get the aspsessionid cookie
// use its value as part of jscookiename
// on load, check for cookienamed [ASPSESSIONID] + jsCookie
// ---------------------------------------------------------------------------
function GetCookie(CookieName) {
    if (document.cookie) {
        var cookies = document.cookie.split(";");
        for (var j = 0; j < cookies.length; j++) {
            var NameValue = cookies[j].split("=");
            if (NameValue[0].replace(' ','') == CookieName.replace(' ','')) {
                return NameValue[1];
            }
        }
        return null;
    } else {
        return null;
    }
}

// ---------------------------------------------------------------------------
// Set a client side cookie with the specified content.  The cookie expiration
// date will be one week from the time this function is invoked.
// ---------------------------------------------------------------------------
function SetCookie(cookieContent) {
    // compute the number of milliseconds in one week
    var oneWeekMsec = (7 * 24 * 60 * 60 * 1000); 
    
    // the cookie expiration date will be one week from now
    var expDate = new Date();
    expDate.setTime(expDate.getTime() + oneWeekMsec);
    
    // set the cookie content
    document.cookie = cookieContent + " expires=" + expDate.toGMTString() + "; path=/;";
}

// ---------------------------------------------------------------------------
// Returns the deepest ancestor DOM node of 'element' whose element ID 
// matches the supplied regular expression, 'idRegExp'.
// ---------------------------------------------------------------------------
function FindAncestor(domNode, idRegExpStr) {
    var idRegExp = new RegExp(idRegExpStr);
    var ancestorNode = domNode;
    var isIdMatch = false;

    while (ancestorNode && !isIdMatch) {
        ancestorNode = ancestorNode.parentNode;
        if (!ancestorNode) isIdMatch = false;
        else isIdMatch = (
            (ancestorNode.nodeType == 1) && // ELEMENT_TYPE
            (ancestorNode.id != null) &&
            (-1 < ancestorNode.id.search(idRegExp))
            );
    }

    if (ancestorNode && isIdMatch) {
        return ancestorNode;
    } else {    
        return null;
    }
}

// ----------------------------------------------------------------------------
// Sets the section "toggle" (the trianglular image which indicates 
// expanded-ness by orientation and enabled-ness by color) for a search 
// criteria input element.  The new setting is based on the current expanded-
// ness of the section.  The new enabled-ness is determined by inspecting all
// of the input elements in the section.  If at least one of them is checked,
// the new value is "on".  If none are checked, the new value is "off".
// ----------------------------------------------------------------------------
function ToggleRadioButton(inputElement) {
    var criteriaSection = FindAncestor(inputElement, "_Title$");

    if (!criteriaSection) return;
    
    // Find the toggle that corresponds to the section container div.
    var idPrefix = criteriaSection.id.split('_')[0];
    var toggleId = idPrefix + RADIO_TOGGLE_ID_SUFFIX;
    var toggleElement = document.getElementById(toggleId);
    
    // Discover the check-edness of each descendant input element.
    var inputElements = criteriaSection.getElementsByTagName(INPUT);
    var anyChecked = false;
    
    for (var i = 0; i < inputElements.length; i++) {
        anyChecked = anyChecked || inputElements[i].checked;
    }
    
    // Set the toggle/icon/triangle image to the left of the section title.
    var isExpanded = IsSectionExpanded(toggleElement.src);
    toggleElement.src = GetSectionImgSrc(isExpanded, anyChecked);
}

// ----------------------------------------------------------------------------
// Marshals the values of all search criteria input elements, then sets a 
// cookie to persist the marshalled values.
// ----------------------------------------------------------------------------
function Serialize() {
    var nodes = GetSerializedTags();
    var values = [];
    for (var q = 0; q < nodes.length; q++) {
        for (var i = 0; i < attrbsToGet.length; i++) {
            var tmpValue = nodes[q][attrbsToGet[i]];
            if (typeof(tmpValue) == "object") {
                tmpValue = tmpValue.display
            }
            if (nodes[q].tagName == INPUT && attrbsToGet[i] == "checked") {
                if (tmpValue == ""){
                    tmpValue = "false";
                }
            }
            if (tmpValue != null && tmpValue != undefined && tmpValue != "") {
                values.push(tmpValue);
            }
        }
    }

    // On the home page, and in other places where there aren't any criteria
    // sections, we should leave the existing cookie intact.    
    if (values.length > 0) {
        var cookieString = cookieName + "=" + values.join(cookieDelimiter)  + ";";
        SetCookie(cookieString);
    }
    
    if (typeof(QuickSearchSerialize) != "undefined")
        QuickSearchSerialize();
}

// ----------------------------------------------------------------------------
// Returns an array of elements for which state should be preserved in the
// cookie.
// ----------------------------------------------------------------------------
function GetSerializedTags() {
    var tagsToGet = new Array("DIV");
    var tags = new Array();
    var serializedTags = new Array();

    for (var i = 0; i < tagsToGet.length; i++) {
        var tmp = document.getElementsByTagName(tagsToGet[i]);
        for (var j = 0; j < tmp.length; j++) {
            tags.push(tmp[j]);
        }
    }

    for (var q = 0; q < tags.length; q++) {
        var splitId = tags[q].id.split('_');
        if (splitId[splitId.length - 1] == "s" || splitId[splitId.length - 1] == "Title") {
            serializedTags.push(tags[q]);
        }
    }

    return serializedTags;
}

// ----------------------------------------------------------------------------
// Returns true iff the array, 'arr', contains the string 'value'.
// ----------------------------------------------------------------------------
function Contains(arr, value) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == value) {
            return true;
        }
    }
    return false;
}

// ----------------------------------------------------------------------------
// Constructs a query string based on the values of search criteria input
// elements and submits the search as a GET query (by setting window.location).
//
// If showHelp is not supplied or is false, the browser is directed to the
// search results page.  If  showHelp is true, the browser is directed to the 
// search help page rather than the search results page.
// ----------------------------------------------------------------------------
function Submit(showHelp) {
    var params = new Object(); // search query parameters
    
    // Preserve "aff" param (for narrowing a search after following a 
    // pre-constructed license or facility chain name search).  There is 
    // currently no UI to construct these searches manually -- when there
    // is, >>THIS SHOULD BE REMOVED<<
    var old_params = GetParams();
    if (old_params["aff"] != null)
        params["aff"] = old_params["aff"];
    

    // Facility Name or SNAP ID
    var PARTY_ID_REGEXP = /^\s*\d{3}\s*[^\d\s]?\s*\d{3}\s*$/;
    var facName = document.getElementById(NameID).value;

    // Search Locale
    var searchLocale = document.getElementById(LocationID);
    
    // Chain name 
    var chainNameTbox = document.getElementById(ChainID);
    if (chainNameTbox &&  (chainNameTbox.value != "") && (chainNameTbox.value != CHAIN_DEFAULT_TEXT)) {
        params["ch"] = chainNameTbox.value;
    }
    
    if ((facName != "") && (facName != NAME_DEFAULT_TEXT)) {
        params["n"] = facName;
        //  On the ELDR portal, we can ignore the other parameters except vacancy and just execute the search
//        if (window.location.hostname.toLowerCase().match(/eldr/)) {
//            var vac_cb = document.getElementById(VacanciesFirstID);
//            if (vac_cb) params["vf"] = vac_cb.checked.toString();
//            window.location = SearchResultsUrl(params);   
//            return;
//        }
    } else if ((searchLocale.value.length) > 0 && (searchLocale.value != LOCATION_DEFAULT_TEXT)) {
        params[searchLocale.name] = searchLocale.value;
    }
    
    // www.snapforseniors.com-specific UI stuff -- only submit what's actually visible
    var name_div = document.getElementById("FacilityNameSearch");
    var ch_div = document.getElementById("FacilityChainSearch");
    var nameIsVis = true;
    var chIsVis = true;
    if (name_div && name_div.style && (name_div.style.display == "none"))
        nameIsVis = false;
    if (ch_div && ch_div.style && (ch_div.style.display == "none"))
        chIsVis = false;
    if (nameIsVis && !chIsVis) {
        if (params["ch"] != null) delete params["ch"];
        if ((params["n"] != null) && (params[searchLocale.name] != null))
            delete params[searchLocale.name];
    }
    if (!nameIsVis && chIsVis) {
        if (params["n"] != null) delete params["n"];
    }
    
    // Search Categories (i.e., IL, AL, SN)
    var categoryCheckBoxes = new Array(
        document.getElementById(AssistedLivingID), 
        document.getElementById(IndependentLivingID),
        document.getElementById(SkilledNursingID),
        document.getElementById(ContinuingCareID));
    var checkedCategories = new Array();

    for (var i = 0; i < categoryCheckBoxes.length; i++) {
        if (categoryCheckBoxes[i].checked) {    
            checkedCategories.push(categoryCheckBoxes[i].name);
        }
    }
    
    if (checkedCategories.length > 0) {
        params["cat"] = checkedCategories.join('-');
    }
    
    // Advanced Search Criteria
    var SEARCH_CRITERIA_ID_REGEXP = /_s$/i;
    var inputsElements = document.getElementsByTagName(INPUT);
    var excludedInputIds = new Array(
        LocationID, 
        AssistedLivingID, 
        IndependentLivingID, 
        SkilledNursingID, 
        ContinuingCareID,
        NameID,
        ChainID);
    
    for (var q = 0; q < inputsElements.length; q++) {
        var inputElement = inputsElements[q];
        var isSearchCriteria = (-1 < inputElement.id.search(SEARCH_CRITERIA_ID_REGEXP));
        var isExcluded = Contains(excludedInputIds, inputElement.id);
        var isVacanciesFirstElement = (inputElement.id == VacanciesFirstID);
        var isCheckBox = (inputElement.type == "checkbox");

        if (isSearchCriteria && !isExcluded) {
            if (isCheckBox && (isVacanciesFirstElement || inputElement.checked)) {
                params[inputElement.name] = inputElement.checked.toString();
            } else if (Contains(["radio", "text", "hidden"], inputElement.type)) {
                params[inputElement.name] = encodeURIComponent(inputElement.value);
            }
        }
    }
    
    if (showHelp) {
        window.location = SearchHelpUrl(params);
        return;
    } else {
        window.location = SearchResultsUrl(params);
        return;
    }
}

function ToggleSearchBar() {
    var img = document.getElementById("toggleImage");
    var txt = document.getElementById("toggleText");
    var searchPane = document.getElementById("SearchPane");
    var divs = document.getElementsByTagName("div");
    var srleft_regexp = new RegExp("srleft");
    var srleft;
    var srcenter_regexp = new RegExp("srcenter");
    var srcenter;
    var hilite_photo_regexp = new RegExp("SearchResultsListingHighlightsPhoto");
    var hilite_nophoto_regexp = new RegExp("SearchResultsListingHighlightsNoPhoto");
    var vacancy_regexp = new RegExp("SearchResultsListingVacancy");
    var moreinfo_regexp = new RegExp("SearchResultsListingMoreInfoButton");
    var header_regexp = new RegExp("SearchResultsListingHeaderR");
    var header_center_regexp = new RegExp("SearchResultsListingHeader");
    
    var tmpState = searchPane.style.display;
    for (var i = 0; i < divs.length; i++) {
        if (srleft_regexp.test(divs[i].className)) srleft = divs[i];
        if (srcenter_regexp.test(divs[i].className)) srcenter = divs[i];

        /*if ((vacancy_regexp.test(divs[i].className)  || 
            moreinfo_regexp.test(divs[i].className)) && (isIE)) {
            if (tmpState == "block")
                divs[i].style.right = -1;
            else
                divs[i].style.right = 0; 
        }*/
        if (header_regexp.test(divs[i].className) && (isIE)) {
            if (tmpState == "block")
                divs[i].style.right = -1;
            else
                divs[i].style.right = 0; 
        }
        
        /*if (header_center_regexp.test(divs[i].className)) {
            if (tmpState == "block")
                divs[i].style.width = "736px";
            else
                divs[i].style.width = "506px";
        }*/
    }
    
    if (tmpState == "block") {
        searchPane.style.display = "none";
        img.src = PLUS_IMG_SRC;
        txt.firstChild.nodeValue = " Show Search Options";
        if (srleft) srleft.style.display = "none";
        if (srcenter) {
		if (isIE) srcenter.style.width = "726px";
		else srcenter.style.width = "730px";
	}
    } else {
        searchPane.style.display = "block";
        img.src = MINUS_IMG_SRC;
        txt.firstChild.nodeValue = " Hide Search Options";
        if (srleft) srleft.style.display = "inline";
        if (srcenter) { 
		if (isIE) srcenter.style.width="496px"; 
		else srcenter.style.width = "500px";
	}
    }
}

function Toggle(section) {
    var toToggle;
    var id;
    var tag;
    
    if (section.tagName == "IMG") {
        id = section.id.split('_')[0] + "_s";
        toToggle = document.getElementById(id);
        tag = section;
    } else {
        var reg = /\(/g;
        var reg2 = /\)/g;
        var space = /\s/g;
        id = section.firstChild.nodeValue.split(':')[0].replace(space,'').replace(reg,'').replace(reg2,'') + "_s";
        toToggle = document.getElementById(id);
        tag = document.getElementById(toToggle.id.split('_')[0] + "_Toggle_s");
    }
    toToggle = document.getElementById(id);

    // Discover old (current) state
    var oldExpandState = toToggle.style.display.toString();
    var oldIsExpanded = (oldExpandState == EXPANDED);

    // Determine new (next) state
    var newIsExpanded = !oldIsExpanded;
    var newExpandState = newIsExpanded ? EXPANDED : COLLAPSED;
    
    var isOn = IsSectionOn(tag.src); // "on" state won't change
    tag.src = GetSectionImgSrc(newIsExpanded, isOn);
    toToggle.style.display = newExpandState;
}
function SetSrc(element) {
	var id = element.id;
	var imgTag = document.getElementById(id.split('_')[0] + RADIO_TOGGLE_ID_SUFFIX);
	var isExpanded = (element.style.display == EXPANDED);
	var isOn = IsSectionOn(imgTag.src);
	imgTag.src = GetSectionImgSrc(isExpanded, isOn);
}
function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}
function MakeHelpBox(element) {
    var helpLink = document.getElementById("helpLink");
    helpBox = document.getElementById("helpBox");
    var pos = findPos(helpLink);
    helpBox.style.top = (pos[1] + 40).toString() + "px";
    helpBox.style.left = (pos[0] - 10).toString() + "px";
    helpBox.style.height = "0px";
    helpBox.style.display = "block";
    interval = window.setInterval(Expand,1);
}

function Expand() {
    var pix = ParsePixels(helpBox.style.height);
    if (pix < helpTextContainer.offsetHeight) {
        helpBox.style.height = ToPixels(pix + 10);
    } else {
        helpBox.style.height = helpTextContainer.offsetHeight;
        window.clearInterval(interval);
    }
}

function KillHelpBox() {
    var helpBox = document.getElementById("helpBox");
    helpBox.style.display = "none";
}

// ----------------------------------------------------------------------------
// Reset all search criteria (not just "advanced" criteria check boxes) to 
// default values.
// ----------------------------------------------------------------------------
function StartOver() {

    // reset the location text box
    var txtLocale = document.getElementById(LocationID);
    txtLocale.value = LOCATION_DEFAULT_TEXT;
    
    // reset the name/ID text box
    var txtNameOrId = document.getElementById(NameID);
    txtNameOrId.value = NAME_DEFAULT_TEXT;
    
    // reset the vacancies first check box
    var cbVacanciesFirst = document.getElementById(VacanciesFirstID);
    cbVacanciesFirst.checked = DefaultCheckboxValues[VacanciesFirstId];
    
    // reset the Independent Living check box
    var cbIndependentLiving = document.getElementById(IndependentLivingID);
    cbIndependentLiving.checked = DefaultCheckboxValues[IndependentLivingID];

    // reset the Assisted Living check box
    var cbAssistedLiving = document.getElementById(AssistedLivingID);
    cbAssistedLiving.checked = DefaultCheckboxValues[AssistedLivingID];

    // reset the SkilledNursing check box
    var cbSkilledNursing = document.getElementById(SkilledNursingID);
    cbSkilledNursing.checked = DefaultCheckboxValues[SkilledNursingID];
    
    // CCRC checkbox
    var cbContinuingCare = document.getElementById(ContinuingCareID);
    cbContinuingCare.checked = DefaultCheckboxValues[ContinuingCareID];
    
    // clear all advanced search criteria check boxes
    ClearOptions();
}

// ----------------------------------------------------------------------------
// Clear all of the advanced search criteria check boxes.
// ----------------------------------------------------------------------------
function ClearOptions() {
    var tags = document.getElementsByTagName("INPUT");
    for (var i = 0; i < tags.length; i++) {
        if (tags[i].type == "checkbox") {
            if (tags[i].name == "IL" || tags[i].name == "AL" || tags[i].name == "SN" || tags[i].name == "CC" || tags[i].name == "vf") {
                tags[i].checked = true;
            } else {
                tags[i].checked = false;
            }
        }
    }
    //RESET IMAGES
    var imgElements = document.getElementsByTagName("IMG");
    for (var i = 0; i < imgElements.length; i++) {
        var img = imgElements[i];
        var isSearchCriteriaSectionImg = 
            (-1 < img.src.search(/button-(EXPANDED|COLLAPSED)-(ON|OFF).gif$/i));
            
        if (isSearchCriteriaSectionImg) {
            var isExpanded = IsSectionExpanded(img.src);
            img.src = GetSectionImgSrc(isExpanded, false);
        }
    }
}

function MouseOver(element) {
    element.style.color = "#ff0000";
    element.style.textDecoration = "none";
}

function MouseOut(element) {
    element.style.color = "#000000";
    element.style.textDecoration = "underline";
    
}
function ParsePixels(str) {
    pix = parseInt(str);
    return pix;
}
function ToPixels(num) {
    return num.toString() + "px";
}

