/* ---------------------------------------------------------------------------
    hp_search.js
    Copyright (C) 2007-2008 SNAPforSeniors, Inc.
    
    Stripped-down version of snap_search.js for use with snapforseniors.com home page only.
    
   --------------------------------------------------------------------------- */

// 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 INPUT = "INPUT";
var attrbsToGet = new Array("style");

var owol = window.onload;
var owoul = window.onunload;

window.onload = function() {if (owol) owol(); RestoreState(); }
window.onunload = function() {if (owoul) owoul(); Serialize(); }

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;

var Tabs = []; // will fill this in later
var ActiveTab;

function DisableMouseSelection(name) {
    var element = document.getElementById(name);
    element.onselectstart = function () { return false; } // ie
    element.onmousedown = function () { return false; } // mozilla
}
function DisableALILSNFCheckboxes() { 
    DisableCheckbox("AL_l");
    DisableCheckbox("IL_l");
    DisableCheckbox("SN_l");
}
function EnableALILSNFCheckboxes() {
    EnableCheckbox("AL_l");
    EnableCheckbox("IL_l");
    EnableCheckbox("SN_l");
}   
function EnableCheckbox(name) {
    var lbl = document.getElementById(name);
    if (lbl.className.indexOf("c_on") != -1) {
        lbl.className = "label_check c_on";
    } else {
        lbl.className = "label_check c_off";
    }    
    var inp = gebtn(lbl,'input')[0];
    inp.disabled = false;
}
function DisableCheckbox(name) {
    var lbl = document.getElementById(name);
    if (lbl.className.indexOf("c_on") != -1) {
        lbl.className = "label_check c_on_d";
    } else {
        lbl.className = "label_check c_off_d";
    }    
    var inp = gebtn(lbl,'input')[0];
    inp.disabled = true;
}
function ccrc_click(elm) {
    var x;
    if (elm.checked) {
        DisableALILSNFCheckboxes();
    } else {
        EnableALILSNFCheckboxes();
    }
} 
function QuickSearchRestoreState() {
    // Disable other checkboxes if the CCRC checkbox is checked
    var ccrc_chk = document.getElementById("CC_s");
    if (ccrc_chk && ccrc_chk.checked) 
        DisableALILSNFCheckboxes();
}
function CheckClick(elm) {
    if (safari) return true;
    if (elm.className.indexOf("_d") != -1) return; // Cannot click disabled checkboxes
    var inp = gebtn(elm,'input')[0];
    if (elm.className == 'label_check c_off_m' || (!safari && inp.checked)) {
        elm.className = 'label_check c_on_m';
    } else {
        elm.className = 'label_check c_off_m';
    };
    return true;
};

