function beta_optin(percent, existing_redirect_url, new_redirect_url) {
    var managed = AGCookie.getCookieValue('customer','managed');
    var gotbeta = MagicCookie.getCookieValue('gotbeta');
    if(window.location.search.indexOf('nobeta') > -1) { gotbeta = '0' }
    if(gotbeta == '0') {
        return false;
    } else if(gotbeta == '1' && existing_redirect_url) {
        window.location.href = existing_redirect_url;
        return true;
    }
    var num = Math.round(Math.random()*100);
    if(num < percent && !managed) {
        MagicCookie.setCookieValue('gotbeta', '1', true);
        if(new_redirect_url) {
            window.location.href = new_redirect_url;
            return true;
        }
    } else {
        MagicCookie.setCookieValue('gotbeta', '0', false);
    }
    return false;
}

function beta_optout(redirect_url, popup_url) {
    MagicCookie.setCookieValue('gotbeta', '0', true);
    if(popup_url) {
        var wopts = 'toolbar=no,scrollbars=yes,width=426,height=400,resizable=yes';
        window.open(popup_url, 'betafeedback', wopts);
    }
    if(redirect_url) {
        window.location.href = redirect_url;
    }
}

function beta_forget() {
    MagicCookie.delCookieValue('gotbeta', true);
    MagicCookie.delCookieValue('gotbeta', false);
}

function agi_to_pw(partial_url)
{
    // instantiate object vars
    this.partial_url = partial_url;
    this.email = null;
    this.ahost = null;
    this.site = null;

    /* init vars, perform the redirect */
    this.go = function ()
    {
        this.clean_url();
        this.init_environ();
        this.set_email();
        this.do_redirect();
    };

    /* init environ-related vars */
    this.init_environ = function ()
    {
        if(window.ahost)
        {
            this.ahost = window.ahost;
        }
        else
        {
            this.ahost = window.location.protocol + '//' + window.location.host;
        }

        this.environ = (this.ahost.indexOf('www') != -1) ? 'www' : 'beta';
        this.site = (this.ahost.indexOf('msn') != -1) ? 'AG_MSN' : 'AG';
    };

    /* grab email address from cookie, if present */
    this.set_email = function ()
    {
        if(window.AGCookie)
        {
            this.email = window.AGCookie.getCookieValue('customer', 'email');
            if(!this.email){
                this.email = '';
            }
        }
        else
        {
            this.email = '';
        }
    };

    /* just as a safeguard, clean up the url that was passed in */
    this.clean_url = function ()
    {
        var pu = this.partial_url;
        pu = pu.replace('^http://www.', '');
        pu = pu.replace(/cb=[^&]*&*/, '');
        pu = pu.replace(/email=[^&]*&*/, '');
        this.partial_url = pu;
    };

    /* redirect to photoworks */
    this.do_redirect = function ()
    {
        var base_url = 'http://' + this.environ + '.' + this.partial_url;
        var extra_qs = '&cb=PW_' + this.site + '&email=' + this.email;
        var full_url = base_url + extra_qs;
        window.location.assign(full_url);
    };

    this.go();
}

var _complete = new Object();
//if (!onupfunctions)
//    var onupfunctions = new Array();

function console_log(message)
{
    try{
        console.log(message);
    } catch (e) {}
}

function arrayIndexOf(array, object)
{
    for (var i = 0; i < array.length; i++) {
        if (array[i] == object)
            return i;
    }
    return -1;
}

check_complete = function(e)
{
    e = (e) ? e : ((window.event) ? window.event : null);
    if (e !== null)
    {
        for (id in _complete)
        {
            _complete[id].check_click_source(e, id);
        }
    }
};

// BACKPORTED from dojo1.1 <ag.widget.autocomplete>
// Remove an autocomplete widget from the _complete "registry".  Added to
// support replacing recipient email textarea with single-recipient text
// input for gift cards.  -- mpirnat, 10/06/2008
autocomplete_unregister = function(id) {
    if(_complete[id]) {
        delete _complete[id];
    }
};

if (document.addEventListener)
    document.addEventListener("mouseup", check_complete, false);
else
    document.attachEvent("onmouseup", check_complete);

function AutoComplete(element, suggest_url)
{
    var auto = this;
    _complete[element.id] = this;

    this.request = new Requester(suggest_url, "POST", true, false);
    this.debug = document.getElementById("debug");
    this.element = element;
    this.suggestions = new Array();
    this.inputText = null;
    this.search_text = null;

    // position variables
    this.top = 0;
    this.left = 0;
    this.cursor = -1;

    this.open = false;
    this.max_suggestions = 15;
    this.selectedIdx = -1;
    this.suggest_url = suggest_url;

    // default styles
    this.class_name = "agi-auto-complete";
    this.class_selected = "agi-auto-complete-selected";

    // must type more than this many characters to get a suggestion
    this.min_len = 0;

    // look for the auto-complete-div or create it if missing
    this.popup = document.getElementById(element.id + "-auto-complete-div");
    if (!this.popup)
        this.popup = createDiv(this.element.id);

    // look for the auto-complete-iframe or create it if missing
    this.iframe = document.getElementById(element.id + "-auto-complete-iframe");
    if (!this.iframe)
        this.iframe = createIFrame(this.element.id);

    // Keycode constants
    var TAB = 9;
    var ENTER = 13;
    var ESC = 27;
    var KEYUP = 38;
    var KEYDN = 40;
    var KEYLFT = 37;
    var KEYRGT = 39;
    var KEYSHFT = 16;

    // turn off the browser's autocomplete on the element
    this.element.setAttribute("autocomplete", "off");

    this.is_open = function()
    {
        return _complete[element.id].open;
    };

    this.check_click_source = function(e, id)
    {
        if (!_complete[element.id].is_open())
        {
            // cancel pending queries
            if (_complete[element.id].request.in_process)
                _complete[element.id].request.onsuccess = null;
            return;
        } else {
            var my_ids = new Array(id, id + "-auto-complete-div", id + "-auto-complete-ifram");
            var clicked = get_event_source(e);

            //if (my_ids.indexOf(clicked.id) == -1)
            if (arrayIndexOf(my_ids, clicked.id) == -1) {
                if ((clicked.id.indexOf(id + "-href-") !== 0)
                    && (clicked.id.indexOf(id + "-li-") !== 0)
                    && (clicked.id.indexOf(id + "-div-") !== 0))
                {
                    // cancel pending queries
                    if (_complete[element.id].request.in_process)
                        _complete[element.id].request.onsuccess = null;
                    _complete[element.id].hidePopup();
                }
            }
        }

    };

    this.makeVisible = function()
    {
        var popup_bottom = this.popup.clientHeight + this.top - getScrollOffset().pageYOffset;
        var new_top = this.top - this.element.offsetHeight - this.popup.clientHeight;
        var window_height = getSize().height;

        // position the popup above the element if it will fit there but not below
        if (popup_bottom > window_height && new_top > 0)
        {
            this.popup.style.top = new_top + "px";
            this.iframe.style.top = new_top + "px";
        }
    };

    this.positionPopup = function()
    {
        var elem = this.element;
        this.left = 0;
        this.top = elem.offsetHeight;

        //Walk up the DOM and add up all of the offset positions.
        while (elem.offsetParent && elem.tagName.toUpperCase() != 'BODY')
        {
            //if (elem.id != "lightbox")
            //{
                this.left += elem.offsetLeft;
                this.top += elem.offsetTop;
            //}
            elem = elem.offsetParent;
        }

        this.left += elem.offsetLeft;
        this.top += elem.offsetTop;

        this.popup.style.left = this.left + 'px';
        this.popup.style.top = this.top + 'px';
    };

    this.showPopup = function()
    {
        this.selectedIdx = -1;

        this.iframe.style.display = "block";
        this.popup.style.display = "block";
        this.popup.scrollTop = 0;

        var width = this.popup.clientWidth + "px";
        var ul = document.getElementById(element.id + "-ul");
        var lis = ul.getElementsByTagName('DIV');
        for (i = 0; i < lis.length; i++)
        {
            lis[i].style.width = width;
        }

        if (lis.length > 15)
        {
            lineHeight = lis[0].scrollHeight;
            divHeight = lineHeight * 15;
            this.popup.style.height = divHeight + "px";
            this.iframe.style.height = divHeight + "px";
            this.popup.style.overflow = "auto";
            this.popup.style.overflowX = "hidden";
        } else {
            this.popup.style.height = "";
            this.iframe.style.height = "";
            this.popup.style.overflow = "";
        }

        this.popup.style.zIndex = "500";
        this.iframe.style.zIndex = "499";
        this.iframe.style.background = "#FFFFFF";
        this.iframe.style.width = this.popup.clientWidth + "px";
        this.iframe.style.height = this.popup.clientHeight + "px";
        this.iframe.style.left = this.popup.style.left;
        this.iframe.style.top = this.popup.style.top;
        this.open = true;
        this.makeVisible();
    };

    this.hidePopup = function()
    {
        this.selectedIdx = -1;
        this.iframe.style.display = "none";
        this.popup.style.display = "none";
        this.open = false;
    };


    this.bind_element = function(element)
    {
        this.element = element;

        // if the popup is visible, don't allow arrow keys to move the cursor
        element.onkeypress = function(e)
        {
            var thisKey = auto.getKeyCode(e);
            switch(thisKey)
            {
                case TAB:
                case KEYUP:
                case KEYDN:
                case KEYLFT:
                case KEYRGT:
                case ENTER:
                case ESC:
                    return (auto.popup.style.display == "none");
                default:
                    return true;
            }
        };

        element.onkeyup = function(e)
        {
            var thisKey = auto.getKeyCode(e);

            switch(thisKey)
            {
                case TAB:
                case ESC:
                case KEYUP:
                case KEYDN:
                case KEYLFT:
                case KEYRGT:
                    return (auto.popup.style.display == "none");
                case KEYSHFT:
                    return true;
                default:
                    var cur_text = auto.getSearchValue(auto.element);
                    if (cur_text != auto.inputText)
                    {
                        auto.inputText = cur_text;
                        if  (cur_text.length > auto.min_len)
                            auto.searchSuggestions();
                        else
                            auto.hidePopup();
                    }// else {
                    //  auto.hidePopup();
                    //}
                    return true;
            }
        };

        element.onkeydown = function(e)
        {
            var thisKey = auto.getKeyCode(e);

            switch(thisKey)
            {
                case ENTER:
                    auto.useSuggestion();
                break;

                case TAB:
                    if (auto.selectedIdx > -1)
                    {
                        auto.useSuggestion();
                    } else {
                        auto.hidePopup();
                        if (auto.request.in_process)
                            auto.request.onsuccess = null;
                        focus_next_element(auto.element);
                    }
                break;

                case ESC:
                    var status = (auto.popup.style.display == "none");
                    auto.hidePopup();
                    return status;
                break;

                case KEYUP:
                    if (auto.selectedIdx > 0)
                        auto.selectedIdx--;
                    //else
                    //  auto.selectedIdx = auto.suggestions.length - 1;
                    auto.changeSelected(thisKey);
                    return (auto.popup.style.display == "none");
                break;

                case KEYDN:
                    if (auto.selectedIdx < (auto.suggestions.length - 1))
                        auto.selectedIdx++;
                    //else
                    //  auto.selectedIdx = 0;
                    auto.changeSelected(thisKey);
                    return (auto.popup.style.display == "none");
                break;
            }
        };

    };

    this.bind_element(this.element);

    this.getKeyCode = function(e)
    {
        if(e)           //Firefox
            return e.keyCode;
        if(window.event)    //IE
            return window.event.keyCode;
    };

    this.createSuggestions = function(search_text)
    {
        var ul = document.createElement('ul');
        ul.setAttribute("id", element.id + "-ul");
        ul.style.listStyleType = "none";
        ul.style.margin = "0px";
        ul.style.padding = "0px";
        ul.style.cursor = "pointer";

        //Create an array of LI's for the words.
        //for (i = 0; i < this.suggestions.length && i < this.max_suggestions; i++)
        for (i = 0; i < this.suggestions.length; i++)
        {
            var linkText = this.getDisplaySuggestion(this.suggestions[i]);
            if (search_text)
            {
                fidx = linkText.toLowerCase().indexOf(search_text);
                linkText = linkText.substring(0,fidx) +
                            "<b>" + linkText.substring(fidx, fidx + search_text.length) +
                            "</b>" + linkText.substring(fidx + search_text.length);
            }
            linkText = linkText.replace(/ /g, "&nbsp;");

            var li = document.createElement('li');
            li.setAttribute("id", element.id + "-li-" + i);
            var d = document.createElement('div');
            d.setAttribute("id", element.id + "-div-" + i);
            d.setAttribute("style", "cursor: pointer;");

            var a = document.createElement('a');
            a.href="javascript:void(null)";
            a.innerHTML = linkText;
            a.setAttribute("class", this.class_name);
            a.setAttribute("className", this.class_name);
            a.setAttribute("id", element.id + "-href-" + i);
            d.appendChild(a);
            li.appendChild(d);
            //li.appendChild(a);

            if (auto.selectedIdx == i)
            {
                li.setAttribute("class", this.class_selected);
                li.setAttribute("className", this.class_selected);
                a.className = this.class_selected;
            } else {
                li.setAttribute("class", this.class_name);
                li.setAttribute("className", this.class_name);
            }

            ul.appendChild(li);
        }

        this.popup.replaceChild(ul,this.popup.childNodes[0]);


        /********************************************************
        mouseover handler for the dropdown ul
        move the highlighted suggestion with the mouse
        ********************************************************/
        ul.onmouseover = function(ev)
        {
            //Walk up from target until you find the LI.
            var target = auto.getEventSource(ev);
            while (target.parentNode && target.tagName.toUpperCase() != 'LI')
            {
                target = target.parentNode;
            }

            var lis = auto.popup.getElementsByTagName('LI');


            for (i = 0; i < lis.length; i++)
            {
                var li = lis[i];
                if(li == target)
                {
                    auto.selectedIdx = i;
                    break;
                }
            }
            auto.changeSelected();
        };

        /********************************************************
        click handler for the dropdown ul
        insert the clicked suggestion into the input
        ********************************************************/
        ul.onclick = function(ev)
        {
            auto.useSuggestion();
            auto.hidePopup();
            auto.cancelEvent(ev);
            return false;
        };

        this.popup.className = this.class_name;
        this.popup.style.position = 'absolute';
    };

    this.useSuggestion = function()
    {
        if (this.selectedIdx > -1)
        {
            var suggested_email = this.suggestions[this.selectedIdx];
            this.applySuggestion(suggested_email);
            this.hidePopup();
            this.selectedIdx = -1;
            this.inputText = "";
            this.search_text = "";


            //intentionally lose focus on the element to discard the enter event;
            this.element.blur();

            //It's impossible to cancel the Tab key's default behavior.
            //So this undoes it by moving the focus back to our field right after
            //the event completes.
            setTimeout("focus_element('" + this.element.id + "')",10);

            // IE needs to be told where to position the cursor again...
            if (this.cursor != -1)
                setTimeout("set_cursor_position('" + this.element.id + "'," + this.cursor + "," + this.cursor + ")", 15);
            this.setSuggestionUsage(suggested_email,'k');
        }
    };

    this.setSuggestionUsage = function(address,type)
    {
        // Store autocomplete indicator in hidden webvar.
        try {
            var autokomp = document.getElementsByName("autokomp")[0];
        } catch(e) {
            autokomp = false;
        }

        var usage_value = autokomp.value;
        var entry = trim(address) + "|" + type;
        entry = encodeURIComponent(entry);

        if (usage_value.length > 0)
            usage_value += "," + entry;
        else
            usage_value = entry;
        autokomp.value = usage_value;
    };

    this.changeSelected = function(keyPressed)
    {
        if (!keyPressed)
            keyPressed = '';
        var lis = this.popup.getElementsByTagName('LI');

        var height = lis[0].scrollHeight;
        if (!isIE)
            height = height + 1;
        var divScroll = this.popup.scrollTop + (this.popup.clientHeight * 1);

        for (i = 0; i < lis.length; i++)
        {
            var li = lis[i];
            if (this.selectedIdx == i)
            {
                li.className = this.class_selected;
                li.getElementsByTagName("A")[0].className = this.class_selected;
                if (lis.length > 15 && (keyPressed == KEYDN || keyPressed == KEYUP))
                {
                    var scroll = height * i;
                    if (scroll > divScroll)
                        this.popup.scrollTop = this.popup.scrollTop + height;
                    else if (scroll < this.popup.scrollTop)
                        this.popup.scrollTop = scroll;
                }
            }
            else
            {
                li.className = this.class_name;
                li.getElementsByTagName("A")[0].className = this.class_name;
            }
        }
    };

    this.getEventSource = function(ev)
    {
        if(ev)          //Moz
            return ev.target;

        if(window.event)    //IE
            return window.event.srcElement;
    };

    this.cancelEvent = function(ev)
    {
        if(ev)          //Moz
        {
            ev.preventDefault();
            ev.stopPropagation();
        }

        if(window.event)    //IE
            window.event.returnValue = false;
    };

    this.searchSuggestions = function()
    {
        auto.request.onsuccess = auto.onsuccess;
        if (!auto.request.in_process)
        {
            auto.search_text = auto.getSearchValue(auto.element);
            auto.request.sendRequest("q=" + encodeURIComponent(auto.getSearchValue(auto.element)));
        }
    };

    this.onsuccess = function(req)
    {
        var cur_text = auto.getSearchValue(auto.element);
        if (cur_text != auto.search_text && cur_text.length > auto.min_len )
        {
            auto.searchSuggestions();
            return;
        }
        try {
            eval("auto.suggestions = " + req.responseText);
        } catch (e) {
            auto.hidePopup();
            return;
        }
        auto.suggestions.sort(compare_contacts);
        auto.createSuggestions(auto.search_text);
        auto.positionPopup();
        if (auto.suggestions.length > 0)
            auto.showPopup();
        else
            auto.hidePopup();
    };

    // override the getDisplaySuggestion, applySuggestion, and getSearchValue
    // functions if suggestions are not simple arrays of strings.
    this.getDisplaySuggestion = function(suggestion)
    {
        return suggestion;
    };

    this.applySuggestion = function(suggestion)
    {
        this.element.value = suggestion;
    };

    this.getSearchValue = function(el)
    {
        return this.element.value;
    };
}

// functions used to create the popup div and the iframe
// used to hide controls in IE.
function createIFrame(parent_id)
{
    var iframe = document.createElement("IFRAME");
    iframe.setAttribute("src", "javascript:void(null)");
    iframe.setAttribute("scrolling", "no");
    iframe.setAttribute("frameBorder", "0");
    iframe.setAttribute("id", parent_id + "-auto-complete-iframe");
    iframe.style.width = "0px";
    iframe.style.height = "0px";
    iframe.style.position = "absolute";
    iframe.style.display = "none";
//  objParent.appendChild(iframe);
    document.body.appendChild(iframe);
    return iframe;
}

function createDiv(parent_id)
{
    var div = document.createElement("DIV");
    div.setAttribute("id", parent_id + "-auto-complete-div");
    div.style.display = "none";
//  div.style.overflow = "auto";

    var list = document.createElement("UL");

    div.appendChild(list);
//  objParent.appendChild(div);
    document.body.appendChild(div);
    return div;
}

// bma custom page contact autocomplete
function CustomEventComplete(elId, to_name, to_email)
{
    // methods to work on storage
    var wcomplete = this;
    var complete;
    var toname    = to_name;
    var toemail   = to_email;

    // set up AutoComplete object
    if (_complete[elId])
    {
        complete = _complete[elId];
        complete.bind_element(document.getElementById(elId));
    } else {
        complete = new AutoComplete(document.getElementById(elId), ahost + '/reminders/contactsearch.pd');
    }

    //Actually finds matches
    var oldcomplete = complete.searchSuggestions;
    complete.searchSuggestions = function()
    {
        if (!preloaded)
        {
            oldcomplete();
            return;
        }

        complete.suggestions = new Array();

        // text to be searched for
        var search = (complete.getSearchValue(complete.element) + "").toLowerCase();

        //pl_contacts is wombat storage object, match text to storage
        for (i in pl_contacts)
        {
            var first_name = (pl_contacts[i].first_name + "").toLowerCase();
            var last_name = (pl_contacts[i].last_name + "").toLowerCase();
            var email = (pl_contacts[i].email + "").toLowerCase();
            if (email.indexOf(search) === 0 ||
                    first_name.indexOf(search) === 0 ||
                    last_name.indexOf(search) === 0)
                complete.suggestions.push(pl_contacts[i]);
        }

        // handles results of search
        complete.suggestions.sort(compare_contacts);
        complete.createSuggestions(search);
        complete.positionPopup();

        // popup display
        if (complete.suggestions.length > 0)
            complete.showPopup();
        else
            complete.hidePopup();
    };

    complete.getDisplaySuggestion = function(suggestion)
    {
            return wcomplete.assembleContact(suggestion).replace("<","&#60;").replace(">", "&#62;");
    };

    this.assembleContact = function(suggestion)
    {
        var fname = (suggestion.first_name === null) ? "" : suggestion.first_name;
        var lname = (suggestion.last_name === null) ? "" : suggestion.last_name;
        var space = (lname.length > 0 && fname.length > 0) ? " " : "";
        var name = (lname.length > 0 || fname.length > 0) ? '"' + fname + space + lname +'"' : "";
        var email = (suggestion.email === null || suggestion.email.length === 0) ? "" : " <" + suggestion.email + ">";
        return name + email;
    };

    complete.applySuggestion = function(suggestion)
    {
        var re = /\&\#(\d*)\;/g ;
        // fill in name and email fields
        if (toname) {
            if (suggestion.first_name !== null && suggestion.last_name !== "")
                toname.value = suggestion.first_name.replace(re, get_unicode);
        }
        if (toemail) {
            if (suggestion.email !== null && suggestion.email !== "")
                toemail.value = suggestion.email;
        }
    };
}


// reminders add/edit page contact autocomplete
function WombatEventComplete(elId, contact_arg)
{
    var wcomplete = this;
    var contact = contact_arg;
    if (_complete[elId])
    {
        var complete = _complete[elId];
        complete.bind_element(document.getElementById(elId));
    } else {
        var complete = new AutoComplete(document.getElementById(elId), ahost + '/reminders/contactsearch.pd');
    }

    var oldcomplete = complete.searchSuggestions;
    complete.searchSuggestions = function()
    {
        if (!preloaded)
        {
            oldcomplete();
            return;
        }

        complete.suggestions = new Array();
//      for (i = 0; i < pl_contacts.length; i++)
        var search = (complete.getSearchValue(complete.element) + "").toLowerCase();
        for (i in pl_contacts)
        {
            var first_name = (pl_contacts[i].first_name + "").toLowerCase();
            var last_name = (pl_contacts[i].last_name + "").toLowerCase();
            var email = (pl_contacts[i].email + "").toLowerCase();
            if (email.indexOf(search) === 0 ||
                    first_name.indexOf(search) === 0 ||
                    last_name.indexOf(search) === 0)
                complete.suggestions.push(pl_contacts[i]);
        }
        complete.suggestions.sort(compare_contacts);
        complete.createSuggestions(search);
        complete.positionPopup();
        if (complete.suggestions.length > 0)
            complete.showPopup();
        else
            complete.hidePopup();
    };

    complete.getDisplaySuggestion = function(suggestion)
    {
            return wcomplete.assembleContact(suggestion).replace("<","&#60;").replace(">", "&#62;");
    };

    this.assembleContact = function(suggestion)
    {
        var fname = (suggestion.first_name === null) ? "" : suggestion.first_name;
        var lname = (suggestion.last_name === null) ? "" : suggestion.last_name;
        var space = (lname.length > 0 && fname.length > 0) ? " " : "";
        var name = (lname.length > 0 || fname.length > 0) ? '"' + fname + space + lname +'"' : "";
        var email = (suggestion.email === null || suggestion.email.length === 0) ? "" : " <" + suggestion.email + ">";
        return name + email;
    };

    complete.applySuggestion = function(suggestion)
    {
        var re = /\&\#(\d*)\;/g ;
        // fill in name and email fields
        if (contact.lname) {
            if (suggestion.last_name !== null && suggestion.last_name !== "")
                contact.lname.value = suggestion.last_name.replace(re, get_unicode);
        }
        if (contact.fname) {
            if (suggestion.first_name !== null && suggestion.last_name !== "")
                contact.fname.value = suggestion.first_name.replace(re, get_unicode);
        }
        if (contact.email) {
            if (suggestion.email !== null && suggestion.email !== "")
                contact.email.value = suggestion.email;
        }
        // check the correct gender
        if (contact.male && suggestion.gender !== null && suggestion.gender.toLowerCase() == "m")
            contact.male.checked = true;
        else if (contact.female)
            contact.female.checked = true;

        // select the correct relationship and type if set for the contact
        if (contact.relationship_type && suggestion.relate_type !== null)
        {
            contact.relationship_type.value = suggestion.relate_type;
            var options = relate_options[suggestion.relate_type];

            for (var j = contact.relationship.options.length - 1; j > -1; j--)
                contact.relationship.remove(j);

            contact.relationship.appendChild(get_option("", "Relationship"));

            for (var i=0; i < options.length; i++)
            {
                var this_option = get_option(options[i].id, options[i].description);
                if (contact.relationship && suggestion.relationship !== null && options[i].id == suggestion.relationship)
                    this_option.setAttribute("selected", true);

                contact.relationship.appendChild(this_option);
            }
        }

        // try to set the display values if this is the event detail page
        try {
            if (suggestion.first_name !== null && suggestion.first_name !== "")
                contact.fname_display.innerHTML = contact.fname.value + "&nbsp;";
            if (suggestion.last_name !== null && suggestion.last_name !== "")
                contact.lname_display.innerHTML = contact.lname.value + "&nbsp;";
            if (suggestion.email !== null && suggestion.email !== "")
                contact.email_display.innerHTML = contact.email.value + "&nbsp;";
            contact.gender_display.innerHTML = (contact.male.checked) ? "Male" : "Female";
            contact.relationship_display.innerHTML = contact.relationship.options[contact.relationship.selectedIndex].text  + "&nbsp;";
        } catch(e) {
        }
    };
}

// reminders textarea email autocomplete
function TextAreaComplete(elId)
{
    var complete;
    var textcomplete = this;
    if (_complete[elId])
    {
        complete = _complete[elId];
        complete.bind_element(document.getElementById(elId));
    } else {
        complete = new AutoComplete(document.getElementById(elId), ahost + '/reminders/contactsearch.pd');
    }

    // Expose this as property of "class" so that its functions can be decorated later
    this.baseCompleter = complete;

    var oldcomplete = complete.searchSuggestions;
    complete.searchSuggestions = function()
    {
        if (!preloaded)
        {
            oldcomplete();
            return;
        }

        complete.suggestions = new Array();
        var search = (complete.getSearchValue(complete.element) + "").toLowerCase();
        for (g in pl_groups)
        {
            var label = (pl_groups[g].label + "").toLowerCase();

            //if (label == search)
            //{
            //  complete.suggestions = new Array();
            //  complete.applySuggestion(pl_groups[g]);
            //  break;
            //}

            if (label.indexOf(search) === 0)
                complete.suggestions.push(pl_groups[g]);
        }
        for (i in pl_contacts)
        {
            var first_name = (pl_contacts[i].first_name + "").toLowerCase();
            var last_name = (pl_contacts[i].last_name + "").toLowerCase();
            var email = (pl_contacts[i].email + "").toLowerCase();
            var f = (first_name.length > 0) ? first_name + " " : "";
            var l = (last_name.length > 0) ? last_name + " " : "";
            var full = f + l;

            if (email.toLowerCase() == search)
            {
                complete.suggestions = new Array();
                break;
            }

            if (((email.indexOf(search) === 0 ||
                    first_name.indexOf(search) === 0 ||
                    last_name.indexOf(search) === 0) ||
                    full.indexOf(search) === 0) &&
                    (email.length > 0))
                complete.suggestions.push(pl_contacts[i]);
        }
        complete.suggestions.sort(compare_contacts);
        complete.createSuggestions(search);
        complete.positionPopup();
        if (complete.suggestions.length > 0)
            complete.showPopup();
        else
            complete.hidePopup();
    };

    complete.getDisplaySuggestion = function(suggestion)
    {
        return textcomplete.assembleContact(suggestion).replace("<","&#60;").replace(">", "&#62;");
    };

    complete.applySuggestion = function(suggestion)
    {
        var suggestion_text = "";
        var elStr = this.element.value;
        var position = get_cursor_position(this.element);
        var start = position - complete.getSearchValue(complete.element).length;
        var before_text = elStr.substring(0, start);
        var after_text = elStr.substring(position);

        var white_before = (before_text.search(/\s+$/g) != -1 || before_text.length === 0);
        var white_after = (after_text.search(/^\s+/g) != -1);

        var prefix = (white_before) ? "" : " ";
        var postfix = (white_after) ? "," : ", ";

        if (!suggestion.label)
            suggestion_text = suggestion.email;
        else
            suggestion_text = get_group_emails(suggestion);

        var newValue = prefix + suggestion_text + postfix;
        this.element.value =  before_text + newValue + after_text;
        this.cursor = start + newValue.length;
        //textcomplete.setPosition(this.element, this.cursor, this.cursor);
    };

    complete.getSearchValue = function(el)
    {
        var elStr = el.value;
        var position = get_cursor_position(el);
        var idx = elStr.lastIndexOf(",", position);
        var start = (idx == -1) ? 0 : idx + 1;
        idx = elStr.indexOf(",", position);
        var end = (idx == -1) ? elStr.length - 1 : idx - 1;
        return elStr.substring(start, position).replace(/^\s*|\s*$/g,"");
    };

    this.assembleContact = function(suggestion)
    {
        if (!suggestion.label)
        {
            var fname = (suggestion.first_name === null) ? "" : suggestion.first_name;
            var lname = (suggestion.last_name === null) ? "" : suggestion.last_name;
            var space = (lname.length > 0 && fname.length > 0) ? " " : "";
            var name = (lname.length > 0 || fname.length > 0) ? '"' + fname + space + lname +'"' : "";
            var email = (suggestion.email === null || suggestion.email.length === 0) ? "" : " <" + suggestion.email + ">";
            return name + email;
        } else {
            return suggestion.label + " (group)";
        }
    };

}

function get_cursor_position(area)
{
    // IE loses focus on the text area when clicking a suggestion -- force it back.
    try {
        area.focus();
    } catch(e){}

    if( document.selection )
    {
        // The current selection
        var range = document.selection.createRange();
        // We'll use this as a 'dummy'
        var stored_range = range.duplicate();
        // Select all text
        stored_range.moveToElementText( area );
        // Now move 'dummy' end point to end point of original range
        stored_range.setEndPoint( 'EndToEnd', range );
        // Now we can calculate start and end points
        area.selectionStart = stored_range.text.length - range.text.length;
        area.selectionEnd = area.selectionStart + range.text.length;
    }

    return area.selectionEnd;
}

function set_cursor_position(area_id, start, end) {
    var area = document.getElementById(area_id);
    if (navigator.appName.indexOf("Microsoft") == -1) {
        area.setSelectionRange(start, end);
    } else {
        // assumed IE
        var range = area.createTextRange();
        range.collapse(true);
        range.moveStart("character", start);
        range.moveEnd("character", end - start);
        range.select();
    }
}

function focus_next_element(element)
{
    var idx = -1;
    for (var i = 0; i < element.form.elements.length; i++)
    {
        if (element.form.elements[i] == element && i < (element.form.elements.length - 1))
            idx = i;
    }

    if (idx != -1)
        element.form.elements[idx].focus();
}

function focus_element(elem_id)
{
    try {
        document.getElementById(elem_id).focus();
    } catch (e) {}
}

function get_unicode(str, digits, offset, s)
{
    // create a unicode string from the digits in an xmlcharref
    digits = parseInt(digits);
    return String.fromCharCode(digits);
}

function get_event_source(ev)
{
    if(ev) {        //Moz
        if (ev.target)
            return ev.target;
        else if (ev.srcElement) //IE
            return ev.srcElement;
    }

    if(window.event)    //IE
        return window.event.srcElement;
}

var Base64 = new Object();


Base64.CARRAY = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
        "abcdefghijklmnopqrstuvwxyz0123456789+/=";


Base64.encode = function(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + Base64.CARRAY.charAt(enc1)
            + Base64.CARRAY.charAt(enc2)
            + Base64.CARRAY.charAt(enc3)
            + Base64.CARRAY.charAt(enc4);
   } while (i < input.length);

   return output;
}


Base64.decode = function(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = Base64.CARRAY.indexOf(input.charAt(i++));
      enc2 = Base64.CARRAY.indexOf(input.charAt(i++));
      enc3 = Base64.CARRAY.indexOf(input.charAt(i++));
      enc4 = Base64.CARRAY.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}


var NVP = new Object();


/* name value pair get the value */
NVP.getValue = function(data, name, sep, term) {
    var spos, epos;

    spos = data.indexOf(term+name+sep);
    if (-1 == spos) {
        spos = data.indexOf(name+sep);
        if (-1 == spos) return null;
        spos += name.length + sep.length;
    } else {
        spos += term.length + name.length + sep.length;
    }

    epos = data.indexOf(term, spos);
    if (-1 == epos) epos = data.length;

    return data.substring(spos, epos);
}


NVP.toMap = function(s, pairsep, sep) {
    var map = new Array();
    var pairs = s.toString().split(pairsep);
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i];
        if (pair) {
            var data = pair.split(sep);
            map[unescape(data[0])] = unescape(data[1]);
        }
    }
    return map;
}


NVP.fromMap = function(map, pairsep, sep) {
    var s = '';
    for (var name in map) {
        if (map[name] == null) { continue; }
        if (typeof(map[name]) == 'function') { continue; }
        s += escape(name) + sep + escape(map[name]) + pairsep;
    }
    if (s) { s = s.substr(0, s.length-1); }
    return s;
}


var AGCookie = new Object();


AGCookie.SUBHOSTS = [[/\.yahoo\./, '_yh'],
        [/\.msn\./, '_msn'],
        [/\.aol\.|^aol\./, '_aol'],
        [/\.target\./, '_tg']];


AGCookie.getCookieDomain = function() {
    var names = window.location.hostname.split('.');
    var idx = names.length - 2;
    var tld = names.slice(-1);
    if (tld != 'com' && tld != 'net' && tld != 'org') {
        idx = names.length -3;
    }
    names = names.slice(idx);
    return '.' + names.join('.');
}


AGCookie.getCookieName = function(name) {
    var hn = window.location.hostname.split('.')[0];
    for (var i = 0; i < AGCookie.SUBHOSTS.length; i++) {
        var pair = AGCookie.SUBHOSTS[i];
        if (pair[0].test(window.location.hostname)) { name += pair[1]; }
    }
    // vanilla should get dev cookies
    hn = hn.replace("vanilla", "dev")

    var envs = ['dev', 'work', 'stage'];

    for (var j = 0; j < envs.length; j++)
    	if (hn.indexOf(envs[j]) == 0)
    		name += "_" + envs[j];

    return escape(name);
}


AGCookie.getCookieValueRaw = function(name, pairname) {
    var c = AGCookie.getCookie(name);
    if (c == null) { return null; }
    var v = NVP.getValue(Base64.decode(c), pairname, "=", "&");

    if(v) { /* do this because IE is dumb! */ return unescape(v); }
    return v;
}


/* Get the entire value of the cookie and unescape it. */
AGCookie.getCookie = function(name) {
    var c = NVP.getValue(document.cookie,
            AGCookie.getCookieName(name), '=', ';');
    if(!c)
        return c;
    c = unescape(c);
    while (c.indexOf('%0A') > -1 || c.indexOf('%0a') > -1) {
        c = c.replace(/\%0[aA]/,'');
    }
    c = unescape(c);
    return c;
}


/* Set the value of a cookie. */
AGCookie.setCookie = function(name, value, expires, perm) {
    name = AGCookie.getCookieName(name);
    var cki = name + '=' + escape(value) + ';';
    if (perm) { expires = 'Thursday, 31-Dec-2037 00:01:00 GMT'; }
    if (expires) { cki = cki + 'expires=' + expires + ';'; }
    cki = cki + 'path=/;domain=' + AGCookie.getCookieDomain();
    document.cookie = cki;
}


AGCookie.expireCookie = function(name) {
    AGCookie.setCookie(name, '', 'Friday, 01-Jan-99 00:00:00 GMT');
}


AGCookie.getCookieValue = function(name, pairname) {
    var v = AGCookie.getCookieValueRaw(name, pairname);
    if(!v && name == 'customer' && pairname == 'name') {
        v = AGCookie.getCookieValueRaw(name, 'email');
    }
    if(!v && name == 'customer' && pairname == 'name') {
        v = "member";
    }
    return v;
}


AGCookie.setCookieValue =
        function(name, pairname, value, expires, perm) {
    var map = null;
    var c = AGCookie.getCookie(name);
    if (c) { map = NVP.toMap(Base64.decode(c), '&', '='); }
    else { map = new Array(); }
    map[pairname] = value;
    AGCookie.setCookie(name, Base64.encode(NVP.fromMap(map, '&', '=')),
            expires, perm);
}


var MagicCookie = new Object();


MagicCookie.setCookieValue = function(pairname, value, perm) {
    var name = perm ? 'mc_p' : 'mc_s';
    return AGCookie.setCookieValue(name, pairname, value, null, perm);
}


MagicCookie.getCookieValue = function(pairname) {
    var value = AGCookie.getCookieValue('mc_s', pairname);
    if (!value) {
        value = AGCookie.getCookieValue('mc_p', pairname);
    }
    return value;
}


MagicCookie.delCookieValue = function(pairname, perm) {
    return MagicCookie.setCookieValue(pairname, null, perm);
}


/***** LEGACY -- this stuff is deprecated and should not be used. *****/

var CARRAY = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

function b64_decode(str)
{
    var data = "";

    if ((str.length % 4) != 0)
        return "ERROR";

    for (var i = 0; i < str.length; i+=4) {
        var i24 = 0;
        i24 |= (CARRAY.indexOf(str.charAt(i)) & 0xFF) << 18;
        i24 |= (CARRAY.indexOf(str.charAt(i+1)) & 0xFF) << 12;
        i24 |= (CARRAY.indexOf(str.charAt(i+2)) & 0xFF) << 6;
        i24 |= (CARRAY.indexOf(str.charAt(i+3)) & 0xFF) << 0;

        data += String.fromCharCode((i24 & 0xFF0000) >> 16);
        if (str.charAt(i+2) != '=')
            data += String.fromCharCode((i24 & 0xFF00) >> 8);
        if (str.charAt(i+3) != '=')
            data += String.fromCharCode((i24 & 0xFF) >> 0);
    }
    return data;
}


get_cookie_domain = AGCookie.getCookieDomain;
get_cookie_name = AGCookie.getCookieName;

nvp_getval = NVP.getValue;


function get_cookie(name)
{
    var c = nvp_getval(document.cookie, name, '=', ';');
    c = unescape(c);
    while(c.indexOf('%0A') > -1 || c.indexOf('%0a') > -1) {
        c = c.replace(/\%0[aA]/,'');
    }
    c = unescape(c);
    return c;
}

function get_cookie_value_raw(name, pairname)
{
    var c = get_cookie(name);
    var v = nvp_getval(b64_decode(c), pairname, "=", "&");
    if(v) { /* do this because IE is dumb! */
        return unescape(v);
    }
    else {
        return '';
    }
}

function get_cookie_value(name, pairname)
{
    var v = get_cookie_value_raw(name, pairname);
    if(!v && name == 'customer' && pairname == 'name') {
        v = get_cookie_value_raw(name, 'email');
    }
    if(!v && name == 'customer' && pairname == 'name') {
        v = "member";
    }
    return v;
}

function set_cookie(name, value, expires, perm) {
    if(perm) {
        expires = 'Thursday, 31-Dec-2037 00:01:00 GMT';
    }
    var cki = name+'='+value+';';
    if(expires) {
        cki = cki+'expires='+expires+';';
    }
    cki=cki+'path=/;domain='+get_cookie_domain();
    document.cookie = cki;
}

expire_cookie = AGCookie.expireCookie;

function make_text(text)
{
	var re = /\&\#(\d*)\;/g
	text = text.replace(re, get_unicode);
    var new_node = document.createTextNode(text);
    return new_node;
}

function get_unicode(str, digits, offset, s)
{
	// create a unicode string from the digits in an xmlcharref
	digits = parseInt(digits);
	return String.fromCharCode(digits);
}

function make_node(which,attrs,children)
{
    var new_node = document.createElement(which);
    if(attrs!=undefined)
    {
        for(var attr in attrs)
        {
            //doing `.className` is cross-browser compatible
            if(attr.toLowerCase()=='class'||attr.toLowerCase()=='classname')
                new_node.className = attrs[attr];
            else
                new_node.setAttribute(attr, attrs[attr]);
        }
    }
    if(children!=undefined)
    {
        //make sure in array
        if(!children.push || !children.join)
            children = [children];
        for(var x=0; x<children.length; x++)
        {
            try
            {
                new_node.appendChild(children[x]);
            }
            catch(e){}
        }
    }
    return new_node;
}

function swap_node(elem, new_elem) {
    elem.parentNode.replaceChild(new_elem, elem);
    return new_elem;
}

var blnClicked = false;

function resetClicked() {
  blnClicked = false;
}

function debounce(x, blnAlert, intSeconds) {
  var intTime = 3000;
  if(intSeconds != null) {
    intTime = intSeconds * 1000;
  }
  if (window.setDoPopAway != null)
  {
    setDoPopAway(false);
  }
  if (blnClicked == true) {
    if(blnAlert == true) {
      alert('Please wait while we process your request.');
    }
    return false;
  }
  else {
    blnClicked = true;
    setTimeout('resetClicked()', intTime); // disable the form for some time
    return true;
  }
}

function FeedbackTrigger(url, attr) {
    var loc = '/feedback/lb.pd';
    var attrs = {'width':440,'hideloading':true};
    if(url) loc = url;
    if(attr) attrs = attr;

    var ftrigger = this;
    this.show = function() {
        lightbox(loc, attrs);
        omniture.swap_vars_and_ping({'s_pageName':loc});
    }
    this.hide = function() {
        if (scrollInterval)
            clearInterval(scrollInterval)
        hideLightbox();
    }
}