function CheckClickInput(inp) {
    if (!safari) return true;
    
    var lbl = inp.parentNode;
    if (!lbl) return true;
    
    if (lbl.className.indexOf("_d") != -1) return true; // Cannot click disabled checkboxes
    
    if (lbl.className == 'label_check c_off_m') {
        lbl.className = 'label_check c_on_m';
        inp.checked = true;
    } else {
        lbl.className = 'label_check c_off_m';
        inp.checked = false;
    };
    return true;
}
function CheckMouseover(elm) {
    if (elm.className.indexOf("_d") != -1) return; // Don't provide mouseover effects to disabled checkboxes
    if (elm.className == 'label_check c_off') {
        elm.className = 'label_check c_off_m';
    } else {
        elm.className = 'label_check c_on_m';
    }
    
}
function CheckMouseout(elm) {
    if (elm.className.indexOf("_d") != -1) return; // Don't provide mouseover effects to disabled checkboxes
    if (elm.className == 'label_check c_off_m') {
        elm.className = 'label_check c_off';
    } else {
        elm.className = 'label_check c_on';
    }
}
function TabMouseover(tab) {
    if (/InactiveTabMouseover/.test(tab.className)) return;
    
    if (/InactiveTab/.test(tab.className)) {
        tab.className = tab.className.replace(/InactiveTab/, "InactiveTabMouseover");
    }
}
function TabMouseout(tab) {
    if (/InactiveTabMouseover/.test(tab.className)) {
        tab.className = tab.className.replace(/InactiveTabMouseover/, "InactiveTab");
    }
}
function TabClick(tab) {
    // Stop processing if this tab is already the active tab
    if (ActiveTab == tab) return;
    
    // Set current active tab to inactive
    ActiveTab.className = "InactiveTab";
    
    // Set new tab active
    tab.className = "ActiveTab";
    ActiveTab = tab;
    
    // Replace content
    var lbl = document.getElementById("LeadInSpan");
    var loc_box = document.getElementById("l_s");
    var name_box = document.getElementById("n_s");
    var chain_box = document.getElementById("ch_s");
    var chain_lead_in = document.getElementById("ChainLeadInSpan");
    
    loc_box.style.display = "none";
    name_box.style.display = "none";
    chain_box.style.display = "none";
    chain_lead_in.style.display = "none";
    
    switch (ActiveTab.id) {
        case "SnoogleLocationTabDiv":
            lbl.innerHTML = "Enter a location:";
            loc_box.style.display = "block";
            break;
        case "SnoogleNameTabDiv":
            lbl.innerHTML = "Enter a facility name:";
            name_box.style.display = "block";
            break;
        case "SnoogleChainTabDiv":
            lbl.innerHTML = "Enter a facility chain name:";
            chain_box.style.display = "block";
            loc_box.style.display = "block";
            chain_lead_in.style.display = "block";
            break;
        default:
            lbl.innerHTML = "";
            
            break;
    }
    
    var search = document.getElementById("SnoogleSearch");
    var checkboxes = document.getElementById("SnoogleCheckboxes");
    var helptext = document.getElementById("SnoogleHelpContent");
    search.style.display = "none";
    checkboxes.style.display = "none";
    helptext.style.display = "none";
    if (ActiveTab.id == "SnoogleHelpTabDiv") {
        helptext.style.display = "block";
    } else {
        search.style.display = "block";
        checkboxes.style.display = "block";
    }
}
    
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 IsChainSearch = /Chain/.test(ActiveTab.id);
    
    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 ((inputElement.value == "") || (inputElement.value == MAP_INPUT_ID_TO_DEFAULT_TEXT[id])) {
                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 RestoreState() {

    //get the SnapForSeniorsSearch cookie if it has been set
    var stateCookie = GetCookie(cookieName);
    
    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;
                    }
                }
            }
        }
    }
    
    
    InitializeTextInputFontStyles();
    
    if (typeof(QuickSearchRestoreState) != "undefined")
        QuickSearchRestoreState();
}

// ---------------------------------------------------------------------------
// 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;
    }
}


// ----------------------------------------------------------------------------
// 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) {
    //SetSearchResultsTabId(193);
    ForceFriendlyUrls(true);
    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 facilityName = document.getElementById(NameID).value;

    // Location
    var location = document.getElementById(LocationID).value;
    
    // Chain name 
    var chainName = document.getElementById(ChainID).value;
    
    // If the relevant input box isn't empty or the stub text, use its contents
    if ((chainName != "") && (chainName != CHAIN_DEFAULT_TEXT)) {
        params["ch"] = chainName;
    }
    if ((facilityName != "") && (facilityName != NAME_DEFAULT_TEXT)) {
        params["n"] = facilityName;
    } 
    if ((location.length) > 0 && (location != LOCATION_DEFAULT_TEXT)) {
        params["l"] = location;
    }
    
    // Only submit what's actually visible
    var nameIsVis = false;
    var chIsVis = false;
    if (ActiveTab.id.indexOf("Name") != -1) nameIsVis = true;
    if (ActiveTab.id.indexOf("Chain") != -1) chIsVis = true;
   
    if (nameIsVis && !chIsVis) {
        if (params["ch"] != null) delete params["ch"];
        if ((params["n"] != null) && (params["l"] != null))
            delete params["l"];
    }
    if (!nameIsVis && chIsVis) {
        if (params["n"] != null) delete params["n"];
    }
    
    if (!nameIsVis && !chIsVis) { // location tab
        if (params["ch"] != null) delete params["ch"];
        if (params["n"] != null) delete params["n"];
    }
    
    // Make sure they fill in a chain name on the chain tab
    /*if (chIsVis && (params["ch"] == null)) {
        alert("Must enter a chain name");
        return;
    }*/
    
    // 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);
            }
        }
    }

    ShowLoadingScreen();
    
    if (showHelp) {
        window.location = SearchHelpUrl(params);
        return;
    } else {
        window.location = SearchResultsUrl(params);
        return;
    }
}