function FeedbackForm(formid, submitbtnid, cancelbtnid) {
    var fform = this;
    this.debug = false;
    this.form = document.getElementById(formid);
    if(!submitbtnid) submitbtnid = 'save';
    if(!cancelbtnid) cancelbtnid = 'cancel';
    this.btn_submit = document.getElementById(submitbtnid);
    this.btn_cancel = document.getElementById(cancelbtnid);
    this.errors = new Errors('lightbox_message_area');
    this.request = new Requester('', 'POST', true, true);
    this.submitting = false;
    this.isIE = navigator.appName.indexOf('Microsoft') != -1;
    this.user_status = document.getElementById('user_status');
    this.comments = document.getElementById('comments');
    this.page_name = document.getElementById('page_name');
    this.likely_recommend = document.getElementById('likely_recommend');
    this.rate_design = this.form.rate_design;
    this.rate_ease = this.form.rate_ease;

    // add event triggers to buttons
    try {
//        this.btn_submit = document.getElementById('save');
        this.btn_submit.onclick = function() { fform.submit(); }
    } catch(e) {}
    try {
//        this.btn_cancel = document.getElementById('cancel');
        this.btn_cancel.onclick = function() { fform.hide(); }
    } catch(e) {}

    this.hide = function() {
        if (scrollInterval)
            clearInterval(scrollInterval)
        hideLightbox();
    }

    this.submit = function() {
        if(!this.form) return false;
        this.disable(true);
        this.page_name.value = s_pageName;
        var strQuery = new Requester().formToQuery(this.form);
        if(this.submitting) return;
        this.submitting = true;
        this.request.url = '/feedback/submitfeedback.pd';
        this.request.onsuccess = this.onsuccess;
        this.request.onerror = this.onerror;
        this.request.sendRequest(strQuery);
    }

    this.onerror = function(req) {
        fform.submitting = false;
        fform.disable(false);
        fform.errors.add(new Error('', "There was an error submitting your feedback.<br/>Please try again in a few minutes."));
        if(fform.debug)
            fform.errors.add(new Error('', req.responseText));
        fform.errors.display(true);
    }

    this.onsuccess = function(req) {
        eval('var results = '+req.responseText);
        fform.submitting = false;
        if(results.status == 0) {
            fform.hide();
        } else {
            fform.disable(false);
            fform.errors.add(new Error('', results.message));
            if(fform.debug)
                fform.errors.add(new Error('', results.error));
            fform.errors.display(true);
        }
    }

    this.disable = function(disabled) {
        if(!this.form) return false;
        for(var i=0; i<this.form.elements.length; i++) {
            if(this.form.elements[i].type != 'hidden') {
                this.form.elements[i].disabled = disabled;
                if(this.form.elements[i].type != 'button')
                    this.form.elements[i].style.background = '#FFFFFF';
            }
        }
    }
}

function FinditLightbox(hidden_node_id, form_id) {
    var findittrigger = this;
    this.hidden_node_id = hidden_node_id;
    this.form_id = form_id;
    this.ff = undefined;

    this.show = function() {
        var markup = dojo.byId(findittrigger.hidden_node_id).innerHTML;
        markup = markup.replace('findit_magic',form_id);
        lightbox('', undefined, markup);
        findit_ff = new FocusForm(findittrigger.form_id);
        findittrigger.ff = new FocusForm(findittrigger.form_id);
        return false;
    }

    this.hide = function() {
        if(findittrigger.ff) {
            findittrigger.ff.reset_form();
        }
        hideLightbox();
        return false;
    }
}

function OriginalFormValues() {
}

function FocusForm(form_id, off_cls, on_cls) {
  var fform = this;
  this.orig_form_values = new OriginalFormValues();
  this.on_cls = on_cls || 'activeinput';
  this.off_cls = off_cls || 'lazyinput';
  this.form = document.getElementById(form_id);

  this.wake_input = function(elem) {
    if(elem.className.indexOf(fform.off_cls) > -1) {
      eval('fform.orig_form_values.'+elem.name+'=elem.value;');
      elem.value = '';
      if(elem.name.indexOf('password') > -1) {
        var new_elem = make_node('input',
            {'class':elem.className,'name':elem.name,'type':'password','id':elem.id});
        elem = swap_node(elem, new_elem);

        // password enter detector has to be reconnected for ie
        connect_password_keypress(elem, form_id);
        elem.focus(); // x2 to make ie6 happy
        elem.focus();
        new_elem.focus();
      }
      elem.className = elem.className.replace(/lazyinput/, fform.on_cls);
    }
  }

  this.reset_input = function(elem) {
    if(elem.className.indexOf(fform.on_cls) > -1) {
      elem.className = elem.className.replace(/activeinput/,fform.off_cls);
      if(elem.name.indexOf('password') > -1) {
        var new_elem = make_node('input',
            {'class':elem.className,'name':elem.name,'type':'text','id':elem.id});
        elem = swap_node(elem, new_elem);
        elem.focus();
      }
      try {
        eval('var orig_value=fform.orig_form_values.'+elem.name+';');
        elem.value = orig_value;
      } catch(e) {
        elem.value = "Couldn't find original value";
      }

    }
  }

  this.reset_form = function() {
    for(var i=0; i<fform.form.elements.length; i++) {
      fform.reset_input(fform.form.elements[i]);
    }
    fform.setup_onfocus();
  }

  this.setup_onfocus = function() {
    for(var i=0; i<fform.form.elements.length; i++) {
      function wake_closure(elem) {
        var el = elem;
        function inner_wake() {
          fform.wake_input(el);
        }
        return inner_wake;
      }
      elem = fform.form.elements[i];
      if(elem.type == 'textarea' || elem.type == 'text' || elem.type == 'select-one') {
        elem.onfocus = wake_closure(elem);
      }
    }
  }
  this.setup_onfocus();
  this.form.onreset = fform.reset_form;
}

function toggle_display(id) {
  elem = document.getElementById(id);
  if(elem.style.display == 'none') {
    elem.style.display = 'block';
  } else {
    elem.style.display = 'none';
  }
}

function toggle_vis(id) {
  elem = document.getElementById(id);
  if(elem.style.visibility == 'hidden') {
    elem.style.visibility = 'visible';
  } else {
    elem.style.visibility = 'hidden';
  }
}

function connect_password_keypress(node, form_id) {
	dojo.event.connect(node, 'onkeypress',
		function(e) {
			if (e.keyCode == 13) {
				e.preventDefault();
				submit_on_keypress(form_id);
			}
		}
	);
}

function submit_on_keypress(form_id) {
	dojo.byId(form_id).submit();
}

// Success/Error codes - caller can process the codes however it sees fit
var PASS = true;
var FAIL = false;
// keys for message array
var EMAIL_FAIL = "EMAIL_FAIL";
var IS_EMPTY = "IS_EMPTY";
var TOO_LONG = "TOO_LONG";
var ONE_EMAIL = "ONE_EMAIL";

// default error messages
var defaultErrorMessages = new Array();
defaultErrorMessages[ EMAIL_FAIL ] = " is not a valid email address.";
defaultErrorMessages[ TOO_LONG ] = " is too long to fit in our database; please choose an alternative email address.";
defaultErrorMessages[ IS_EMPTY ] = "Please specify at least one recipient's email for your card.";
defaultErrorMessages[ ONE_EMAIL ] = "Please enter one email address at a time.";

function isEmpty(val){
    if(trim(val) == "")
        return true;
    return false;
}

function ltrim(val){
    //  ltrim removes leading whitespace characters from a string
    //        @param    val  string to be modified
    //        @return   val  modified string
    return val.replace(/^\s*/g,"");
}

function rtrim(val){
    //  rtrim removes trailing whitespace characters from a string
    //        @param    val  string to be modified
    //        @return   val  modified string
    return val.replace(/\s*$/g,"");
}

function trim(val){
    //  trim removes leading and trailing whitespace characters
    //  from a string
    //        @param    val  string to be modified
    //        @return   val  modified string
    return val.replace(/^\s*|\s*$/g,"");
}

function write_message(message_id, message, class_name)
{
    var message_div = document.getElementById(message_id);
    var curr_class = message_div.className;

    if(message)
    {
        if(class_name)
        {
            message_div.setAttribute('class', class_name);
            message_div.setAttribute('className', class_name);
        }
        message_div.style.display = 'block';
        message_div.innerHTML = message;
        scroll_into_view(message_id);
    }
    else
    {
        message_div.style.display = 'none';
    }
}

function reformat_emails(emails, email_object){
    var reformatted_emails = '';
    for(var i=0; i<emails.length; i++)
    {
        if(!isEmpty(emails[i]))
        {
            reformatted_emails += trim(emails[i]);
            if(i < emails.length-1)
                reformatted_emails += ', ';
        }
    }
    if(email_object)
        email_object.value = reformatted_emails;
    return reformatted_emails;
}

function validate_email(email, maxlen, allow_empty) {
    // validate_email validates a single email address
    //      @param      email   email address to be validated
    //      @param      maxlen  maximum length allowed for email address
    //      @exception  IS_EMPTY|TOO_LONG|FAIL
    //                      raise error code via "throw()"
    //      @return     PASS    return PASS if no tests fail
    var strEmail = trim(email);
    var strUser;
    var strDomain;
    var arrDomainParts = Array();
    var intDomainLength;

    if(!maxlen)
        maxlen = 75;

    if(!allow_empty)
        allow_empty

    // empty email address
    if(strEmail == "" && !allow_empty)
        throw(IS_EMPTY);
    else if(strEmail == "")
        return;

    // email address too long
    if(strEmail.length > maxlen)
        throw(TOO_LONG);

    // check for: '@' at beginning, multiple '@', '@' at end, no '@'
    if (strEmail.match(/.*@$|.*@.*@.|^@.*|^[^@]*$/))
        throw(EMAIL_FAIL);

    strUser = strEmail.split("@")[ 0 ];
    strDomain = strEmail.split("@")[ 1 ];

    // missing part of email
    if (strUser == "" || strDomain == "")
        throw(EMAIL_FAIL);

    // user shouldn't contain '()<>:;,[ ]\" ' (delivermail.py)
    if(strUser.match(/.*[*()<>;:,\[\]\\'" ].*/))
        throw(EMAIL_FAIL);

    // domain should only contain alphanumerics or a hyphen. Single letter subdomains are allowed. (delivermail.py)
    if (!(strDomain.match(/^([0-9a-zA-Z\-\.]+\.)+[a-zA-Z]{2,9}$/)))
        throw(EMAIL_FAIL);

    // domain should be text.text[ .text ]*
    if (strDomain.indexOf("..") != -1) // part of domain missing
        throw(EMAIL_FAIL);

    arrDomainParts = strDomain.split(".");
    intDomainLength = arrDomainParts.length;
    if (intDomainLength == 1)
        throw(EMAIL_FAIL);
    // top level is wrong length (2-char country code, or 3-6 char whatchallit)
    if (arrDomainParts[ intDomainLength-1 ].length < 2 || arrDomainParts[ intDomainLength-1 ].length > 6)
        throw(EMAIL_FAIL);

    // passed all the tests
    return PASS;
}

function validate_emails(email_object, reformat, message_array){

    var valid           = true;
    var emails          = email_object.value.replace(/;/g,',');
    var result_object   =   {
                            'error_message' : '',
                            'error_codes' : new Array(),
                            'pass_validation' : FAIL,
                            'emails': ''
                            }
    if(!reformat)
        reformat = true;
    if(!message_array)
        message_array = defaultErrorMessages;

    if(reformat)
    {
        emails = emails.replace(/\n/g,', ');
        emails = emails.replace(/\r/g,', ');
    }

    if(isEmpty(emails) || isEmpty(emails.replace(/,/g,'')))
    {
        valid = FAIL;
        result_object.error_message += '<p>'+message_array[IS_EMPTY]+'</p>';
    }

    emails = emails.split(',');
    for (i=0; i<emails.length; i++)
    {
        try
        {
            validate_email(emails[i],'',true);
        }
        catch(e_code)
        {
            result_object.error_message += '<p>'+emails[i]+' '+message_array[e_code]+'</p>';
            valid = FAIL;
            result_object.error_codes[result_object.error_codes.length] = e_code+'|'+emails[i];
        }
    }

    if(reformat)
        reformat_emails(emails, email_object);

    result_object.emails = emails;
    result_object.pass_validation = valid;
    return result_object;
}

function validate_checkboxes(checkbox_name){
    var checkboxes = document.getElementsByName(checkbox_name);
    var is_checked = false;
    for(var i=0; i < checkboxes.length; i++)
    {
        if(checkboxes[i].checked)
        {
            is_checked = true;
            break;
        }
    }
    if(!is_checked)
        return FAIL;
    return PASS;
}

function Error(field, message, type)
{
	var e_obj = this;
	this.message = message;
	this.field = field;
	this.type = type
}

function Errors(display_div)
{
	var e_obj = this;
	this.errors = new Array();
	this.display_div = document.getElementById(display_div);
	this.error_html = "<p>%s</p>";
	this.error_color = "#FF0000";

	this.ERROR = "agi-message-area agi-error";
	this.MESSAGE = "agi-message-area agi-message-demo";
	this.SUCCESS = "agi-message-area agi-message-success";

	this.count = function()
	{
		return this.errors.length;
	}

	this.is_error = function()
	{
		return (this.errors.length > 0);
	}

	this.display = function(blnShow)
	{
		if (blnShow)
		{
			write_message(this.display_div.id, this.to_html(), "agi-message-area agi-error");
//			this.display_div.innerHTML = this.to_html();
//			this.display_div.style.color = this.error_color;
			this.mark_fields();
		} else {
			write_message(this.display_div.id, null, "agi-message-area agi-error");
//			this.display_div.innerHTML = "";
			this.clear_fields();
		}
	}

	this.set_class = function(class_name)
	{
		var curr_class = this.display_div.className;
		if(class_name && (curr_class.indexOf(class_name) == -1))
		{
			message_class = (this.display_div.className) ? this.display_div.className+' '+class_name : class_name
			this.display_div.setAttribute('class', message_class);
			this.display_div.setAttribute('className', message_class);
		}
	}

	this.write_message = function(message, class_name)
	{

    if(message)
    {
        this.display_div.style.display = 'block';
        this.display_div.innerHTML = message;
    }
    else
    {
        this.display_div.style.display = 'none';
    }
	}

	this.mark_fields = function()
	{
		for (i = 0; i < this.errors.length; i++)
		{
			try{
				document.getElementById(this.errors[i].field + "-error").className = "agi-mesage-area agi-error";

			} catch(e) {
			}
		}
	}

	this.clear_fields = function()
	{
		for (i = 0; i < this.errors.length; i++)
		{
			try{
				document.getElementById(this.errors[i].field + "-error").className = "";
			} catch(e) {
			}
		}
	}

	this.to_html = function()
	{
		var html = "";
		for (i = 0; i < this.errors.length; i++)
		{
			html += this.error_html.replace("%s", this.errors[i].message);
		}
		return html;
	}

	this.show = function()
	{
		this.display(true);
	}

	this.hide = function()
	{
		this.display(false);
	}

	this.reset = function()
	{
		this.hide();
		this.errors = new Array();
	}

	this.add = function(error)
	{
		this.errors.push(error);
	}

	this.add_error = function(field, message, type)
	{
		if (!type)
			type = this.ERROR;
		this.add(new Error(field, message, type));
	}
}


try{
    var path = String(window.location.pathname);
    var x = 0;
    if (path.indexOf('/cnp') != -1)
        x = 1;
    if (path.indexOf('/inv') != -1)
        x = 2;
    document.getElementById('ag-searcharea').selectedIndex = x;
} catch(e){}

// methods to be used for creating a 'placeholder' text for the search box
var srchElem;
var searcherrmsg = "Enter Search Here";

function searchBlur(){if (srchElem.value==="") { srchElem.value=searcherrmsg;}}
function searchFocus(){srchElem.value="";}

function submitSearch(lbl){
  try{
      if ((lbl===undefined)||(lbl==="")) {
        srchElem = document.getElementById("ag-searchtext");
      } else {
        srchElem = document.getElementById(lbl);
      }
      var searchpage = document.getElementById('ag-searcharea').value;
      var searchval  = srchElem.value;
      var lpage='';
      var newloc=searchpage+'?strSearch='+escape(searchval);

      // make sure something is submitted
      if (( searchval.length <= 0 )||(searchval==searcherrmsg)) {
        // nothing entered
        srchElem.style.border = "2px solid #ff0000";
        srchElem.style.background = "#FFDDDD";

        // set the value of the field to hold a place holder text using onblur/onfocus
        srchElem.onblur = searchBlur;
        srchElem.onfocus = searchFocus;
        srchElem.value=searcherrmsg;
        srchElem.blur();
      } else {
          if(document.getElementById('lpage')){
            lpage=document.getElementById('lpage').value;
            newloc=newloc+'&lpage='+lpage;
          }
          window.document.location.href=newloc;
      }
      return false;
  } catch(e){return false;}
}

function submitMSNSearch(brand){
    if (brand == 'ag'){
       try{
           submitSearch("q");
       } catch(e){return false;}
    }
    else if (brand == 'msn'){
        try{
            document.forms[ 'msn-search' ].action = 'http://search.msn.com/results.aspx';
            document.forms[ 'msn-search' ].submit();
        }
        catch(e){
            return false;
        }
    }
}


// leftnav_util.js
//   utilities specific to the AG Rebirth Left Nav menu
//   add them as you see fit

function _has_perm(perm_num,str_perm) {
    // Permission number '1' is
    var arr_perms = str_perm.split('|');
    dojo.debug('#perms: ' + arr_perms.length);
    for (var i=0;i<arr_perms.length;i++) {
        var arr_perm = arr_perms[i].split('^');
        dojo.debug('perm: ' + arr_perm[0] + ' val: ' + arr_perm[1]);
        if ((perm_num == arr_perm[0]) && (arr_perm[1] == 'C')) {
            return true;
        }
    }
    return false;
}

function hide_signup(perm_num) {
    var undef; //undefined -- used for comparison
    var div_signup = dojo.byId('agi-signup-cont');
    if ((div_signup !== null) && (div_signup !== undef)){
        var perms = MagicCookie.getCookieValue('vanperms');
        dojo.debug('vanperms: ' + perms);
        if ((perms !== null) && (perms !== undef) && (perms !== '')) {
            if (_has_perm(1,perms) === true) {
                //div_signup = dojo.byId('agi-signup-cont');
                dojo.html.hide(div_signup);
            }
        }
    }
}

var ag_newsletter_perm = 1; // Defined here but call in commonjs executable
                            // code snippet



__date__    = "$Date: 7/09/07 10:23a $"
__version__ = "$Revision: 13 $"
__author__  = "$Author: Csitko $"


/*
  Lightbox w/o Prototype
  Based upon Lokesh Dhakar's Lightbox JS (See http://huddletogether.com/projects/lightbox/)

  This script is released by 23 (http://www.23hq.com) under  the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
  (Steffen Tiedemann Christensen, steffen@23hq.com, http://blog.23hq.com)

  Usage:
  lightbox('/myurl/demo.html');
  lightbox('/myurl/demo.html', {height:300, width:500});
  lightbox('/myurl/demo.html', {params:'test=yes', left:10, top:10, height:300, width:500, callingObj:this, position:'relative'});
*/

var isIE = navigator.appName.indexOf("Microsoft") != -1;

// Config
//var loadingImgSrc = 'loading.gif'

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){
    var yScroll;

    if (self.pageYOffset) {
  yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop){  // Explorer 6 Strict
  yScroll = document.documentElement.scrollTop;
    } else if (document.body) {// all other Explorers
  yScroll = document.body.scrollTop;
    }

    arrayPageScroll = new Array('',yScroll)
  return arrayPageScroll;
}



//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {
  xScroll = document.body.scrollWidth;
  yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
  xScroll = document.body.scrollWidth;
  yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
  xScroll = document.body.offsetWidth;
  yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;
    if (self.innerHeight) { // all except Explorer
  windowWidth = self.innerWidth;
  windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
  windowWidth = document.documentElement.clientWidth;
  windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
  windowWidth = document.body.clientWidth;
  windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if (yScroll < windowHeight){
  pageHeight = windowHeight;
    } else {
  pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if (xScroll < windowWidth) {
  pageWidth = windowWidth;
    } else {
  pageWidth = xScroll;
    }


    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) ;
    return arrayPageSize;
}


//
// getAbsoluteObjectX(obj)
//
function getAbsoluteObjectX(obj) {
    var x = obj.offsetLeft;
    while (obj.offsetParent) {
        obj = obj.offsetParent;
  x += obj.offsetLeft;
    }
    return(x);
}

//
// getAbsoluteObjectY(obj)
//
function getAbsoluteObjectY(obj) {
    var y = obj.offsetTop;
    while (obj.offsetParent) {
        obj = obj.offsetParent;
  y += obj.offsetTop;
    }
    return(y);
}


//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//

function getKey(e){
    if (e == null) { // ie
  keycode = event.keyCode;
    } else { // mozilla
  keycode = e.which;
    }
    key = String.fromCharCode(keycode).toLowerCase();
    /* perhaps for future use */
    //if (key == 'x') hideLightbox();
}


//
// listenKey()
//
function listenKey () { document.onkeypress = getKey; }

function showLightbox(clearoverlay) {
    ////log(lbX + ", " + lbY + ", " + lbW + ", " + lbH);

    // prep objects
    var objOverlay = document.getElementById('agi-overlay' + (clearoverlay ? '-clear' : ''));
    var objLightbox = document.getElementById('lightbox');
    var objLoadingImage = document.getElementById('loadingImage');

    objLightbox.style.overflow = lbOverflow;
    objLoadingImage.style.display = 'none';
    objLoadingImage.style.visibility = 'hidden';

    var arrayPageSize = getPageSize();
    var arrayPageScroll = getPageScroll();

    if (lbH!=undefined) objLightbox.style.height = lbH + "px";
    if (lbW!=undefined) objLightbox.style.width = lbW + "px";
    ////log("H: " + objLightbox.style.height + ", W: " + objLightbox.style.width);

    if (lbY==undefined) {lbY=20;}
    objLightbox.style.top = lbY + "px";

    objLightbox.style.visibility = 'hidden';
    objLightbox.style.display = 'block';

    if (lbX==undefined) {lbX = ((arrayPageSize[0] - objLightbox.offsetWidth) / 2);}
    ////log(arrayPageSize[0] + ", " + objLightbox.offsetWidth + ", " + lbX);

    objLightbox.style.left = lbX + "px";

    objLightbox.style.visibility = 'visible';

    ////log(lbX + ", " + lbY + ", " + lbW + ", " + lbH);


    // After load, update the overlay height as the new content might have
    // increased the overall page height.
    arrayPageSize = getPageSize();
    objOverlay.style.height = (arrayPageSize[1] + 'px');

    try {
      document.getElementById("agi-page").className = "agi-noprint";
    } catch (e){}
    //log(7);

    // Check for 'x' keypress
    listenKey();
}


//
// lightbox()
//
var lbX, lbY, lbW, lbH, lbOverflow;
function lightbox(target, P, html_string, clearoverlay) {
    clearoverlay = clearoverlay == undefined ? false : clearoverlay;
    if (target==undefined) return;
    if (P==undefined) {var P = new Object();}
    if (html_string == undefined) { html_string = "";}

    var params = P.params; var h = P.height; var w = P.width; var x = P.left; var y = P.top; var callingObj = P.callingObj; var position = P.position; var overflow = P.overflow;


    if (params==undefined) {params = '';}
    if (overflow==undefined) {overflow = 'auto';}
    if (position==undefined) {position = 'absolute';}

    var arrayPageSize = getPageSize();
    var arrayPageScroll = getPageScroll();

    if (position=="relative") {
  // Relative to obj
        if (!callingObj) {alert('Lightbox needs a callingObj when positioning relatively');}

        if (x==undefined) x=0;
        if (y==undefined) y=0;
        x += getAbsoluteObjectX(callingObj);
        y += getAbsoluteObjectY(callingObj);
    } else if (position=="user") {
  // User-defined offset
        if ((y===undefined)||(x===undefined)) {
            alert("Lightbox needs 'left' and 'top' defined when user-defined is positioning option.");
            return null;
        }
    }else {
  // Absolute
        if (y==undefined) y=20;
        y += arrayPageScroll[1];
    }

    lbX = x;
    lbY = y;
    lbW = w;
    lbH = h;
    lbOverflow = overflow;

    initLightbox(clearoverlay);

    // prep objects
    var objOverlay = document.getElementById('agi-overlay' + (clearoverlay ? '-clear' : ''));
//    if(P.allowclick == 'no')
//        objOverlay.onclick = function () {return false;}
//    else
//        objOverlay.onclick = function () {hideLightbox(); return false;}
	try
	{
    	filter = getStyle('agi-overlay', 'filter');

    	if (filter && isIE)
    	{
    		if (filter.indexOf(imghost) == -1)
    		{
    			filter = filter.replace('/agbeta', imghost + '/agbeta');
    			objOverlay.style.filter = filter;
    		}
    	}

    } catch (e) {}

    var objLightbox = document.getElementById('lightbox');
    var objLoadingImage = document.getElementById('loadingImage');

    var arrayPageSize = getPageSize();
    var arrayPageScroll = getPageScroll();

    objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
    objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');

    // show loading image ?
    var hide_loading = false;
    try
    {
        var main_print_html = document.getElementById('agi-cal-or-list').innerHTML;
        if(main_print_html.indexOf('loader.swf')>=0)
            hide_loading = true;
    }
    catch(e){}
    if(P.hideloading || hide_loading){
        objLoadingImage.style.display = 'none';
        objLoadingImage.style.visibility = 'hidden';
    }
    else{
        objLoadingImage.style.display = 'block';
        objLoadingImage.style.visibility = 'visible';
    }

    // set height of Overlay to take up whole page and show
    objOverlay.style.height = (arrayPageSize[1] + 'px');
    objOverlay.style.display = 'block';
  // hide select boxes in IE
  if (isIE)
  {
    var selects = document.getElementsByTagName("SELECT");
    for (var i=0; i < selects.length; i++)
    {
      selects[i].style.visibility = "hidden";
    }
  }

  if (html_string == "")
    {
      var requester = new Requester(target, 'GET', true, true);
      requester.onsuccess = P.allowclick ? onSuccess_clickable : onSuccess;
      requester.onerror = onError;
      requester.sendRequest(params);
    }
    else
    {
      objLightbox.innerHTML = stripScripts(html_string);
      showLightbox(clearoverlay);
      evalScripts(html_string);
      if (P.allowclick)
        objOverlay.onclick = function () {hideLightbox(); return false;}
    }
}

function onSuccess(request)
{
  var lightbox = document.getElementById('lightbox');
  lightbox.innerHTML = stripScripts(request.responseText);
  showLightbox();

  evalScripts(request.responseText);
}

function onSuccess_clickable(request)
{
  onSuccess(request);
  var objOverlay = document.getElementById('agi-overlay');
  if (objOverlay)
    objOverlay.onclick = function () {hideLightbox(); return false;}

  var objOverlay = document.getElementById('agi-overlay-clear');
  if (objOverlay)
      objOverlay.onclick = function () {hideLightbox(); return false;}
}

function onError(request)
{
  hideLightbox();
}

//
// hideLightbox()
//
function hideLightbox()
{
    // get objects
    var objOverlay = document.getElementById('agi-overlay');
    var objOverlayClr = document.getElementById('agi-overlay-clear');
    var objLightbox = document.getElementById('lightbox');
    var objLoadingImage = document.getElementById('loadingImage');

    if (objOverlay)
        objOverlay.onclick = function () {return false;}

  // display select boxes in IE
  if (isIE)
  {
    var selects = document.getElementsByTagName("SELECT");
    for (var i=0; i < selects.length; i++)
      selects[i].style.visibility = "visible";
  }

    // hide lightbox and overlay
    if (objOverlay)
        objOverlay.style.display = 'none';
    if (objOverlayClr)
        objOverlayClr.style.display = 'none';
    objLightbox.style.display = 'none';
    objLoadingImage.style.display = 'none';
    objLoadingImage.style.visibility = 'hidden';
    objLightbox.innerHTML = "";

    try {
      document.getElementById("agi-page").className = "";
    } catch (e){}

    // disable keypress listener
    document.onkeypress = '';
}




//
// initLightbox()
//
function initLightbox(clearoverlay)
{
  var objBody = document.getElementsByTagName("body").item(0);
  var arrayPageSize = getPageSize();
  var arrayPageScroll = getPageScroll();

  var sOverlayID = 'agi-overlay' + (clearoverlay ? '-clear' : '')

  if (!document.getElementById(sOverlayID))
  {
    // create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
    var objOverlay = document.createElement("div");
    objOverlay.setAttribute('id', sOverlayID);
    objOverlay.setAttribute('class', 'agi-noprint');
    objOverlay.setAttribute('className', 'agi-noprint');
    //objOverlay.onclick = function () {hideLightbox(); return false;}
    objOverlay.style.display = 'none';
    objOverlay.style.position = 'absolute';
    objOverlay.style.top = '0';
    objOverlay.style.left = '0';
    objOverlay.style.zIndex = '190';
    objOverlay.style.width = '100%';
    objBody.insertBefore(objOverlay, objBody.firstChild);
  }

  if (!document.getElementById('lightbox'))
  {
    // create lightbox div, same note about styles as above
    var objLightbox = document.createElement("div");
    objLightbox.setAttribute('id','lightbox');
    objLightbox.style.display = 'none';
    objLightbox.style.position = 'absolute';
    objLightbox.style.zIndex = '200';
    objBody.insertBefore(objLightbox, objOverlay.nextSibling);
  }

  if (!document.getElementById('loadingImage'))
  {
    /*var objLoadingImage = document.createElement("img");
    objLoadingImage.src = loadingImgSrc;
    objLoadingImage.setAttribute('id','loadingImage');
    objLoadingImage.style.position = 'absolute';
    objLoadingImage.style.zIndex = '150';
    objBody.insertBefore(objLoadingImage, objBody.firstChild);*/

    var objLoadingImage = document.createElement("embed");
    objLoadingImage.setAttribute('id','loadingImage');
    objLoadingImage.setAttribute('name','FlashProduct');
    try {
    	if (!imghost_site)
			imghost_site = 'ag';
    }
    catch(ex) {imghost_site = 'ag';}
    objLoadingImage.setAttribute('src',imghost+'/'+imghost_site+'/reminders/loader.swf');
    objLoadingImage.setAttribute('swLiveConnect',true);
    objLoadingImage.setAttribute('width',120);
    objLoadingImage.setAttribute('height',120);
    objLoadingImage.setAttribute('scale','noborder');
    objLoadingImage.setAttribute('quality','high');
    objLoadingImage.setAttribute('type','application/x-shockwave-flash');
    objLoadingImage.setAttribute('pluginspace','http://www.macromedia.com/go/getflashplayer');
    objLoadingImage.setAttribute('wmode','transparent');
    objLoadingImage.style.position = 'absolute';
    objLoadingImage.style.zIndex = '250';
    objBody.insertBefore(objLoadingImage, objBody.firstChild);
  }
}

//
// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func)
{
  var oldonload = window.onload;
  if (typeof window.onload != 'function'){
      window.onload = func;
  } else {
    window.onload = function(){
    oldonload();
    func();
    }
  }

}

function resizeOverlay()
{
    var objOverlay = document.getElementById('agi-overlay');
    var arrayPageSize = getPageSize();

    if (arrayPageSize[1] > objOverlay.clientHeight)
    {
      var newHeight = arrayPageSize[1] + 10;
      objOverlay.style.height = (newHeight + 'px');
    }
}

glbStdFeatures = "width=400,height=320,resizable=yes,scrollbars=yes,toolbar=no";
glbStdFeaturesExcSize = "resizable=yes,scrollbars=yes,toolbar=no";

var newwin;
function encodePurl(purl){
  if (purl.charAt(purl.length-1) == '/') {
    purl=purl.slice(0,-1);
  }
  purl=purl.replace(/http:\/\//,"");
  purl=purl.replace(/\&/g,"|");
  purl=purl.replace(/\?/g,"_");
  purl=purl.replace(/\=/g,":");
  purl=purl.replace(/\%%20/g,"perc20");
  purl=purl.replace(/ /g,"perc20");
  purl=purl.replace(/\+/g,"%%20");
  purl=purl.replace(/#.*$/,"");
  purl=purl.replace(/%%(\d+)/g,"perc$1");
  return purl;
}

function decodePurl(purl){
  purl=purl.replace(/\|/g,"&");
  purl=purl.replace(/_/g,"?");
  purl=purl.replace(/:/g,"=");
  purl=purl.replace(/perc(\d+)/g,"%%$1");
  purl=purl.replace(/\/popup\/signin\.pd/,"/index.pd");
  purl=purl.replace(/\/popup\/signout\.pd/,"/index.pd");
  if(purl){
    purl="http://"+purl;
  }
  return purl;
}

function openJoin(url, purl, width, height, windowname, intX, intY, same_win) {
  if(!purl)
  {
    purl=window.location.href;
  }
  if(!width)
  {
    width='300';
  }
  if(!height)
  {
    height='320';
  }
  if(!windowname)
  {
    windowname = "joinwin";
  }
  if(!intX)
  {
    intX=0;
  }
  if(!intY)
  {
    intY=0;
  }
  if(!same_win)
  {
    same_win = false;
  }

  pageindex = -1;
  questionindex = -1;
  questionindex = url.indexOf("?");
  if ((url.indexOf("offer.pd")>0) && (url.indexOf("isic_offer.pd")<0))
  {
    pageindex = url.indexOf("offer.pd");
  }
  else if (url.indexOf("announce.pd")>0)
  {
    pageindex = url.indexOf("announce.pd");
  }
  else if (url.indexOf("marketingpop.pd")>0)
  {
    pageindex = url.indexOf("marketingpop.pd");
  }

  purl = encodePurl(purl);
  var ma      = document.getElementById("ma");
  var musicon = document.getElementById("wcMusicOn");
  var mci     = document.getElementById("musicChoiceIndex");
  if (ma && ma.value != "nomusic" && purl.indexOf("&ma=") == -1)
  {
    purl += "|ma:" + ma.value.replace(".mp3","");
  }
  if (musicon)
  {
    purl += "|wcMusicOn:" + musicon.value;
  }
  if (mci)
  {
    purl += "|musicChoiceIndex:" + mci.value;
  }
  if (url.indexOf('subscribe.pd') >= 0)
  {
      purl = purl.replace(/\%20/g, "perc20");
      purl = purl.replace(/\%26/g, "and");
      url += "&purl=" + purl;
      same_win = true;
  }
  else if(url.indexOf("ostatus") >= 0)
  {
  	if (url.indexOf('subs.subsag') >= 0)
  	{
	  	purl = purl.replace(/\%20/g, "+");
	  	purl = purl.replace(/\%26/g, "and");
	}
    url = url.replace(/ostatus/,"purl="+purl+"&ostatus");
  }
  else if (questionindex == -1)
  {
    url += "?purl=" + purl;
  }
  else
  {
    url += "&purl=" + purl;
  }

  if(pageindex < questionindex && !same_win)
  {
    if (intX || intY)
    {
      strWinFeatures="resizable=no,screenX="+intX+",screenY="+intY+",left="+intX+",top="+intY+",scrollbars=no,width="+width+",height="+height;
      newwin = window.open(url,windowname,strWinFeatures);
    }
    else
    {
      strWinFeatures="resizable=no,scrollbars=no,width="+width+",height="+height;
      newwin = window.open(url,windowname,strWinFeatures);
    }
    newwin.focus();
  }
  else
  {
    window.document.location.href=url;
  }
}

function openOfferPop(url, cookiename, cookiedays)
{
  purl = window.location.href;

  if(!url)
  {
    var url = "/popup/offer.pd?";
    if (purl.indexOf("cnp") >= 0)
    {
      url = url + "cnp=1";
    }
  }

  var intSw = window.screen.availWidth;
  var intSh = window.screen.availHeight;
  var intW = 300;
  var intH = 320;
  var intX=intSw - intW;
  var intY=intSh - intH;

  if (cookiename)
  {
    var allcookies = document.cookie;
    var pos = allcookies.indexOf(cookiename);
//only pop the window if we don't see the cookie
    if (pos == -1)
    {
      SECONDS_PER_DAY = 86400;
      myMinTimeOut    = SECONDS_PER_DAY*cookiedays;
      myDate          = new Date();
      myDate.setTime(myDate.getTime()+(myMinTimeOut*1000));
      document.cookie = cookiename + "=true; expires=" + myDate.toGMTString();
      openJoin(url,0,0,0,0,intX,0);
    }
  }
  else
  {
    openJoin(url,0,0,0,0,intX,0);
  }
}

//Generic Open Window
function OpenNewWindow(url,winwidth,winheight,bar)
{
  NewWindow = window.open(url,'descr','toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,copyhistory=no,width='+winwidth+',height='+winheight+',scrollbars='+bar);
}

function appendHiddens(url, purl)
{
  var ma      = document.getElementById("ma");
  var musicon = document.getElementById("wcMusicOn");
  var mci     = document.getElementById("musicChoiceIndex");
  if (ma && ma.value != "nomusic" && purl.indexOf("&ma=") == -1)
  {
    purl += "&ma=" + ma.value.replace(".mp3","");
  }
  if (musicon)
  {
    purl += "&wcMusicOn=" + musicon.value;
  }
  if (mci)
  {
    purl += "&musicChoiceIndex=" + mci.value;
  }
  purl = escape(purl);
  window.document.location.href=url+purl;
}

function recordMiscUsageSuccess(request) {
}

function recordMiscUsageError(request) {
}

function recordMiscUsage(usage_type, product_number, path_number){
    // set up query string for ajax call
    var query = "utype=" + usage_type + "&product=" + product_number + "&path=" + path_number;

    // Post the Ajax call to store miscusage
    var req = new Requester("/miscusage.pd", "POST", true, true);
    req.onsuccess = recordMiscUsageSuccess;
    req.onerror = recordMiscUsageError;
    req.sendRequest(query);
}

/**
* These functions make the "My AG" button and dropdown menu work.
*
*
* __version__ = "$Revision: 4 $"
* __author__ = "$Author: Aoliver $"
* __date__ = "$Date: 7/18/07 3:32p $"
*
*/


startList = function() {
    if (document.all&&document.getElementById) {
        navRoot = document.getElementById("myag-menu");
        if(!navRoot){
            return;
        }
        for (i=0; i<navRoot.childNodes.length; i++) {
            node = navRoot.childNodes[i];
            if (node.nodeName=="LI") {
                node.onmouseover=function() {
                    this.className+=" over";
                    var selects = document.getElementsByTagName("SELECT");
                    for(var i = 0; i< selects.length; i++){
                        selects[i].style.visibility = "hidden";
                    }
                }
                node.onmouseout=function() {
                this.className=this.className.replace(" over", "");
                var selects = document.getElementsByTagName("SELECT");
                    for(var i = 0; i< selects.length; i++){
                        selects[i].style.visibility = "visible";
                    }
               }
            }
        }
    }
}
if (dojo != null)
try{
    dojo.addOnLoad(startList);
}
catch(e){
    window.onload=startList
}

var NAV_KEYS = {'ecards'      : 'ec',
                'printables'  : 'cnp',
                'downloads'   : 'dl',
                'invitations' : 'inv'}

function navtype_toString(navtype_object){
  var navtype_string = '';
  for (var value in navtype_object) {
      navtype_string += ('"' + value + '"' +  ':' + '"' + navtype_object[value] + '"' + ',');
  }
  dojo.debug('navtype_toString - navtype_string ' + navtype_string);
  return '{' + navtype_string.slice(0,-1) + '}'
}

function setNavTypeCookie(key, type){
  dojo.debug('*********  BEGIN  NAVTYPE ***************');
  dojo.debug('setNavTypeCookie');
  // set the navtype cookie logic goes here
  navtype_key = 'navtype';

  // get navtype from magic cookie
  var navtype_cookie = MagicCookie.getCookieValue(navtype_key);
  dojo.debug('MagicCookie: ' + navtype_cookie);

  var ary_navtype = new Object();
  // Create a navtype object (associative array)
  if (navtype_cookie){
     dojo.debug('Cookie exists: not null');
     //var ary_navtype = eval(navtype_cookie);
     eval("var ary_navtype =" +  navtype_cookie + ';');
     dojo.debug(ary_navtype);
  }
  else {
     dojo.debug('Cookie does not exist: null');
  }

  // Assign navtype
  ary_navtype[key] = type;

  // Serialize the object for storage in the MagicCookie
  var navtype_serialized = navtype_toString(ary_navtype);
  dojo.debug('navtype_serialized: ' + navtype_serialized);

  // Write the session cookie
  MagicCookie.setCookieValue(navtype_key, navtype_serialized);

  //dojo.debug(key + ':' + type);
  dojo.debug('*********  END NAVTYPE ***************');
}

function getKey(){
  // Get the key for the navtype to be storedretreived based on the path.
  // - default navkey is ecards
  // - This function should be made more robust
  var path = window.location.pathname.split('/')[1];
  return NAV_KEYS[path];
}

function getNavTypeFromCookie(){
  // @return string for navtype for current usage
  dojo.debug('*********  BEGIN  NAVTYPE ***************');
  dojo.debug('getNavTypeCookie');
  navtype_key = 'navtype';
  var navtype_cookie = MagicCookie.getCookieValue(navtype_key);

  // if navtype cookie exists, return the navtype for this "Tab" (ecards, downloads, etc)
  // - if there is not a navtype cookie, return the default navtype of other
  dojo.debug('navtype_cookie ' + navtype_cookie);
  if (navtype_cookie){
     try {
        dojo.debug('Cookie exists: not null');
        eval("var ary_navtype =" +  navtype_cookie + ';');
        dojo.debug(ary_navtype);
        dojo.debug(ary_navtype[getKey()].toLowerCase());
        return ary_navtype[getKey()].toLowerCase();
     }
     catch (err){
        return 'other'
     }
  }
  else{
     dojo.debug('Cookie does not exist: null');
     return 'other';
  }
}

function removeNavTypeFromCookie(self){
   //  If cookie exists, remove navtype(ec,dl,etc) from cookie value, write the new cookie value
   navtype_key = 'navtype';
   var navtype_cookie = MagicCookie.getCookieValue(navtype_key);
   dojo.debug('removeNavTypeFromCookie');
   dojo.debug(navtype_cookie);

   // if navtype cookie exists,
   //  - attempt to delete the navtype for this "Tab" (ecards, downloads, etc)
   // - set the cookie
   // if there is not a navtype cookie, do nothing
   if (navtype_cookie){
      eval("var ary_navtype =" +  navtype_cookie + ';');
      key = getKey();
      dojo.debug('key '+ key);
      if (eval('delete ary_navtype.' + key + ';')){
         // Serialize the object for storage in the MagicCookie
         var navtype_serialized = navtype_toString(ary_navtype);
         dojo.debug('navtype_serialized: ' + navtype_serialized);

         // Write the session cookie
         MagicCookie.setCookieValue(navtype_key, navtype_serialized);
      }
      dojo.debug(ary_navtype);
   }
}

//window.alert = ag.debug;

function newsletter_onsuccess(request)
{
	msg_area = document.getElementById("agi-newsletter-message-area");
	try {
		if (request.responseText)
			eval("var results = " + request.responseText);
		else
			var results = {"status": -1, "message": "An error has occured.  Please try again"};
	} catch (e){
		var req = new Object();
		req.responseText = "error eval'ing response";
		newsletter_onerror(req);
		return;
	}

	write_newsletter_message(results.message);
	if (results.status > -1)
	{
		document.getElementById("agi-newsletter-email").value = "your email address";
		document.getElementById("agi-newsletter-email").blur();
	}
}

function newsletter_onerror(request)
{
	write_newsletter_message("We were unable to process your request.  Please try again in a few minutes.");
}

function write_newsletter_message(message)
{
	msg_area = document.getElementById("agi-newsletter-message-area");
	msg_area.innerHTML = message;
	if (message == "")
		msg_area.style.display = "none";
	else
		msg_area.style.display = "block";
}

function newsletter_signup()
{
	write_newsletter_message("");
	var email = document.getElementById("agi-newsletter-email");
	email.value = trim(email.value);

	if (validate_newsletter_email(email.value))
	{
		var query = "email=" + encodeURIComponent(email.value);

		var req = new Requester("/newsletter/signup.pd", "POST", true, true);
		req.onsuccess = newsletter_onsuccess;
		req.onerror = newsletter_onerror;

		req.sendRequest(query);
	} else {
		write_newsletter_message("Please enter a valid email address.");
	}
}

function email_focus(field, on_focus)
{
	if (field.value == 'your email address' && on_focus)
		field.value='';
	if (field.value == '' && !on_focus)
		field.value = 'your email address';
}

function validate_newsletter_email(email)
{
	if (email == "" || email == null)
		return false;
	else
		try
		{
			validate_email(email)
			return true;
		} catch (e) {
			return false;
		}
}
String.prototype.startswith = function(value)
{
    return this.indexOf(value)===0;
};


function quickshop(id)
{
    //set some defaults for our wiper
    var qs = this;
    this.container = document.getElementById(id);
    this.headings =
        {'occasion': 'I want to send a...',
         'recipient': 'To...',
         'sentiment': 'And I want it to be...'
        };
    this.defaults = {};
    this.check_defaults = true;
    this.chosen_count = 0;
    this.last_recipient = '';
    this.last_sentiment = '';

    this.do_onload = function()
    {
        dojo.debug('quickshop: START do_onload');
        dojo.event.connect(document.getElementById("qs_occasion"), 'onchange', this, 'do_onchange');
        dojo.event.connect(document.getElementById("qs_recipient"), 'onchange', this, 'do_onchange');
        dojo.event.connect(document.getElementById("qs_sentiment"), 'onchange', this, 'do_onchange');
        //parse querystring
        this.parse_url();
        //set the submit trigger/action
        var _submit = dojo.html.getElementsByClass('submit',this.container,'img')[0];
        _submit.onclick = function(){qs.submit_search();};
        //build the quickshop widget
        this.build_quickshop();
        //don't check defaults again; only check during initial build
        this.check_defaults = false;
        dojo.debug('quickshop: END do_onload');
    };


    this.update_occasion = function(val){
        var occasions = qs_data.occasions;
        for (o in occasions){
            occasion = occasions[o];
            if (occasion.name == val){
                this.occasion = occasion;
                var recipients = occasion.recipients;
                var sentiments = occasion.sentiments;
                this.build_dropdown('sentiment',sentiments);
                this.build_dropdown('recipient', recipients);
                this.build_dropdown('occasion', occasions, val);
                return;
            }
        }
    };

    /**
        the recipient field got a new value. recalculate
        the sentiment possibilities. occasion stays put
    */
    this.update_recipient = function(val){
        dojo.debug("update_recipient: count " + this.chosen_count);
        this.last_recipient = val;
        if(val == ''){
            //we're doing a "reset" of this field, so reset everything
            this.build_dropdown('sentiment',this.occasion.sentiments, this.last_sentiment);
            this.chosen_count--;
        }
        if(document.getElementById('qs_recipient').value != val){
            document.getElementById('qs_recipient').value = val;
        }
        if(document.getElementById('qs_sentiment').value != '' && this.chosen_count < 3){
            this.chosen_count ++;
            return;
        }
        dojo.debug('updating sentiments');
        for( r in this.occasion.recipients){
            recipient = this.occasion.recipients[r];
            if( recipient.name == val){
                var sentiments = recipient.sentiments;
                this.build_dropdown('sentiment', sentiments);
            };
        }
        this.chosen_count = 2;
    };

    this.update_sentiment = function(val){
        dojo.debug("update_sentiment: count " + this.chosen_count + ',' + val);
        this.last_sentiment = val;
        if(val == ''){
            this.build_dropdown('recipient',this.occasion.recipients, this.last_recipient);
            this.chosen_count--;
        }
        if(document.getElementById('qs_sentiment').value != val){
            document.getElementById('qs_sentiment').value = val;
        }
        if(document.getElementById('qs_recipient').value != '' && this.chosen_count < 3){
            this.chosen_count++;
            return;
        }
        dojo.debug('updating_recipients');
        //check if we need to update recipient
        for(s in this.occasion.sentiments){
            sentiment = this.occasion.sentiments[s];
            if (sentiment.name == val){
                var recipients = sentiment.recipients;
                this.build_dropdown('recipient', recipients);
            }
        }
        this.chosen_count = 2;
    };

    this.build_quickshop = function()
    {
        //get proper "chunk" of dropdowns
        this.occasions = qs_data.occasions;
        this.occasion = qs_data.occasions[1];
        if (this.defaults.occasion != null){
            this.update_occasion(this.defaults.occasion);
        }
        else{
            this.update_occasion(qs_data.occasions[0].name);
        }
        if( this.defaults.recipient != null){
            this.update_recipient(this.defaults.recipient);
        }
        if( this.defaults.sentiment != null){
            this.update_sentiment(this.defaults.sentiment);
        }
        this.chosen_count = 1;
        dojo.debug('END build_quickshop');
    };

    this.build_dropdown = function(which, unit, value, empty)
    {
        dojo.debug('build_dropdown, got which='+which+', value='+value+', empty='+empty);
        //create <select>
        //var _select = make_node('select',{'id':'qs_'+which});
        var _select = document.getElementById('qs_' + which);
        //add <option>s to the <select>
        this.add_options(unit, _select, which, value, empty, true);
        dojo.debug('done adding options to select');
        //insert <select> into DOM
        //this.insert_select(_select, which);
        dojo.debug('added select to DOM');
    };

    this.add_options = function(unit, _select, which, value, empty)
    {
        this.remove_options(_select);
        //check optional parms
        //extra = extra===undefined ? '' : extra;
        empty = empty===undefined ? true : empty;

        //add a default <option> --> e.g. "[Choose Recipient type]"
        var offset = 0;
        if(empty && (_select.id == "qs_recipient" || _select.id == "qs_sentiment"))
        {
            var proper = which.charAt(0).toUpperCase()+which.substring(1);
            //minor hack for a last minute copy change
            proper = proper.replace('Sentiment','Style');
            this._add_option("[Choose "+proper+"]", "", _select, offset);
            offset += 1;
        }
        //loop through and build each <option>
        for(var i=0; i<unit.length; i++)
        {
            var _selected = false;
            //is <option> selected ?
            if (value != undefined)
                _selected = unit[i].name==value;
            //add <option>
            this._add_option(unit[i].name, unit[i].name, _select, i+offset, _selected);
        }
    };

    this._add_option = function(text, value, _select, idx, _selected)
    {
        //add an <option> to a <select>
        var option = document.createElement('option');
        option.text = text.toLowerCase();
        option.value = value;
        if(_select.id == 'qs_occasion'){
            option.text = option.text + ' ecard';
        }
        if(_select.options.add) {
            _select.options.add(option,idx);
        } else {
            _select.appendChild(option);
        }
        if(_selected)
        {
            _select.options.selectedIndex = idx;
        }
    };

    this.remove_options = function(_select)
    {
        //remove all <option>s from a <select>
        for(var i=_select.options.length-1; i>=0; i--)
        {
            _select.remove(i);
        }
        _select.options.length = 0;
    };

    this.replace_options = function()
    {
        dojo.debug('replace_options...');
        //get proper "chunk" of dropdowns
        var dropdowns = qs.get_group();

        //Sentiment
        var _select = document.getElementById('qs_sentiment');
        qs.remove_options(_select);
        var sentiment = dropdowns.sentiments;
        qs.add_options(sentiment, _select, 'sentiment');

        //Recipient
        _select = document.getElementById('qs_recipient');
        qs.remove_options(_select);
        var recipient = dropdowns.recipients;
        qs.add_options(recipient, _select, 'recipient');

        dojo.debug('END replace_options');
    };

    this.insert_select = function(_select, which)
    {
        //text above each dropdown
        //var heading = make_node('strong',{},make_text(this.headings[which]));
        var br = make_node('br',{});

        //insert <select> and text into DOM (in reverse order)
        dojo.dom.prependChild(br, this.container);
        dojo.dom.prependChild(_select, this.container);
        //dojo.dom.prependChild(heading, this.container);
    };

    this.do_onchange = function(e){
        dojo.debug('doing onchange for ' + e.target.id);
        var val = e.target.value;
        switch(e.target.id){
            case 'qs_occasion':
                this.update_occasion(val);
                this.chosen_count =1;
                break;
            case 'qs_sentiment':
                this.update_sentiment(val);
                break;
            case 'qs_recipient':
                this.update_recipient(val);
                break;
        }
    };

    this.parse_url = function()
    {
        //grab querystring
        var _qs = window.location.search.replace('?','').split('&');
        //loop through parms
        for(var i=0; i<_qs.length; i++)
        {
            //quickshop parm?
            if(_qs[i].startswith('qs_'))
            {
                //turn into a useable NVP
                var nvp = _qs[i].split('=');
                if(nvp.length != 2)
                {
                    continue;
                }
                //save off value; use for setting selected <option>
                this.defaults[nvp[0].replace('qs_','')] = unescape(nvp[1]);
            }
        }
    };

    this.submit_search = function()
    {
        //grab the quickshop <select>s
        var ds = this.container.getElementsByTagName('select');
        var u = ahost+'/ecards/quickshop.pd?lpage=quickshop&';
        var p = '';
        //loop through the <select>s
        for(var i=0; i<ds.length; i++)
        {
            //grab value, append it to parms
            var d = ds[i];
            var value = d.options[d.selectedIndex].value;
            p += value ? d.id+'='+escape(value)+'&' : '';
        }
        if(!p)
        {
            alert('Please make a selection first.');
            return;
        }
        //remove trailing '&'
        p = p.replace(/&$/,'');
        u = u+p;
        //redirect to results page with appropriate parms
        window.location = u;
    };

    //get this show on the road!
    this.do_onload();
}

function RegistrationTrigger(url, attr) {
  var loc = '/register/lb.pd';
  var attrs = {'width':440,'hideloading':true};
  if(url) loc = url;
  if(attr) attrs = attr;

  var ftrigger = this;
  this.show = function(app, returnurl) {
    var url = loc;
    if(app) url += '?app='+escape(app)+'&referer='+escape(returnurl);
    lightbox(url, attrs);
    omniture.swap_vars_and_ping({'s_pageName':loc});
  }
  this.hide = function() {
    hideLightbox();
  }
}

function showCellInfo(btn) {
  document.getElementById('cell_info').style.display='block';
}
function hideCellInfo(btn) {
  document.getElementById('cell_info').style.display='none';
}


function Requester(url, method, async, showbusy)
{
  var objReq = this;
  var req = null;

  this.async = async;
  this.method = method;
    //this.url = fixurl(url);
    this.url = url;

  this.showbusy = showbusy;
  this.in_process = false;

  this.get_millisecond_query = function()
  {
    var today = new Date();
    var ms = today.getTime();
    return "&ajax_requester_ms=" + ms;
  };

  this.sendRequest = function(strQuery)
  {
    if (strQuery && strQuery.length > 0)
      strQuery += this.get_millisecond_query();

    try{
      // branch for native XMLHttpRequest object
      if(window.XMLHttpRequest)
        this.req = new XMLHttpRequest();
      // branch for IE/Windows ActiveX version
      else if(window.ActiveXObject)
        this.req = new ActiveXObject("Microsoft.XMLHTTP");
      // failure
      else
        this.req = '';
    }
    // failure
    catch(e){
      this.req = '';
    }

    if(this.req && this.url != null)
    {
        if (this.showbusy)
          document.body.style.cursor = "wait";
        if(!strQuery)
            strQuery = '';
        this.req.onreadystatechange = this.processRequest;
        if (this.method == "GET" && strQuery.length > 0)
          this.url = this.url + "?" + strQuery;
        this.req.open(this.method, this.url, this.async);
        this.req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        this.req.setRequestHeader("Content-length", strQuery.length);
        this.in_process = true;
        if (this.method == "GET")
          this.req.send("");
        else
          this.req.send(strQuery);
    }
  }

  this.processRequest = function()
  {
    // only if req shows "loaded"
    if (objReq.req.readyState == 4)
    {
      var kaboom = "";

      if (objReq.req.getResponseHeader("Kaboom"))
        kaboom = objReq.req.getResponseHeader("Kaboom");

      // build a modifiable copy of the request object
      var pseudo_req = new Object;
      pseudo_req.responseText = objReq.req.responseText;
      pseudo_req.responseXML = objReq.req.responseXML;
      pseudo_req.status = objReq.req.status;
      pseudo_req.statusText = objReq.req.statusText;
      pseudo_req.readyState = objReq.req.readyState;

      objReq.in_process = false;
      if (objReq.showbusy)
        document.body.style.cursor = "auto";
      // only if "OK"
      if (pseudo_req.responseText)
        pseudo_req.responseText = pseudo_req.responseText.replace("<!--this page was compressed by your friendly neighborhood pydriver-->", "")
      if (kaboom.toLowerCase() == "true")
      {
        if (objReq.onerror)
          objReq.onerror(pseudo_req);
      }
      else if (objReq.req.status == 200)
      {
        if (objReq.onsuccess)
          objReq.onsuccess(pseudo_req);
      } else {
        if (objReq.onerror)
          objReq.onerror(pseudo_req);
      }
    }
  }

  this.formToQuery = function(objForm)
  {
    // given a form loop through the elements and build a
    // URL encoded query string.

    var arrElements = objForm.elements;
                var iIndex = 0;
                var alphaExp = /[0-9a-zA-Z]+$/;
                var test =""
                var alphapunct =/[0-9a-zA-Z-_!?()\'\"{}=+#$*., ]/;
                var scrub ="";

    var strQuery = "";
                var strDebug = "";



    for (i=0; i < arrElements.length; i++)
    {
      if (strQuery.length > 0)
        strQuery += "&";

      if ((arrElements[i].type == "radio" || arrElements[i].type == "checkbox") && arrElements[i].checked)
        strQuery += arrElements[i].name + "=" + encodeURIComponent(arrElements[i].value);
      else if (arrElements[i].type == "select-one")
        strQuery += arrElements[i].name + "=" + encodeURIComponent(arrElements[i].options[arrElements[i].selectedIndex].value);
      else if (arrElements[i].type == "text" || arrElements[i].type == "textarea" || arrElements[i].type == "hidden")
      {
        var this_value = arrElements[i].value;

        strQuery += arrElements[i].name + "=" + encodeURIComponent(this_value);
      }

    }

    return strQuery;
  }
}

//var script_fragment = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)'
var script_fragment = '<script[^>]*>([\\s\\S]*?)<\/script>'
function stripScripts(html_string)
{
  return html_string.replace(new RegExp(script_fragment, 'img'), '');
}

function extractScripts(html_string)
{
  var matchAll = new RegExp(script_fragment, 'img');
  var matchOne = new RegExp(script_fragment, 'im');
  var matches = html_string.match(matchAll);
  var results = new Array();
  if (matches) {
      for (var i = 0; i < matches.length; i++) {
          if (matches[i].indexOf("agi-lb-exec") != -1)
            results.push(matches[i].match(matchOne)[1]);
          };
      };
  return results;
}

function evalScripts(html_string)
{
  var scripts = extractScripts(html_string);
  for (i = 0; i < scripts.length; i++)
  {
    try {
      eval(scripts[i]);
    } catch (e) {}
  }
}

function checkAll(formId, checked)
{
  form = document.getElementById(formId);

  for (i = 0 ; i < form.elements.length; i++)
  {
    if (form.elements[i].type == "checkbox")
      form.elements[i].checked = checked;
  }
}

function countChecked(formId)
{
  var form = document.getElementById(formId);
  var checked = 0;
  for (i = 0 ; i < form.elements.length; i++)
  {
    if (form.elements[i].type == "checkbox" & form.elements[i].checked)
      checked++;
  }
  return checked;
}

function selectAll(listId, checked)
{
	if (checked==undefined){
    	var is_checked = true;
	} else {
		var is_checked = checked;
	}

	var list = document.getElementById(listId);
	var elements = document.getElementsByName("event_id"); /*cs*/


	for (i = 0 ; i < list.childNodes.length; i++)
	{
		if (list.childNodes[i].nodeName == "LI")
		{
			for (j = 0; j < list.childNodes[i].childNodes.length; j++)
			{
				if (list.childNodes[i].childNodes[j].type == "checkbox")
				{
					list.childNodes[i].childNodes[j].checked = is_checked;
					/*seek and set any identical valued checkboxes*/
					len = elements.length;
					for (n=0; n < len; n++)
					{
						if ( (elements[n].value) == (list.childNodes[i].childNodes[j].value) )
						{
							elements[n].checked = is_checked;
						}
					}
				}
			}
		}
	}
}

function selectEqual(oCheck)
{
  var elements = document.getElementsByName(oCheck.name);

  for (i=0; i < elements.length; i++)
  {
    if (oCheck.form.elements[i].value == oCheck.value)
      oCheck.form.elements[i].checked = oCheck.checked;
  }
}

function fixurl(url) {
    if(url.indexOf('http') != 0) {
        var sep = '';
        url.indexOf('/') == 0 ? sep = '' : sep = '/';
        url = ajaxhost()+sep+url;
    }
  return url;
}

function ajaxhost() {
    return document.location.protocol+'//'+document.location.hostname;
}

/*=:project
    scalable Inman Flash Replacement (sIFR) version 3, beta 1

  =:file
    Copyright: 2006 Mark Wubben.
    Author: Mark Wubben, <http://novemberborn.net/>

  =:history
    * IFR: Shaun Inman
    * sIFR 1: Mike Davidson, Shaun Inman and Tomas Jogin
    * sIFR 2: Mike Davidson, Shaun Inman, Tomas Jogin and Mark Wubben

  =:license
    This software is licensed and provided under the CC-GNU LGPL.
    See <http://creativecommons.org/licenses/LGPL/2.1/>
*/

var parseSelector=(function(){var _1=/\s*,\s*/;var _2=/\s*([\s>+~(),]|^|$)\s*/g;var _3=/([\s>+~,]|[^(]\+|^)([#.:@])/g;var _4=/^[^\s>+~]/;var _5=/[\s#.:>+~()@]|[^\s#.:>+~()@]+/g;function parseSelector(_6,_7){_7=_7||document.documentElement;var _8=_6.split(_1),_9=[];for(var i=0;i<_8.length;i++){var _b=[_7],_c=toStream(_8[i]);for(var j=0;j<_c.length;){var _e=_c[j++],_f=_c[j++],_10="";if(_c[j]=="("){while(_c[j++]!=")"&&j<_c.length){_10+=_c[j]}_10=_10.slice(0,-1)}_b=select(_b,_e,_f,_10)}_9=_9.concat(_b)}return _9}function toStream(_11){var _12=_11.replace(_2,"$1").replace(_3,"$1*$2");if(_4.test(_12)){_12=" "+_12}return _12.match(_5)||[]}function select(_13,_14,_15,_16){return (_17[_14])?_17[_14](_13,_15,_16):[]}var _18={toArray:function(_19){var a=[];for(var i=0;i<_19.length;i++){a.push(_19[i])}return a}};var dom={isTag:function(_1d,tag){return (tag=="*")||(tag.toLowerCase()==_1d.nodeName.toLowerCase())},previousSiblingElement:function(_1f){do{_1f=_1f.previousSibling}while(_1f&&_1f.nodeType!=1);return _1f},nextSiblingElement:function(_20){do{_20=_20.nextSibling}while(_20&&_20.nodeType!=1);return _20},hasClass:function(_21,_22){return (_22.className||"").match("(^|\\s)"+_21+"(\\s|$)")},getByTag:function(tag,_24){return _24.getElementsByTagName(tag)}};var _17={"#":function(_25,_26){for(var i=0;i<_25.length;i++){if(_25[i].getAttribute("id")==_26){return [_25[i]]}}return []}," ":function(_28,_29){var _2a=[];for(var i=0;i<_28.length;i++){_2a=_2a.concat(_18.toArray(dom.getByTag(_29,_28[i])))}return _2a},">":function(_2c,_2d){var _2e=[];for(var i=0,_30;i<_2c.length;i++){_30=_2c[i];for(var j=0,_32;j<_30.childNodes.length;j++){_32=_30.childNodes[j];if(_32.nodeType==1&&dom.isTag(_32,_2d)){_2e.push(_32)}}}return _2e},".":function(_33,_34){var _35=[];for(var i=0,_37;i<_33.length;i++){_37=_33[i];if(dom.hasClass([_34],_37)){_35.push(_37)}}return _35},":":function(_38,_39,_3a){return (pseudoClasses[_39])?pseudoClasses[_39](_38,_3a):[]}};parseSelector.selectors=_17;parseSelector.pseudoClasses={};parseSelector.util=_18;parseSelector.dom=dom;return parseSelector})();
var sIFR=new function(){var _3b=this;var _3c="sIFR-active";var _3d="sIFR-replaced";var _3e="sIFR-flash";var _3f="sIFR-ignore";var _40="sIFR-alternate";var _41="sIFR-class";var _42="sIFR-layout";var _43="http://www.w3.org/1999/xhtml";var _44=6;var _45=126;var _46=8;var _47="SIFR-PREFETCHED";var _48=" ";this.isActive=false;this.isEnabled=true;this.hideElements=true;this.replaceNonDisplayed=false;this.preserveSingleWhitespace=false;this.fixWrap=true;this.registerEvents=true;this.setPrefetchCookie=true;this.cookiePath="/";this.domains=[];this.fromLocal=true;this.forceClear=false;this.forceWidth=false;this.fitExactly=false;this.forceTextTransform=true;this.useDomContentLoaded=true;this.debugMode=false;this.hasFlashClassSet=false;var _49=0;var _4a=false,_4b=false;var dom=new function(){this.getBody=function(){var _4d=document.getElementsByTagName("body");if(_4d.length==1){return _4d[0]}return null};this.addClass=function(_4e,_4f){if(_4f){_4f.className=((_4f.className||"")==""?"":_4f.className+" ")+_4e}};this.removeClass=function(_50,_51){if(_51){_51.className=_51.className.replace(new RegExp("(^|\\s)"+_50+"(\\s|$)"),"").replace(/^\s+|(\s)\s+/g,"$1")}};this.hasClass=function(_52,_53){return new RegExp("(^|\\s)"+_52+"(\\s|$)").test(_53.className)};this.create=function(_54){if(document.createElementNS){return document.createElementNS(_43,_54)}return document.createElement(_54)};this.setInnerHtml=function(_55,_56){if(ua.innerHtmlSupport){_55.innerHTML=_56}else{if(ua.xhtmlSupport){_56=["<root xmlns=\"",_43,"\">",_56,"</root>"].join("");var xml=(new DOMParser()).parseFromString(_56,"text/xml");xml=document.importNode(xml.documentElement,true);while(_55.firstChild){_55.removeChild(_55.firstChild)}while(xml.firstChild){_55.appendChild(xml.firstChild)}}}};this.getComputedStyle=function(_58,_59){var _5a;if(document.defaultView&&document.defaultView.getComputedStyle){_5a=document.defaultView.getComputedStyle(_58,null)[_59]}else{if(_58.currentStyle){_5a=_58.currentStyle[_59]}}return _5a||""};this.getStyleAsInt=function(_5b,_5c,_5d){var _5e=this.getComputedStyle(_5b,_5c);if(_5d&&!/px$/.test(_5e)){return 0}_5e=parseInt(_5e);return isNaN(_5e)?0:_5e};this.getZoom=function(){return _5f.zoom.getLatest()}};this.dom=dom;var ua=new function(){var ua=navigator.userAgent.toLowerCase();var _62=(navigator.product||"").toLowerCase();this.macintosh=ua.indexOf("mac")>-1;this.windows=ua.indexOf("windows")>-1;this.quicktime=false;this.opera=ua.indexOf("opera")>-1;this.konqueror=_62.indexOf("konqueror")>-1;this.ie=false/*@cc_on || true @*/;this.ieSupported=this.ie&&!/ppc|smartphone|iemobile|msie\s5\.5/.test(ua)/*@cc_on && @_jscript_version >= 5.5 @*/;this.ieWin=this.ie&&this.windows/*@cc_on && @_jscript_version >= 5.1 @*/;this.windows=this.windows&&(!this.ie||this.ieWin);this.ieMac=this.ie&&this.macintosh/*@cc_on && @_jscript_version < 5.1 @*/;this.macintosh=this.macintosh&&(!this.ie||this.ieMac);this.safari=ua.indexOf("safari")>-1;this.webkit=ua.indexOf("applewebkit")>-1&&!this.konqueror;this.khtml=this.webkit||this.konqueror;this.gecko=!this.webkit&&_62=="gecko";this.operaVersion=this.opera&&/.*opera(\s|\/)(\d+\.\d+)/.exec(ua)?parseInt(RegExp.$2):0;this.webkitVersion=this.webkit&&/.*applewebkit\/(\d+).*/.exec(ua)?parseInt(RegExp.$1):0;this.geckoBuildDate=this.gecko&&/.*gecko\/(\d{8}).*/.exec(ua)?parseInt(RegExp.$1):0;this.konquerorVersion=this.konqueror&&/.*konqueror\/(\d\.\d).*/.exec(ua)?parseInt(RegExp.$1):0;this.flashVersion=0;if(this.ieWin){var axo;var _64=false;try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7")}catch(e){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");this.flashVersion=6;axo.AllowScriptAccess="always"}catch(e){_64=this.flashVersion==6}if(!_64){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash")}catch(e){}}}if(!_64&&axo){this.flashVersion=parseFloat(/([\d,?]+)/.exec(axo.GetVariable("$version"))[1].replace(/,/g,"."))}}else{if(navigator.plugins&&navigator.plugins["Shockwave Flash"]){var _65=navigator.plugins["Shockwave Flash"];this.flashVersion=parseFloat(/(\d+\.?\d*)/.exec(_65.description)[1]);var i=0;while(this.flashVersion>=_46&&i<navigator.mimeTypes.length){var _67=navigator.mimeTypes[i];if(_67.type=="application/x-shockwave-flash"&&_67.enabledPlugin.description.toLowerCase().indexOf("quicktime")>-1){this.flashVersion=0;this.quicktime=true}i++}}}this.flash=this.flashVersion>=_46;this.transparencySupport=this.macintosh||this.windows;this.computedStyleSupport=this.ie||document.defaultView&&document.defaultView.getComputedStyle&&(!this.gecko||this.geckoBuildDate>=20030624);this.css=true;if(this.computedStyleSupport){try{var _68=document.getElementsByTagName("head")[0];_68.style.backgroundColor="#FF0000";var _69=dom.getComputedStyle(_68,"backgroundColor");this.css=!_69||/\#F{2}0{4}|rgb\(255,\s?0,\s?0\)/i.test(_69);_68=null}catch(e){}}this.xhtmlSupport=!!window.DOMParser&&!!document.importNode;this.innerHtmlSupport;try{var n=dom.create("span");if(!this.ieMac){n.innerHTML="x"}this.innerHtmlSupport=n.innerHTML=="x"}catch(e){this.innerHtmlSupport=false}this.zoomSupport=!!(this.opera&&document.documentElement);this.geckoXml=this.gecko&&(document.contentType||"").indexOf("xml")>-1;this.requiresPrefetch=this.ieWin||this.khtml;this.verifiedKonqueror=false;this.supported=this.flash&&this.css&&(!this.ie||this.ieSupported)&&(!this.opera||this.operaVersion>=8)&&(!this.webkit||this.webkitVersion>=412)&&(!this.konqueror||this.konquerorVersion>3.5)&&this.computedStyleSupport&&(this.innerHtmlSupport||!this.khtml&&this.xhtmlSupport)};this.ua=ua;var _6b=new function(){function capitalize($){return $.toUpperCase()}this.normalize=function(str){if(_3b.preserveSingleWhitespace){return str.replace(/\s/g,_48)}return str.replace(/(\s)\s+/g,"$1")};this.textTransform=function(_6e,str){switch(_6e){case "uppercase":str=str.toUpperCase();break;case "lowercase":str=str.toLowerCase();break;case "capitalize":var _70=str;str=str.replace(/^\w|\s\w/g,capitalize);if(str.indexOf("function capitalize")!=-1){var _71=_70.replace(/(^|\s)(\w)/g,"$1$1$2$2").split(/^\w|\s\w/g);str="";for(var i=0;i<_71.length;i++){str+=_71[i].charAt(0).toUpperCase()+_71[i].substring(1)}}break}return str};this.toHexString=function(str){if(typeof (str)!="string"||!str.charAt(0)=="#"||str.length!=4&&str.length!=7){return str}str=str.replace(/#/,"");if(str.length==3){str=str.replace(/(.)(.)(.)/,"$1$1$2$2$3$3")}return "0x"+str};this.toJson=function(obj){var _75="";switch(typeof (obj)){case "string":_75="\""+obj+"\"";break;case "number":case "boolean":_75=obj.toString();break;case "object":_75=[];for(var _76 in obj){if(obj[_76]==Object.prototype[_76]){continue}_75.push("\""+_76+"\":"+_6b.toJson(obj[_76]))}_75="{"+_75.join(",")+"}";break}return _75};this.convertCssArg=function(arg){if(!arg){return {}}if(typeof (arg)=="object"){if(arg.constructor==Array){arg=arg.join("")}else{return arg}}var obj={};var _79=arg.split("}");for(var i=0;i<_79.length;i++){var $=_79[i].match(/([^\s{]+)\s*\{(.+)\s*;?\s*/);if(!$||$.length!=3){continue}if(!obj[$[1]]){obj[$[1]]={}}var _7c=$[2].split(";");for(var j=0;j<_7c.length;j++){var $2=_7c[j].match(/\s*([^:\s]+)\s*\:\s*([^\s;]+)/);if(!$2||$2.length!=3){continue}obj[$[1]][$2[1]]=$2[2]}}return obj};this.extractFromCss=function(css,_80,_81,_82){var _83=null;if(css&&css[_80]&&css[_80][_81]){_83=css[_80][_81];if(_82){delete css[_80][_81]}}return _83};this.cssToString=function(arg){var css=[];for(var _86 in arg){var _87=arg[_86];if(_87==Object.prototype[_86]){continue}css.push(_86,"{");for(var _88 in _87){if(_87[_88]==Object.prototype[_88]){continue}css.push(_88,":",_87[_88],";")}css.push("}")}return escape(css.join(""))}};this.util=_6b;var _5f={};_5f.fragmentIdentifier=new function(){this.fix=true;var _89;this.cache=function(){_89=document.title};function doFix(){document.title=_89}this.restore=function(){if(this.fix){setTimeout(doFix,0)}}};_5f.synchronizer=new function(){this.isBlocked=false;this.block=function(){this.isBlocked=true};this.unblock=function(){this.isBlocked=false;_8a.replaceAll()}};_5f.zoom=new function(){var _8b=100;this.getLatest=function(){return _8b};if(ua.zoomSupport&&ua.opera){var _8c=document.createElement("div");_8c.style.position="fixed";_8c.style.left="-65536px";_8c.style.top="0";_8c.style.height="100%";_8c.style.width="1px";_8c.style.zIndex="-32";document.documentElement.appendChild(_8c);function updateZoom(){if(!_8c){return}var _8d=window.innerHeight/_8c.offsetHeight;var _8e=Math.round(_8d*100)%10;if(_8e>5){_8d=Math.round(_8d*100)+10-_8e}else{_8d=Math.round(_8d*100)-_8e}_8b=isNaN(_8d)?100:_8d;_5f.synchronizer.unblock();document.documentElement.removeChild(_8c);_8c=null}_5f.synchronizer.block();setTimeout(updateZoom,54)}};this.hacks=_5f;var _8f={kwargs:[],replaceAll:function(){for(var i=0;i<this.kwargs.length;i++){_3b.replace(this.kwargs[i])}this.kwargs=[]}};var _8a={kwargs:[],replaceAll:_8f.replaceAll};function isValidDomain(){if(_3b.domains.length==0){return true}var _91="";try{_91=document.domain}catch(e){}if(_3b.fromLocal&&sIFR.domains[0]!="localhost"){sIFR.domains.unshift("localhost")}for(var i=0;i<_3b.domains.length;i++){if(_3b.domains[i]=="*"||_3b.domains[i]==_91){return true}}return false}this.activate=function(){if(!ua.supported||!this.isEnabled||this.isActive||!isValidDomain()){return}this.isActive=true;if(this.hideElements){this.setFlashClass()}if(ua.ieWin&&_5f.fragmentIdentifier.fix&&window.location.hash!=""){_5f.fragmentIdentifier.cache()}else{_5f.fragmentIdentifier.fix=false}if(!this.registerEvents){return}function handler(evt){_3b.initialize();if(evt&&evt.type=="load"){if(document.removeEventListener){document.removeEventListener("DOMContentLoaded",handler,false);document.removeEventListener("load",handler,false)}if(window.removeEventListener){window.removeEventListener("load",handler,false)}}}if(window.addEventListener){if(_3b.useDomContentLoaded&&ua.gecko){document.addEventListener("DOMContentLoaded",handler,false)}window.addEventListener("load",handler,false)}else{if(ua.ieWin){if(_3b.useDomContentLoaded&&!_4a){document.write("<scr"+"ipt id=__sifr_ie_onload defer src=//:></script>");document.getElementById("__sifr_ie_onload").onreadystatechange=function(){if(this.readyState=="complete"){handler();this.removeNode()}}}window.attachEvent("onload",handler)}}};this.setFlashClass=function(){if(this.hasFlashClassSet){return}dom.addClass(_3c,dom.getBody()||document.documentElement);this.hasFlashClassSet=true};this.removeFlashClass=function(){if(!this.hasFlashClassSet){return}dom.removeClass(_3c,dom.getBody());dom.removeClass(_3c,document.documentElement);this.hasFlashClassSet=false};this.initialize=function(){if(_4b||!this.isActive||!this.isEnabled){return}_4b=true;_8f.replaceAll();clearPrefetch()};function getSource(src){if(typeof (src)!="string"){if(src.src){src=src.src}if(typeof (src)!="string"){var _95=[];for(var _96 in src){if(src[_96]!=Object.prototype[_96]){_95.push(_96)}}_95.sort().reverse();var _97="";var i=-1;while(!_97&&++i<_95.length){if(parseFloat(_95[i])<=ua.flashVersion){_97=src[_95[i]]}}src=_97}}if(!src&&_3b.debugMode){throw new Error("sIFR: Could not determine appropriate source")}if(ua.ie&&src.charAt(0)=="/"){src=window.location.toString().replace(/([^:]+)(:\/?\/?)([^\/]+).*/,"$1$2$3")+src}return src}this.prefetch=function(){if(!ua.requiresPrefetch||!ua.supported||!this.isEnabled||!isValidDomain()){return}if(this.setPrefetchCookie&&new RegExp(";?"+_47+"=true;?").test(document.cookie)){return}try{_4a=true;if(ua.ieWin){prefetchIexplore(arguments)}else{prefetchLight(arguments)}if(this.setPrefetchCookie){document.cookie=_47+"=true;path="+this.cookiePath}}catch(e){if(_3b.debugMode){throw e}}};function prefetchIexplore(_99){for(var i=0;i<_99.length;i++){document.write("<embed src=\""+getSource(_99[i])+"\" sIFR-prefetch=\"true\" style=\"display:none;\">")}}function prefetchLight(_9b){for(var i=0;i<_9b.length;i++){new Image().src=getSource(_9b[i])}}function clearPrefetch(){if(!ua.ieWin||!_4a){return}try{var _9d=document.getElementsByTagName("embed");for(var i=_9d.length-1;i>=0;i--){var _9f=_9d[i];if(_9f.getAttribute("sIFR-prefetch")=="true"){_9f.parentNode.removeChild(_9f)}}}catch(e){}}function getRatio(_a0){if(_a0<=10){return 1.55}if(_a0<=19){return 1.45}if(_a0<=32){return 1.35}if(_a0<=71){return 1.3}return 1.25}function getFilters(obj){var _a2=[];for(var _a3 in obj){if(obj[_a3]==Object.prototype[_a3]){continue}var _a4=obj[_a3];_a3=[_a3.replace(/filter/i,"")+"Filter"];for(var _a5 in _a4){if(_a4[_a5]==Object.prototype[_a5]){continue}_a3.push(_a5+":"+escape(_6b.toJson(_6b.toHexString(_a4[_a5]))))}_a2.push(_a3.join(","))}return _a2.join(";")}this.replace=function(_a6,_a7){if(!ua.supported){return}if(_a7){for(var _a8 in _a6){if(typeof (_a7[_a8])=="undefined"){_a7[_a8]=_a6[_a8]}}_a6=_a7}if(!_4b){return _8f.kwargs.push(_a6)}if(_5f.synchronizer.isBlocked){return _8a.kwargs.push(_a6)}var _a9=_a6.elements;if(!_a9&&parseSelector){_a9=parseSelector(_a6.selector)}if(_a9.length==0){return}this.setFlashClass();var src=getSource(_a6.src);var css=_6b.convertCssArg(_a6.css);var _ac=getFilters(_a6.filters);var _ad=(_a6.forceClear==null)?_3b.forceClear:_a6.forceClear;var _ae=(_a6.fitExactly==null)?_3b.fitExactly:_a6.fitExactly;var _af=_ae||(_a6.forceWidth==null?_3b.forceWidth:_a6.forceWidth);var _b0=parseInt(_6b.extractFromCss(css,".sIFR-root","leading"))||0;var _b1=_6b.extractFromCss(css,".sIFR-root","background-color",true)||"#FFFFFF";var _b2=_6b.extractFromCss(css,".sIFR-root","opacity",true)||"100";if(parseFloat(_b2)<1){_b2=100*parseFloat(_b2)}var _b3=_6b.extractFromCss(css,".sIFR-root","kerning",true)||"";var _b4=_a6.gridFitType||_6b.extractFromCss(css,".sIFR-root","text-align")=="right"?"subpixel":"pixel";var _b5=_3b.forceTextTransform?_6b.extractFromCss(css,".sIFR-root","text-transform",true)||"none":"none";var _b6="";if(_ae){_6b.extractFromCss(css,".sIFR-root","text-align",true)}if(!_a6.modifyCss){_b6=_6b.cssToString(css)}var _b7=_a6.wmode||"";if(_b7=="transparent"){if(!ua.transparencySupport){_b7="opaque"}else{_b1="transparent"}}for(var i=0;i<_a9.length;i++){var _b9=_a9[i];if(!ua.verifiedKonqueror){if(dom.getComputedStyle(_b9,"lineHeight").match(/e\+08px/)){ua.supported=_3b.isEnabled=false;this.removeFlashClass();return}ua.verifiedKonqueror=true}if(dom.hasClass(_3d,_b9)||dom.hasClass(_3f,_b9)){continue}var _ba=false;if(!_b9.offsetHeight||!_b9.offsetWidth){if(!_3b.replaceNonDisplayed){continue}_b9.style.display="block";if(!_b9.offsetHeight||!_b9.offsetWidth){_b9.style.display="";continue}_ba=true}if(_ad&&ua.gecko){_b9.style.clear="both"}var _bb=null;if(_3b.fixWrap&&ua.ie&&dom.getComputedStyle(_b9,"display")=="block"){_bb=_b9.innerHTML;dom.setInnerHtml(_b9,"X")}var _bc=dom.getStyleAsInt(_b9,"width",ua.ie);if(ua.ie&&_bc==0){var _bd=dom.getStyleAsInt(_b9,"paddingRight",true);var _be=dom.getStyleAsInt(_b9,"paddingLeft",true);var _bf=dom.getStyleAsInt(_b9,"borderRightWidth",true);var _c0=dom.getStyleAsInt(_b9,"borderLeftWidth",true);_bc=_b9.offsetWidth-_be-_bd-_c0-_bf}if(_bb&&_3b.fixWrap&&ua.ie){dom.setInnerHtml(_b9,_bb)}var _c1,_c2;if(!ua.ie){_c1=dom.getStyleAsInt(_b9,"lineHeight");_c2=Math.floor(dom.getStyleAsInt(_b9,"height")/_c1)}else{if(ua.ie){var _bb=_b9.innerHTML;_b9.style.visibility="visible";_b9.style.overflow="visible";_b9.style.position="static";_b9.style.zoom="normal";_b9.style.writingMode="lr-tb";_b9.style.width=_b9.style.height="auto";_b9.style.maxWidth=_b9.style.maxHeight=_b9.style.styleFloat="none";var _c3=_b9;var _c4=_b9.currentStyle.hasLayout;if(_c4){dom.setInnerHtml(_b9,"<div class=\""+_42+"\">X<br />X<br />X</div>");_c3=_b9.firstChild}else{dom.setInnerHtml(_b9,"X<br />X<br />X")}var _c5=_c3.getClientRects();_c1=_c5[1].bottom-_c5[1].top;_c1=Math.ceil(_c1*0.8);if(_c4){dom.setInnerHtml(_b9,"<div class=\""+_42+"\">"+_bb+"</div>");_c3=_b9.firstChild}else{dom.setInnerHtml(_b9,_bb)}_c5=_c3.getClientRects();_c2=_c5.length;if(_c4){dom.setInnerHtml(_b9,_bb)}_b9.style.visibility=_b9.style.width=_b9.style.height=_b9.style.maxWidth=_b9.style.maxHeight=_b9.style.overflow=_b9.style.styleFloat=_b9.style.position=_b9.style.zoom=_b9.style.writingMode=""}}if(_ba){_b9.style.display=""}if(_ad&&ua.gecko){_b9.style.clear=""}_c1=Math.max(_44,_c1);_c1=Math.min(_45,_c1);if(isNaN(_c2)||!isFinite(_c2)){_c2=1}var _c6=Math.round(_c2*_c1);if(_c2>1&&_b0){_c6+=Math.round((_c2-1)*_b0)}var _c7=dom.create("span");_c7.className=_40;var _c8=_b9.cloneNode(true);for(var j=0,l=_c8.childNodes.length;j<l;j++){_c7.appendChild(_c8.childNodes[j].cloneNode(true))}if(_a6.modifyContent){_a6.modifyContent(_c8,_a6.selector)}if(_a6.modifyCss){_b6=_a6.modifyCss(css,_c8,_a6.selector)}var _cb=handleContent(_c8,_b5);if(_a6.modifyContentString){_cb=_a6.modifyContentString(_cb,_a6.selector)}if(_cb==""){continue}var _cc=["content="+_cb.replace(/\</g,"&lt;").replace(/>/g,"&gt;"),"width="+_bc,"height="+_c6,"fitexactly="+(_ae?"true":""),"tunewidth="+(_a6.tuneWidth||""),"tuneheight="+(_a6.tuneHeight||""),"offsetleft="+(_a6.offsetLeft||""),"offsettop="+(_a6.offsetTop||""),"thickness="+(_a6.thickness||""),"sharpness="+(_a6.sharpness||""),"kerning="+_b3,"gridfittype="+_b4,"zoomsupport="+ua.zoomSupport,"filters="+_ac,"opacity="+_b2,"blendmode="+(_a6.blendMode||""),"size="+_c1,"zoom="+dom.getZoom(),"css="+_b6];_cc=encodeURI(_cc.join("&amp;"));var _cd="sIFR_callback_"+_49++;var _ce={flashNode:null};window[_cd+"_DoFSCommand"]=(function(_cf){return function(_d0,arg){if(/(FSCommand\:)?resize/.test(_d0)){var $=arg.split(":");_cf.flashNode.setAttribute($[0],$[1]);if(ua.khtml){_cf.flashNode.innerHTML+=""}}}})(_ce);_c6=Math.round(_c2*getRatio(_c1)*_c1);var _d3=_af?_bc:"100%";var _d4;if(ua.ie){_d4=["<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" id=\"",_cd,"\" sifr=\"true\" width=\"",_d3,"\" height=\"",_c6,"\" class=\"",_3e,"\">","<param name=\"movie\" value=\"",src,"\"></param>","<param name=\"flashvars\" value=\"",_cc,"\"></param>","<param name=\"allowScriptAccess\" value=\"always\"></param>","<param name=\"quality\" value=\"best\"></param>","<param name=\"wmode\" value=\"",_b7,"\"></param>","<param name=\"bgcolor\" value=\"",_b1,"\"></param>","<param name=\"name\" value=\"",_cd,"\"></param>","</object>","<scr","ipt event=FSCommand(info,args) for=",_cd,">",_cd,"_DoFSCommand(info, args);","</","script>"].join("")}else{_d4=["<embed class=\"",_3e,"\" type=\"application/x-shockwave-flash\" src=\"",src,"\" quality=\"best\" flashvars=\"",_cc,"\" width=\"",_d3,"\" height=\"",_c6,"\" wmode=\"",_b7,"\" bgcolor=\"",_b1,"\" name=\"",_cd,"\" allowScriptAccess=\"always\" sifr=\"true\"></embed>"].join("")}dom.setInnerHtml(_b9,_d4);_ce.flashNode=_b9.firstChild;_b9.appendChild(_c7);dom.addClass(_3d,_b9);if(_a6.onReplacement){_a6.onReplacement(_ce.flashNode)}}_5f.fragmentIdentifier.restore()};function handleContent(_d5,_d6){var _d7=[],_d8=[];var _d9=_d5.childNodes;var i=0;while(i<_d9.length){var _db=_d9[i];if(_db.nodeType==3){var _dc=_6b.normalize(_db.nodeValue);_dc=_6b.textTransform(_d6,_dc);_d8.push(_dc.replace(/\%/g,"%25").replace(/\&/g,"%26").replace(/\,/g,"%2C").replace(/\+/g,"%2B"))}if(_db.nodeType==1){var _dd=[];var _de=_db.nodeName.toLowerCase();var _df=_db.className||"";if(/\s+/.test(_df)){if(_df.indexOf(_41)){_df=_df.match("(\\s|^)"+_41+"-([^\\s$]*)(\\s|$)")[2]}else{_df=_df.match(/^([^\s]+)/)[1]}}if(_df!=""){_dd.push("class=\""+_df+"\"")}if(_de=="a"){var _e0=_db.getAttribute("href")||"";var _e1=_db.getAttribute("target")||"";_dd.push("href=\""+_e0+"\"","target=\""+_e1+"\"")}_d8.push("<"+_de+(_dd.length>0?" ":"")+escape(_dd.join(" "))+">");if(_db.hasChildNodes()){_d7.push(i);i=0;_d9=_db.childNodes;continue}else{if(!/^(br|img)$/i.test(_db.nodeName)){_d8.push("</",_db.nodeName.toLowerCase(),">")}}}if(_d7.length>0&&!_db.nextSibling){do{i=_d7.pop();_d9=_db.parentNode.parentNode.childNodes;_db=_d9[i];if(_db){_d8.push("</",_db.nodeName.toLowerCase(),">")}}while(i<_d9.length&&_d7.length>0)}i++}return _d8.join("").replace(/\n|\r/g,"")}};
var helneu = {
  src: imghost + '/agbeta/sifr/helveticaneuelt_v3.swf'
};

sIFR.prefetch(helneu);
sIFR.activate();

function sifr_banner(){
    sIFR.replace(helneu, {
        selector: '#agi-category-banner h1'
        ,wmode: 'transparent'
        ,css: {
                '.sIFR-root': { 'color': '#ffffff', 'text-transform': 'lowercase' }
        }
    });
}

function sifr_bannerl3(){
    sIFR.replace(helneu, {
        selector: '#agi-category-banner h2'
        ,wmode: 'transparent'
        ,css: {
                '.sIFR-root': { 'color': '#ffffff', 'text-transform': 'lowercase' }
        }
    });
}

function sifr_ecardtitle(){
	sIFR.replace(helneu, {
		selector: '#agi-ecardtitle h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#000000', 'text-align': 'center', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_ecardtitlety(){
	sIFR.replace(helneu, {
		selector: '#agi-ecardtitlety h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#9d0017', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_ecardtitlel(){
	sIFR.replace(helneu, {
		selector: '#agi-ecardtitlel h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#9d0017', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_ecardtitleleft(){
	sIFR.replace(helneu, {
		selector: '#agi-ecardtitleleft h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#9d0017', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_ecardtitleleftsm(){
	sIFR.replace(helneu, {
		selector: '#agi-ecardtitleleftsm h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#9d0017', 'text-transform': 'lowercase' }
		}
	});
}


function sifr_ecardtitleleftsm2(){
	sIFR.replace(helneu, {
		selector: '#agi-ecardtitleleftsm2 h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#9d0017', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_othertitlety(){
	sIFR.replace(helneu, {
		selector: '#agi-othertitlety h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#9d0017', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_printabletitle(){
	sIFR.replace(helneu, {
		selector: '#agi-printabletitle h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#9d0017', 'text-align': 'center', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_invitetitle(){
	sIFR.replace(helneu, {
		selector: '#agi-invitetitle h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#9d0017', 'text-align': 'center', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_invitetitleleft(){
	sIFR.replace(helneu, {
		selector: '#agi-invitetitleleft h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#9d0017', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_invitetitlefl(){
	sIFR.replace(helneu, {
		selector: '#agi-invitetitlefl h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#9d0017', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_invitetitlefls(){
	sIFR.replace(helneu, {
		selector: '#agi-invitetitlefls h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#9d0017', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_dltitle(){
	sIFR.replace(helneu, {
		selector: '#agi-dltitle h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#9d0017', 'text-align': 'center', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_thumbsvlist(){
	sIFR.replace(helneu, {
		selector: '#agi-thumbs-vlist h2'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#b0ad89' }
		}
	});
}

function sifr_featuredcontent(){
	sIFR.replace(helneu, {
		selector: '#agi-featuredcontent h2'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#c73e30', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_printable(){
	sIFR.replace(helneu, {
		selector: '#agi-printable h2'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#aeab8d', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_printableproj(){
	sIFR.replace(helneu, {
		selector: '#agi-printableproj h2'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#aeab8d', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_myinvmain(){
	sIFR.replace(helneu, {
		selector: '#agi-myinvmain h2'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#aeab8d', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_instructions(){
	sIFR.replace(helneu, {
		selector: '#agi-instructions h2'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#aeab8d', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_rcolumn(){
	sIFR.replace(helneu, {
		selector: '#agi-rcolumn h2'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#aeab8d', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_lcolumn(){
	sIFR.replace(helneu, {
		selector: '#agi-lcolumn h2'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#aeab8d', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_headtitle(){
	sIFR.replace(helneu, {
		selector: '#headtitle h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#98936c', 'text-align': 'left', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_seohallow(){
	sIFR.replace(helneu, {
		selector: '#agi-seohallow #agi-seohead #headtitle h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#e55800', 'text-align': 'left', 'text-transform': 'lowercase' }
    	}
	});
}

function sifr_seobday(){
	sIFR.replace(helneu, {
		selector: '#agi-seobday #agi-seohead #headtitle h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#e92e37', 'text-align': 'left', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_seodisney(){
	sIFR.replace(helneu, {
		selector: '#agi-seodisney #agi-seohead #headtitle h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#333399', 'text-align': 'center', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_seothanks(){
	sIFR.replace(helneu, {
		selector: '#agi-seothanks #agi-seohead #headtitle h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#CC6633', 'text-align': 'left', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_seosweet(){
	sIFR.replace(helneu, {
		selector: '#agi-seosweet #agi-seohead #headtitle h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#CC3366', 'text-align': 'left', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_momcount(){
	sIFR.replace(helneu, {
		selector: '#momcount h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#ee353d', 'text-align': 'right', 'text-transform': 'lowercase', 'font-size': '24px' }
		}
	});
}


function sifr_agierrors(){
	sIFR.replace(helneu, {
		selector: '#agi-errors h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#ee353d', 'text-align': 'left', 'text-transform': 'lowercase', 'font-size': '24px' }
		}
	});
}

function sifr_mdtoc(){
	sIFR.replace(helneu, {
		selector: '#mdtoc h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#ee353d', 'text-align': 'left', 'text-transform': 'lowercase', 'font-size': '24px' }
		}
	});
}

function sifr_mdtoc2(){
	sIFR.replace(helneu, {
		selector: '#mdtoc h2'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#333333', 'text-transform': 'lowercase', 'font-size': '20px' }
		}
	});
}

function sifr_mompage(){
	sIFR.replace(helneu, {
		selector: '.momforward h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#ee353d', 'text-transform': 'lowercase', 'font-size': '20px', 'text-align': 'right' }
		}
	});
}

function sifr_mompage2(){
	sIFR.replace(helneu, {
		selector: '#momview #agi-content #momtexttop h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#ee353d', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_mompage3(){
	sIFR.replace(helneu, {
		selector: '#momview #agi-content .momtext h2'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#aeab8d', 'text-transform': 'lowercase', 'font-size': '24px' }
		}
	});
}

function sifr_choosemomcard(){
	sIFR.replace(helneu, {
		selector: '#mdchoose h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#ee353d', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_choosemomcard2(){
	sIFR.replace(helneu, {
		selector: '#mdchoose h2'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#484848', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_choosemomcard3(){
	sIFR.replace(helneu, {
		selector: '#mdchoose .momintrot h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#ee353d', 'text-transform': 'lowercase' }
		}
	});
}

function sifr_mompopup(){
	sIFR.replace(helneu, {
		selector: '#agi-flashAlbum-popUp h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#ee353d', 'text-transform': 'lowercase' }
		}
	});
}


function sifr_mompageview(){
	sIFR.replace(helneu, {
		selector: '#momviewpd .momreport h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#ee353d', 'text-transform': 'lowercase','text-align': 'right' }
		}
	});
}

function sifr_mompageview2(){
	sIFR.replace(helneu, {
		selector: '#momviewpd .momforward h1'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#ee353d', 'text-transform': 'lowercase','text-align': 'right' }
		}
	});
}

function sifr_mompageview3(){
	sIFR.replace(helneu, {
		selector: '#momviewpd .momviewtrib h2'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#ee353d', 'text-transform': 'lowercase','text-align': 'center' }
		}
	});
}

function sifr_momstep1(){
	sIFR.replace(helneu, {
		selector: '#mdcustom2 h2'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#808080', 'text-transform': 'lowercase','text-align': 'left' }
		}
	});
}

function sifr_mompreview(){
	sIFR.replace(helneu, {
		selector: '.agi-face-tribmsg'
		,wmode: 'transparent'
		,css: {
			'.sIFR-root': { 'color': '#ee353d', 'text-transform': 'lowercase','text-align': 'left' }
		}
	});
}
function SignIn(hidden_node_id, open_id, close_id, duration, cb_show, cb_hide) {
    var signintrigger = this;
    try {
        this.signin = document.getElementById(hidden_node_id);
        this.open_trigger = document.getElementById(open_id);
        this.close_trigger = document.getElementById(close_id);
    } catch(e) {
        this.signin = undefined;
        this.open_trigger = undefined;
        this.close_trigger = undefined;
    }
    duration ? this.duration = duration : this.duration = 400;
    this.cb_show = cb_show;
    this.cb_hide = cb_hide;

    this.show = function(e) {
        dojo.lfx.html.fadeShow(this.signin, this.duration, '', this.cb_show).play();
    }

    this.hide = function(e) {
        dojo.lfx.html.fadeHide(this.signin, this.duration, '', this.cb_hide).play();
    }

    if(this.signin && this.open_trigger) {
        dojo.event.connect(this.open_trigger,"onclick",function(e){signintrigger.show();});
    }
    if(this.signin && this.close_trigger) {
        dojo.event.connect(this.close_trigger,'onclick',function(e){signintrigger.hide();});
    }
}

function SignInLightbox(hidden_node_id, form_id) {
    var signintrigger = this;
    this.hidden_node_id = hidden_node_id;
    this.form_id = form_id;
    this.ff = undefined;

    this.show = function() {
        var markup = dojo.byId(signintrigger.hidden_node_id).innerHTML;
        markup = markup.replace('signin_magic',form_id);
        lightbox('', undefined, markup);
        signin_ff = new FocusForm(signintrigger.form_id);
        signintrigger.ff = new FocusForm(signintrigger.form_id);
        try { init_tempstorage(); } catch(e) {}
        return false;
    }

    this.hide = function() {
        if(signintrigger.ff) {
            signintrigger.ff.reset_form();
        }
        hideLightbox();
        return false;
    }
}

var blnDoPopAway = true;
var BLN_POPAWAY  = true;

var popURL  = '';
var popH    = 420;
var popW    = 500;
var popCN   = '';
var popCD   = 7;
var popPCT  = 100;
var popSCROLL  = 'yes';

function processOnUnload() {
  setTimeout("delay()",500);
  if(blnDoPopAway && BLN_POPAWAY)
  {
    popAway();
  }
}

function processOnClick() {
  setDoPopAway(false);
  setTimeout("delay()",500);
}

function setDoPopAway(blnValue) {
  blnDoPopAway = blnValue;
}

function delay() {
  return true;
}

function popAway(URL, height, width, cookiename, cookiedays, percentage, scroll) {
  if (URL)          { popURL = URL; }
  if (height)       { popH   = height; }
  if (width)        { popW   = width; }
  if (cookiename)   { popCN  = cookiename; }
  if (cookiedays!=undefined) { popCD  = cookiedays; }
  if (percentage)   { popPCT = percentage; }
  if (scroll)       { popSCROLL = scroll; }

  var randPCT = Math.round(Math.random() * 100);

  var strWinFeatures = "resizeable=yes,scrollbars="+popSCROLL+",width="+popW+",height="+popH;

  // only set the cookie and pop the window if we're in the right percent
  if (randPCT <= popPCT)
  {
    if (popCN) {
      var allcookies = document.cookie;
      var pos = allcookies.indexOf(popCN);
      var expires = '';

      // only pop the window if we don't see the cookie
      if (pos == -1) {
        if(popCD)
        {
            var SECONDS_PER_DAY   = 86400;
            var myMinTimeOut      = SECONDS_PER_DAY*popCD;
            var myDate            = new Date();
            myDate.setTime(myDate.getTime()+(myMinTimeOut*1000));
            expires = " expires="+myDate.toGMTString()+";";
        }
            document.cookie = popCN+"=true;"+expires+" path=/;";
        popAwayWin = window.open(popURL, "popaway", strWinFeatures);
      }
    } else {
      popAwayWin = window.open(popURL, "popaway", strWinFeatures);
    }
  }
  return;
}

function addPopAwayHandlers(URL, height, width, cookiename, cookiedays, percentage, scroll) {
  if (URL)          { popURL = URL; }
  if (height)       { popH   = height; }
  if (width)        { popW   = width; }
  if (cookiename)   { popCN  = cookiename; }
  if (cookiedays!=undefined) { popCD  = cookiedays; }
  if (percentage)   { popPCT = percentage; }
  if (scroll)       { popSCROLL = scroll; }

  var browser = navigator.appName;
  var strBrowser = "";

  if (browser == "Microsoft Internet Explorer") {
    strBrowser = "ie";
  }
  else if (browser == "Netscape") {
    strBrowser = "ns";
  }
  else if (browser == "Opera") {
    strBrowser = "op";
  }

  if(strBrowser=="ie") {
    document.onclick   = processOnClick;
    document.onkeydown = processOnClick;
    window.onunload    = processOnUnload;
  }
  else{
    try{
        window.captureEvents(Event.CLICK|Event.KEYDOWN|Event.UNLOAD);
    }
    catch(e){}
    try{
        window.onclick   = processOnClick;
        window.onkeydown = processOnClick;
        window.onunload  = processOnUnload;
    }
    catch(e){}
  }
}

//Check the URL of last visited page. If user came from a specific section,
//survey can be popped.
function checkReferrer(checkPath, URL, height, width, cookiename, cookiedays){
    if(document.referrer.indexOf(checkPath) != -1){
        popAway(URL, height, width, cookiename, cookiedays);
    }
}

/*
Given an elem that was clicked, the ID of a block to show/hide,
and optional class names:
    * change className of clicked_elem (on_class/off_class)
    * show/hide  elems[toggle_id]
*/
function toggle_block(clicked_elem, toggle_id, on_class, off_class) {
    if (on_class && off_class) {
        var _class = clicked_elem.className;
        if (_class == on_class) {
            dojo.html.removeClass(clicked_elem, on_class);
            dojo.html.addClass(clicked_elem, off_class);
        } else {
            dojo.html.removeClass(clicked_elem, off_class);
            dojo.html.addClass(clicked_elem, on_class);
        }
    }
    dojo.html.toggleDisplay(toggle_id);
}

function gotoVeepers()
{
  ckname = get_cookie_name("customer");
  email  = get_cookie_value(ckname, "email");
  status = get_cookie_value(ckname, "status");

  var location = window.location.href;
  if (location.indexOf('bluemountain') != -1)
  {
    url = "http://veepers.bluemountain.com/service/Start"
  }
  else if (location.indexOf('yahoo') != -1)
  {
    url = "http://agyahoo.stage.pulsemobile.com/service/Start"
  }
  else
  {
    url = "http://veepers.americangreetings.com/service/Start"
  }
  window.location.href = url + "?memstat=" + massage_status(status) + "&email=" + email;
}

function massage_status(status)
{
  switch(status)
  {
    case '1':
      return 'afu';
    case '3':
      return 'plat';
    case '5':
      return 'rfu';
    default:
      return 'afu';
  }
}

function gotoVeepersCustom(prodnum, path, bc, src, adisplay, va){
  var location = window.location;
  var isFirefox = (navigator.userAgent.indexOf( "Firefox/" ) != -1 );
  var intMakeYourOwn = 3085679;
  var yhlogin = "";

  if (parseInt(prodnum) == parseInt(intMakeYourOwn)){
     if (isFirefox){
        alert("This product requires Internet Explorer or Netscape");
        return;
     }
  }

  ckname = get_cookie_name("customer");
  email  = get_cookie_value(ckname, "email");
  status = get_cookie_value(ckname, "status");
  memnum  = get_cookie_value(ckname, "memnum");

  if (location.hostname.match(/bluemountain/i))
  {
    if (location.hostname.match(/dev/i) || location.hostname.match(/work/i) || location.hostname.match(/stage/i)){
       url = "http://bma.pulsedemo.com/service/Start";
    }
    else {
       url = "http://veepers.bluemountain.com/service/Start"
    }
  }
  else if (location.hostname.match(/yahoo/i))
  {
    yhname = get_cookie_value(ckname, "ynm");
    if (yhname.length > 1) { yhlogin = "&yhlogin=1";} else { yhlogin = "&yhlogin=0"; }
    if (location.hostname.match(/dev/i) || location.hostname.match(/work/i) || location.hostname.match(/stage/i)){
       url = "http://agyahoo.stage.pulsemobile.com/service/Start";
    }
    else {
       url = "http://veepers.yahoo.americangreetings.com/service/Start"
    }
  }
  else
  {
    if(location.hostname.match(/dev/i) || location.hostname.match(/work/i) || location.hostname.match(/stage/i))
    {
       url = "http://ag.pulsedemo.com/service/Start";
    }
    else
    {
        url = "http://talking.americangreetings.com/service/Start";
    }
  }
  // get server, account for page caching
  var ahost = "http://"+window.location.hostname.replace(/^(\D+)\d\./, "$1.");
  var vp_url = ahost+"/share/veepers_gateway.pd?info=";
  // set up querystring
  var vp_qs = url+"?memstat="+massage_status(status)+"&email="+email;
  vp_qs += "&path="+path+"&prodnum="+prodnum+'&bc='+bc+'&src='+src;
  vp_qs += "&adisplay="+adisplay+"&va="+va+yhlogin;
  // escape our url to veepers, stick in querystring
  vp_url += escape(vp_qs);
  // redirect to veepers_gateway.pd
  location.href = vp_url;
}

function gotoVeepersOutbox(prodnum, path, bc, src, delivdate){
  ckname = get_cookie_name("customer");
  email  = get_cookie_value(ckname, "email");
  status = get_cookie_value(ckname, "status");

  var location = window.location;
  if (location.hostname.match(/bluemountain/i))
  {
    if (location.hostname.match(/dev/i) || location.hostname.match(/work/i) || location.hostname.match(/stage/i)){
       url = "http://bma.pulsedemo.com/service/Start";
    }
    else {
       url = "http://veepers.bluemountain.com/service/Start"
    }
  }
  else if (location.hostname.match(/yahoo/i))
  {
    if (location.hostname.match(/dev/i) || location.hostname.match(/work/i) || location.hostname.match(/stage/i)){
       url = "http://agyahoo.stage.pulsemobile.com/service/Start";
    }
    else {
       url = "http://veepers.yahoo.americangreetings.com/service/Start"
    }
  }
  else
  {
    if(location.hostname.match(/dev/i) || location.hostname.match(/work/i) || location.hostname.match(/stage/i))
    {
       url = "http://ag.pulsedemo.com/service/Start";
    }
    else
    {
        url = "http://talking.americangreetings.com/service/Start";
    }
  }
  location.href = url + "?memstat=" + massage_status(status) + "&email=" + email + "&path=" + path + "&prodnum=" + prodnum + '&bc=' + bc + '&src=' + src + delivdate;
}

//if (!onupfunctions)
//  var onupfunctions = new Array();

//var old_on_up = document.onmouseup;

//document.onmouseup = function(e)
//{
//  for (var i = 0; i < onupfunctions.length; i++)
//    onupfunctions[i](e);
//  try {
//    old_on_up();
//  } catch (e) {}
//};

var scrollInterval;


//scroll the window to move a control into view
function scroll_into_view(control_id)
{
  var control = document.getElementById(control_id);
  var top = 0;
  var bottom = 0;
  var tmp = control;

  //Walk up the DOM and add up all of the offset positions.
  while (tmp.offsetParent && tmp.tagName.toUpperCase() != 'BODY')
  {
    //if (tmp.id != "lightbox")
      top += tmp.offsetTop;
    tmp = tmp.offsetParent;
  }
  top += tmp.offsetTop;
  bottom = control.clientHeight + top;
  var scroll_top = getScrollOffset().pageYOffset;
  var scroll_left = getScrollOffset().pageXOffset;

  var padding = Math.floor((getSize().height - control.clientHeight) / 2);

  var win_top = getLightboxTop();

  // if the entire control is visible, don't do anything
  if (scroll_top < top && bottom < getSize().height)
    return;

  // visible if scrolled to the top
  if ((bottom - win_top) < getSize().height)
    scrollTo(win_top);
  // if we can center the control
  else if (padding > 0)
    scrollTo(top - padding);
  // the top of the control isn't visible.
  else if (scroll_top > top)
    scrollTo(top);
}

// set the interval to scroll to a y position in 25 steps
function scrollTo(y)
{
  if (y > getMaximumScroll())
  	y = getMaximumScroll()
  step = Math.abs(getScrollOffset().pageYOffset - y) / 25;
  scrollInterval = setInterval("smoothScroll(" + step + "," + y + ")", 5);

}

// scroll page by step pixels until we reach dest_y
function smoothScroll(step, dest_y)
{
  var y_pos = getScrollOffset().pageYOffset;
  var new_y;
  if (y_pos > dest_y)
    new_y = Math.max(y_pos - step, dest_y);
  else
    new_y = Math.min(y_pos + step, dest_y);
  window.scroll(0, new_y);
  if (new_y == dest_y)
    clearInterval(scrollInterval);
}

// cross-browser method to get window size
function getSize() {
  var size = new Object();
  size.width = 0;
  size.height = 0;
  if( typeof( window.innerWidth ) == 'number' )
  {
    //Non-IE
    size.width = window.innerWidth;
    size.height = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    size.width = document.documentElement.clientWidth;
    size.height = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    size.width = document.body.clientWidth;
    size.height = document.body.clientHeight;
  }
  return size;
}

// cross-browser method to get window scroll offsets
function getScrollOffset()
{
  var offset = new Object();
  offset.pageYOffset = document.documentElement.scrollTop;
  offset.pageXOffset = document.documentElement.scrollLeft;
  return offset;
}

// cross-browser method to get window scroll offsets
function getElementScrollOffset(element_id)
{
  var elem = document.getElementById(element_id);

  var offset = new Object();
  if ( typeof(elem.pageYOffset) == 'number')
  {
    offset.pageYOffset = elem.pageYOffset;
    offset.pageXOffset = elem.pageXOffset;
  } else {
    offset.pageYOffset = elem.scrollTop;
    offset.pageXOffset =  elem.scrollLeft;
  }
  return offset;
}

function getMaximumScroll()
{
  var page_height = document.body.clientHeight;

  if (typeof( window.innerHeight ) == 'number')
  	var window_height = window.innerHeight
  else if (document.documentElement && document.documentElement.clientHeight)
    var window_height = document.documentElement.clientHeight;
  if (page_height > window_height)
  	return page_height - window_height;
  else
  	return 0;
}

function getLightboxTop()
{
  try {
    var tmp = document.getElementById("lightbox");
    var top = 0;

    if (tmp.style.display == "none")
      return 0;
    while (tmp.offsetParent && tmp.tagName.toUpperCase() != 'BODY')
    {
      top += tmp.offsetTop;
      tmp = tmp.offsetParent;
    }
    top += tmp.offsetTop;
    if (top > 10)
      return top - 10;
    else
      return top;
  } catch (e) {
    return 0;
  }
}

function getStyle(el,styleProp)
{
	var x = document.getElementById(el);
    var y;
	if (x.currentStyle)
		y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}

dojo.addOnLoad( function(){dojo.require("dojo.lfx.html");});
dojo.addOnLoad(find_wipers);

function get_image_prefix()
{
	if (ahost.indexOf("yahoo") > -1)
	{
		return "yh07";
	} else {
		return "agbeta";
	}
}

function set_navcookie(module_name, val){
   // 'lnav' is a magic cookie key
        // with composite values for all wipers

        var id = module_name;
        var magic = MagicCookie;
        //grab cookie, decode it
        var lnav = magic.getCookieValue('lnav');
        lnav = lnav ? Base64.decode(lnav) : '';
        //cookie not found, set value
        if(!lnav)
            lnav = id+'='+val;
        //cooke found, key not present. append value
        else if(lnav.indexOf(id)<0)
            lnav += '&'+id+'='+val;
        //key found, set appropriate value
        else
        {
            var rval = (val==0) ? '1' : '0';
            lnav = lnav.replace(id+'='+rval, id+'='+val);
        }
        //save cookie
        magic.setCookieValue('lnav',Base64.encode(lnav));

}
var wipers = [];
function find_wipers()
{
    //find all wipeable elements and init them
    var w = dojo.html.getElementsByClass('wipe',null,'div');
    for(var i=0; i<w.length; i++)
        new wiper(w[i]);
}

function wiper(node)
{
    var dw = this;
    this._container = node;
    this._anim = '';
    this._height = '';
    this._direction = '';
    //properties that can be overriden in wipe_parms
    this._time = 800;
    this._images = true;
    this._icons = {};
    this._open = false;
    this._dependent = false;
    this._cookie = true;
    this._wait = true;

    this.do_onload = function()
    {
        //set wipeable node
        this._node = dojo.html.getElementsByClass('wipe_block',this._container,'div')[0];
        this._node.style.overflow = 'hidden';
        //set trigger
        this._toggle = dojo.html.getElementsByClass('wipe_toggle',this._container)[0];
        if(this._toggle)
            this._toggle.onclick = function(){dw.do_wipe();};
        //parse optional parms
        var parms = dojo.html.getElementsByClass('wipe_parms',this._container,'input')[0];
        if(parms)
            this._parse_parms(parms.value);
        //push onto stack of overall wipers
        if(this._dependent)
            wipers.push(this);
        //preload toggle images
        this.preload();
        //set initial open/close state
        this._check_toggle();
    };

    this._parse_parms = function(values)
    {
        var parms = values.split(',');
        //parse optional parameters set in a special 'hidden'
        for(var i=0; i<parms.length; i++)
        {
            nvp = parms[i].split('=');
            if(nvp.length==2)
            {
                //prepend an '_' and assign the name-value-pair to our object
                eval('this._'+nvp[0]+'='+nvp[1]);
            }
        }
    };

    this.preload = function()
    {
        //preload the open/close images
        if(this._images)
        {
            var which = this._image_name ? this._image_name : this._node.id;
            var _open = new Image();
            _open.src = imghost+'/' + get_image_prefix() + '/left/'+which+'_open.gif';
            var _close = new Image();
            _close.src = imghost+'/' + get_image_prefix() +'/left/'+which+'_close.gif';
            this._icons.open = _open;
            this._icons.close = _close;
        }
    };

    this.do_wipe = function()
    {
        //if currently animating, do we have a height?
        var okay = this._check_status();
        if(!okay)
            return;
        //wipe close
        if(this._direction=='in')
            this._wipe_out();
        //wipe open
        else
            this._wipe_in();
        //close other dependent wipers
        this._toggle_others();
    };

    this._check_status = function()
    {
        //does wiper have animation object yet?
        if(this._anim)
        {
            //if animating, check for height
            if(this._anim.status() == 'playing')
            {
                //cannot reverse direction mid animation
                if(this._wait)
                    return false;
                //no height, return false
                if(!this._height)
                    return false;
                //stop animation
                this._stop_animation();
            }
        }
        //we have a height, animation has been stopped
        //return true
        return true;
    };

    this._wipe_in = function(instant)
    {
        this._direction = 'in';
        //if instant, immediately show node (don't animate)
        instant = instant==undefined ? false : instant;
        if(instant)
            dojo.html.show(this._node);
        //wipe open (animate)
        else
        {
            //save off node height, perform wipe
            this._set_height();
            this._anim = dojo.lfx.html.wipeIn(this._node,this._time,'','',this._height).play();
        }
        //change toggle image
        this._change_toggle('close');
        this.set_cookie(1);
    };

    this._wipe_out = function()
    {
        /*
        Save off node height
        wipe close the node
        change toggle image
        set cookie
        */
        this._direction = 'out';
        this._set_height();
        this._anim = dojo.lfx.html.wipeOut(this._node,this._time).play();
        this._change_toggle('open');
        this.set_cookie(0);
    };

    this._stop_animation = function()
    {
        // stop wiper's animation
        if(this._anim)
            this._anim.stop(false);
    };

    this._toggle_others = function()
    {
        //not in array of dependent wipers
        if(!dojo.lang.inArray(wipers, this))
            return;
        //grab index of this wiper
        var idx = dojo.lang.find(wipers, this);
        //loop through dependent wipers
        for(var i=0; i<wipers.length; i++)
        {
            //if not this wiper, close it
            if(i!=idx && wipers[i]._direction=='in')
            {
                wipers[i]._stop_animation();
                wipers[i]._wipe_out();
            }
        }
    };

    this._set_height = function()
    {
        if(!this._height)
        {
            var height;
            //temporarily show the node
            if(this._direction == 'in')
                dojo.html.show(this._node);
            //use height of the content box; accounts for any padding
            height = dojo.html.getContentBox(this._node).height;
            //hide the node; we now have the height
            if(this._direction == 'in')
                dojo.html.hide(this._node);
            //if calculated height is positive, save it
            if(height > 0)
            {
                this._height = height;
            }
        }
    };

    this.set_cookie = function(val)
    {
        //var id = this._node.id;
        set_navcookie(this._node.id, val);
    };

    this.get_cookie = function()
    {
        // 'lnav' is a magic cookie key
        // with composite values for all wipers

        //default to open if cookie not found
        var _default = this._open;
        var id = this._node.id;
        var magic = MagicCookie;
        //grab cookie, decode it
        var lnav = magic.getCookieValue('lnav');
        lnav = lnav ? Base64.decode(lnav) : '';
        //cookie not found, retun
        if(!lnav)
            return _default;
        var vals = lnav.split('&');
        //loop through the composite values
        for(var i=0; i<vals.length; i++)
        {
            //found value for this wiper
            if(vals[i].indexOf(id) > -1)
            {
                //break string into a usable NVP
                var nvp = vals[i].split('=');
                if(nvp.length !=2)
                    return _default;
                //return the value as an integer (represents open|close)
                return parseInt(nvp[1]);
            }
        }
        //our catch-all; return the default
        return _default;
    };

    this._change_toggle = function(which)
    {
        //toggle is text, not an image
        if(!this._images)
        {
            this._toggle.innerHTML = which;
            return;
        }
        //grab the toggle container, remove it's children
        var nodes = this._toggle.childNodes;
        for(var i=nodes.length-1; i>=0; i--)
            this._toggle.removeChild(nodes[i]);
        //build new toggle image
        var icon = this._icons[which];
        var width = icon.width ? icon.width : '';
        var height = icon.height ? icon.height : '';
        var toggle = make_node('img',
                {'src': this._icons[which].src,
                 'width': width,
                 'height': height,
                 'border': '0',
                 'title': which+' section',
                 'alt': which+' section'});
        //append image to toggle container
        this._toggle.appendChild(toggle);
    };

    this._check_toggle = function()
    {
        //grab cookie for this wiper
        var show = this.get_cookie();
        //set initial state to "open"
        if(show)
            this._wipe_in(true);
    }

    //get this show on the road!
    this.do_onload();
}

/**
*  Quickly show or hide navigation modules when the page loads.
*
*  This solves a timing problem where events wired via dojo need to wait
*  for dojo's onload to fire, which can take a while if there's a lot of stuff on the page.
*
*  The idea is that you call turbowipe() immediately (inline) after the navigation modules
*  appear on the page. Turbowipe will set the visibility of the various modules according
*  to the leftnav cookie values.
*/
function turbowipe(){
    var magic = MagicCookie;
    //grab cookie, decode it
    var lnav = magic.getCookieValue('lnav');
    lnav = lnav ? Base64.decode(lnav) : '';
    //cookie not found, retun
    if(!lnav){
        set_navcookie('occasions', 1);
        lnav="occasions=1";
    }
    var vals = lnav.split('&');
    //loop through the composite values
    for(var i=0; i<vals.length; i++){
        module_id = vals[ i ].split('=');
        var nvp = vals[ i ].split('=');
        if((nvp.length ==2) && (parseInt(nvp[ 1 ]) == 1)){
            e = document.getElementById(nvp[ 0 ]);
            if(e){
                e.style.display="block";
                toggle_img = document.getElementById(nvp[ 0 ] + "-toggle");
                toggle_img.src = imghost + '/' + get_image_prefix() +'/left/' + nvp[ 0 ] + "_close.gif";
                toggle_img.height = 30;
                toggle_img.width = 160;
                set_navcookie(nvp[ 0 ], 1);
            }
        }
    }
}

var preloaded = false;
var pl_contacts = new Object();
var groups_loaded = false;
var pl_groups = new Object();

var add_html = "";
function getCurrentTimeStamp()
{
	var date = new Date();
	return Date.UTC(date.getFullYear(), date.getMonth(), date.getDay(), date.getHours(), date.getMinutes(), date.getMilliseconds());
}

function wombat_storage_init(force_reload)
{
	dojo.require('dojo.storage.*');
	if(force_reload){
        WOMData.force_reload = true;
    }
    if (WOMData._initialized){
        if(force_reload)
        {
			WOMData.data = new WOMDataItem(WOMData.wid);
            preloaded = WOMData.data.loaded;
            pl_contacts = WOMData.data.contacts;
            WOMData._initialized = true;
            WOMData.force_reload = false;
        }
        WOMData.load();
    }
	else{
		dojo.event.connectOnce(WOMData, 'initialize', WOMData, "load");
    }
}

function WOMDataItem(wid) {
	this.wid = wid;
	this.contacts = new Object();
	this.loaded = false;
	this.groups = new Object();
	this.groups_loaded = false;
	this.last_updated = getCurrentTimeStamp();
}
var cache_wid = AGCookie.getCookieValue('customer','wid');

// demo IDs are - numbers so we replace them all with 'demo' for the key
// WOMData.initialize() is getting called twice by dojo.  Set a global var to keep track
// of whether we're already loading so that contactsearch.pd is not called twice as often
// as needed.
var contacts_loading = false;

var WOMData = {
	wid: (cache_wid > 0) ? cache_wid : 'demo',
	key: "womcache_" + ((cache_wid > 0) ? cache_wid : 'demo'),
	data: new WOMDataItem((cache_wid > 0) ? cache_wid : 'demo'),
	_initialized: false,
    force_reload: false,

	initialize: function(){
		this.data = dojo.storage.get(this.key);
		if (!this.data){
			this.data = new WOMDataItem(this.wid);
        }
		else if (getCurrentTimeStamp() > this.data.last_updated + 86400000){ // data has expired
			this.data = new WOMDataItem(this.wid);
        }
		else if (this.force_reload){
			this.data = new WOMDataItem(this.wid);
        }

		preloaded = this.data.loaded;
		pl_contacts = this.data.contacts;

		try {
			groups_loaded = this.data.groups_loaded;
			if (!groups_loaded)
				pl_groups = new Object();
			else
				pl_groups = this.data.groups;
		} catch(e) {
			groups_loaded = false;
			pl_groups = new Object();
		}

		if (preloaded)
		{
			try
			{
				if (contact_update)
					append_addresses(contact_update);
			} catch(e){}
			try
			{
				if (contact_delete)
					remove_addresses(contact_delete);
			} catch(e){}
		}
		this._initialized = true;
        this.force_reload = false;
	},

	load: function()
	{
		// if contacts are already loading, get out of here.
		if(contacts_loading)
        {
			return;
        }

		var wdl = new WombatDataLoader();
		wdl.load_address_data();
		contacts_loading = true;
	},

	store_contacts: function(contacts)
	{
		this.data.contacts = contacts;
		this.data.loaded = true;
		this.last_updated = getCurrentTimeStamp();
		try{
			dojo.storage.put(this.key, this.data, function(status, key, message){});
		}catch(exp){}
	},

	store_groups: function(groups)
	{
		this.data.groups = groups;
		this.data.groups_loaded = true;
		this.last_updated = getCurrentTimeStamp();
		try{
			dojo.storage.put(this.key, this.data, function(status, key, message){});
		}catch(exp){}
	}

}

if (dojo.storage.manager.isInitialized() == false)
{
	dojo.event.connect(dojo.storage.manager, "loaded", WOMData, WOMData.initialize);
} else {
	dojo.event.connect(dojo, "loaded", WOMData, WOMData.initialize);
}

function WombatDataLoader(on_complete)
{
	var _data_loader = this;
	this.swindow = 100;
	this.offset = 0;
	this.group_offset = 0;

	this.on_complete = on_complete;

	this.load_data = function()
	{
		this.load_add_page();
	};

	this.load_address_data = function()
	{
		if (!preloaded)
		{
			var new_window = _data_loader.swindow + 1
			var request = new Requester(ahost + '/reminders/contactsearch.pd', "POST", true, false);
			request.sendRequest("q=&o=" + _data_loader.offset + "&w=" + new_window);
			request.onsuccess = _data_loader.load_addresses;
			_data_loader.offset = _data_loader.offset + _data_loader.swindow;
		}
		if (!groups_loaded)
		{
			var new_window = _data_loader.swindow + 1
			var request = new Requester(ahost + '/reminders/groupsearch.pd', "POST", true, false);
			request.sendRequest("q=&o=" + _data_loader.group_offset + "&w=" + new_window);
			request.onsuccess = _data_loader.load_groups;
			_data_loader.group_offset = _data_loader.group_offset + _data_loader.swindow;
		}
	}

	this.load_addresses = function(req)
	{
		try {
			eval("var tmpArray = " + req.responseText);
		} catch (e) {
			// We've got an error.   Reset preloaded status
			preloaded = false;
			pl_contacts = new Object();
			return;
		}

		for (i = 0; i < tmpArray.length && i < _data_loader.swindow; i++)
		{
			var this_id = tmpArray[i].id
			pl_contacts[this_id] = tmpArray[i];
		}
		// if there are more, get more
		if (tmpArray.length > _data_loader.swindow)
		{
			_data_loader.load_address_data();
		} else {
			preloaded = true;
			try {
				WOMData.store_contacts(pl_contacts);
			} catch(e){};
		}
	}

	this.load_groups = function(req)
	{
		try {
			eval("var tmpArray = " + req.responseText);
		} catch (e) {
			// We've got an error.   Reset preloaded status
			groups_loaded = false;
			pl_groups = new Object();
			return;
		}

		for (i = 0; i < tmpArray.length && i < _data_loader.swindow; i++)
		{
			var this_id = tmpArray[i].id
			pl_groups[this_id] = tmpArray[i];
		}
		// if there are more, get more
		if (tmpArray.length > _data_loader.swindow)
		{
			_data_loader.load_address_data();
		} else {
			preloaded = true;
			try {
				WOMData.store_groups(pl_groups);
			} catch(e){};
		}
	}

	this.load_add_page = function()
	{
		var requester = new Requester("event_add.pd", 'GET', true, false);
		requester.onsuccess = function(request) {
			add_html = request.responseText;
			try {
				_data_loader.on_complete();
			} catch(e){};
		};
		requester.sendRequest("");
	};
}

function remove_addresses(contact_id)
{
	delete(pl_contacts[contact_id]);
	try {
		WOMData.store_contacts(pl_contacts);
	} catch(e){};
}

function append_addresses(contacts)
{
	for (i = 0; i < contacts.length; i++)
	{
		var this_id = contacts[i].id
		pl_contacts[this_id] = contacts[i];
	}
	try {
		WOMData.store_contacts(pl_contacts);
	} catch(e){};
}

function compare_contacts(a, b)
{
	if (!a.label)
		var a_name = a.last_name + a.first_name + a.email;
	else
		var a_name = a.label
	if (!b.label)
		var b_name = b.last_name + b.first_name + b.email;
	else
		var b_name = b.label

	if (a_name > b_name)
		return 1;
	else
		return -1;
}

function get_group_emails(group)
{
	var group_emails = "";
	for (i in group.contacts)
	{
		var contact_id = group.contacts[i]
		var email = pl_contacts[contact_id].email;
		if (email != null && email.length > 0)
			if (group_emails.length > 0)
				group_emails += ", " + email
			else
				group_emails += email;
	}
	return group_emails;
}

