/**
* add an event to an object
*
* @param object what to add the event to
* @param string event type (i.e. load, mouseover, keypress, etc)
* @param object function
* @return void
*/
function addEvent(obj, type, func)
{
    if (obj.addEventListener)
    {
        obj.addEventListener(type, func, true);
    }
    else if (obj.attachEvent)
    {
        var r = obj.attachEvent("on" + type, func);
    }
}

/**
* set a cookie
*
* @param string cookie name
* @param string cookie value
* @param string [optional] number of hours to expire
* @param string [optional] url path to restrict to
* @param string [optional] domain name to restrict to
* @param string [optional] whether to force SSL cookies or not
*/
function setCookie (sName, sValue)
{
    // test for optional parameters
    var bHours	= (arguments.length >= 3) ? true : false;
    var bPath	= (arguments.length >= 4) ? true : false;
    var bDomain	= (arguments.length >= 5) ? true : false;
    var bSecure	= (arguments.length >= 6) ? true : false;

    // if applicable, set optional parameters
    var sHours	= (bHours) ? arguments[2] : null;
    var sPath	= (bPath) ? arguments[3] : null;
    var sDomain	= (bDomain) ? arguments[4] : null;
    var sSecure	= (bSecure) ? arguments[5] : null;

    // set local variables
    var sDate	= null;
    var sCookie	= null;

    if(bHours)
    {
        if ( (typeof(sHours) == 'string') && Date.parse(sHours) )
        {
            // already a Date string
            sDate = sHours;
        }
        else if (typeof(sHours) == 'number')
        {
            // calculate Date from number of hours
            sDate = (new Date((new Date()).getTime() + sHours * 3600000)).toGMTString();
        }
    }

    // create the cookie string, adding any parameters that were specified
    sCookie = sName + '=' + escape(sValue);
    sCookie += ((sDate != null) ? (';expires=' + sDate) : '');
    sCookie += ((bPath) ? (';path=' + sPath) : '');
    sCookie += ((bDomain) ? (';domain=' + sDomain) : '');
    sCookie += ((bSecure) ? (';secure=' + sSecure) : '');

    // set the cookie
    document.cookie = sCookie;
}

/**
* read a cookie value
*
* @param string cookie name
* @return string cookie value (empty string if not found)
*/
function readCookie(sName)
{
    var sCookie = '' + document.cookie;
    var iFirstIndex = sCookie.indexOf(sName);

    if ((iFirstIndex == -1) || (sName == ''))
    {
        // there's no cookie, so go no further
        return('');
    }
    else
    {
        // there is a cookie and it does contain the name we're
        // looking for so get the value out and return it
        var iLastIndex = sCookie.indexOf(';', iFirstIndex);
        iLastIndex = (iLastIndex == -1) ? sCookie.length : iLastIndex;
        var sReturn = unescape(sCookie.substring(iFirstIndex + sName.length + 1, iLastIndex));
        return(sReturn);
    }
}

/**
* kill a cookie
*
* @param string cookie name
* @param string url path the cookie was restricted to
* @param string domain name the cookie was restricted to
*/
function killCookie(sName)
{
    // test for optional parameters
    var bPath	= (arguments.length >= 2) ? true : false;
    var bDomain	= (arguments.length >= 3) ? true : false;

    // if applicable, set optional parameters
    var sPath	= (bPath) ? arguments[1] : null;
    var sDomain	= (bDomain) ? arguments[2] : null;

    // We need the value to kill the cookie
    var sCookieValue = readCookie(sName);

    if(sCookieValue != '')
    {
        // create the already-expired cookie string, adding any parameters that were specified
        sCookie = sName + '=' + escape(sCookieValue);
        sCookie += ';expires=Fri, 13-Apr-1970 00:00:00 GMT';
        sCookie += ((bPath) ? (';path=' + sPath) : '');
        sCookie += ((bDomain) ? (';domain=' + sDomain) : '');

        // set the cookie
        document.cookie = sCookie;
    }
}


/**
* formats money into a presentable string
*
* @param string money value
* @return string formatted money string
*/
function formatMoney(s)
{
    if (s == "")
    {
        s = "0";
    }

    var p = s.indexOf(".");

    if (p < 0)
    {
        // No decimal present.
        s += ".00";
        p = s.indexOf(".");
    }

    if(p == 0)
    {
        // Decimal at position 0
        s = "0" + s;
        p = s.indexOf(".");
    }

    s += (p == s.length-1) ? "00" : (p == s.length-2) ? "0" : "";

    return "$" + s;
}

/**
* Update the color property of a style
*
* @param string the element id
* @param string the color value
*/
function swapColor(id, value)
{
    if (document.getElementById)
    {
        if (document.getElementById(id))
        {
            document.getElementById(id).style.color = value;
        }
    }
}

/**
* Swap out an image src property via the DOM (alias for swapSrc)
*
* @param string the element id of the image (not name)
* @param string the src property of the image
* @param string [optional] the alt property
*/
function swapImage(id, src)
{
    swapSrc(id, src);

    // the alt can be passed as well but is optional
    if (arguments.length > 2)
    {
        document.getElementById(id).setAttribute('alt', arguments[2]);
    }
}

/**
* Swap out the src property via the DOM
*
* @param string the element id of the image (not name)
* @param string the src property of the image
*/
function swapSrc(id, src)
{
    if (document.getElementById)
    {
        document.getElementById(id).setAttribute('src', src);
    }
}

/**
* Swap out an elements html code
*
* @param string the element id
* @param string the html code to swap in
*/
function swapHtml(id, html)
{
    if (document.getElementById)
    {
        if (document.getElementById(id))
        {
            document.getElementById(id).innerHTML = html;
        }
    }
}

/**
* hide an element by setting visibility to hidden
*
* @param string the element id
*/
function hideElement(id)
{
    if (document.getElementById)
    {
        if (document.getElementById(id))
        {
            document.getElementById(id).style.visibility = 'hidden';
        }
    }
}

/**
* show an element by setting visibility to visible
*
* @param string the element id
*/
function showElement(id)
{
    if (document.getElementById(id))
    {
        if (document.getElementById(id))
        {
            document.getElementById(id).style.visibility = 'visible';
        }
    }
}

/**
* hide an element by setting visibility to hidden
*
* @param string the element id
*/
function hideBlockElement(id)
{
    if (document.getElementById)
    {
        if (document.getElementById(id))
        {
            document.getElementById(id).style.display = 'none';
        }
    }
}

/**
* show an element by setting visibility to visible
*
* @param string the element id
*/
function showBlockElement(id)
{
    if (document.getElementById)
    {
        if (document.getElementById(id))
        {
            document.getElementById(id).style.visibility = 'block';
        }
    }
}

/**
* move an element to x, y coordinates
*
* @param string the element id
* @param string x position
* @param string y position
*/
function moveElement(id, x, y)
{
    if (document.getElementById(id))
    {
        document.getElementById(id).style.left = x + 'px';
        document.getElementById(id).style.top = y + 'px';
    }
}

/**
* Find all matching a element onmouseover and onmouseout properties and
* strip out the image sources for preloading (this function should be
* called from the onload event, never before)
*/
function autoPreload()
{
    if (document.getElementById)
    {
        var aPreloadOver = new Array();
        var aPreloadOut = new Array();
        var aLink = document.getElementsByTagName('a');

        for (var i = 0; i < aLink.length; i++)
        {
            if (aLink[i].getAttribute('onmouseover') && aLink[i].getAttribute('onmouseout'))
            {
                // find the correct mouseover calls
                var re = /^javascript:swapImage\(('|").*('|")(.*)('|")\);$/;

                // grab the mousover properties
                var sTempOver	= aLink[i].getAttribute('onmouseover');
                var sTempOut	= aLink[i].getAttribute('onmouseout');

                if (re.test(sTempOver) && re.test(sTempOut))
                {
                    // strip the properties down to nothing but the
                    // image that we're loading
                    var sOver	= sTempOver.replace(re, "$3");
                    var sOut	= sTempOut.replace(re, "$3");

                    // preload the over image
                    aPreloadOver[i] = new Image();
                    aPreloadOver[i].src = sOver;

                    // preload the out image
                    aPreloadOut[i] = new Image();
                    aPreloadOut[i].src = sOut;
                }
            }
        }
    }
}

/**
* a javascript collection object of all of the window popup options
*/
function popupOptions()
{
    this.height         = screen.availHeight / 2;
    this.width          = screen.availWidth / 2;
    this.top            = 0;
    this.left           = 0;
    this.toolbar        = false;
    this.location       = false;
    this.directories    = false;
    this.status         = false;
    this.menubar        = false;
    this.scrollbars     = false;
    this.resizable      = false;
    this.dependent      = false;

    this.build          = _buildOptions;
}

/**
* a private javascript method for popupOptions which is used
* to build a popup option string
*/
function _buildOptions()
{
    var sTemp = "";

    sTemp += "height=" + this.height + ",";
    sTemp += "width=" + this.width + ",";
    sTemp += "top=" + this.top + ",";
    sTemp += "left=" + this.left + ",";
    sTemp += "scrollbars=" + ((this.scrollbars) ? "yes" : "no") + ",";
    sTemp += "toolbar=" + ((this.toolbar) ? "yes" : "no") + ",";
    sTemp += "location=" + ((this.location) ? "yes" : "no") + ",";
    sTemp += "directories=" + ((this.directories) ? "yes" : "no") + ",";
    sTemp += "status=" + ((this.status) ? "yes" : "no") + ",";
    sTemp += "menubar=" + ((this.menubar) ? "yes" : "no") + ",";
    sTemp += "resizable=" + ((this.resizable) ? "yes" : "no") + ",";
    sTemp += "dependent=" + ((this.dependent) ? "yes" : "no");

    return(sTemp);
}

// used to track different window popups
var aWin = new Array();

/**
* creates a popup window
*
* @param string window url
* @param string window name
* @param string [optional] window width
* @param string [optional] window height
* @param boolean [optional] whether window is scrollable or not
* @param boolean [optional] whether window has a toolbar or not
* @param boolean [optional] whether window is resizable or not
*/
function popup(winlink, winname)
{
    // fix the winlink (if necessary)
    winlink = ((typeof(winlink) == "string") ? winlink : winlink.href);

    // initialize optional parameters
    var winwidth   	   = (arguments.length >= 3) ? arguments[2] : screen.availWidth / 2;
    var winheight      = (arguments.length >= 4) ? arguments[3] : screen.availWidth / 2;
    var winscroll      = (arguments.length >= 5) ? ((arguments[4] == '1') ? true : false) : false;
    var wintoolbar     = (arguments.length >= 6) ? ((arguments[5] == '1') ? true : false) : false;
    var winresize      = (arguments.length >= 7) ? ((arguments[6] == '1') ? true : false) : false;
    var winmenubar     = (arguments.length >= 8) ? ((arguments[7] == '1') ? true : false) : false;
    var winlocationbar = (arguments.length >= 9) ? ((arguments[8] == '1') ? true : false) : false;

    var oOption     = new popupOptions();

    oOption.width		= winwidth;
    oOption.height		= winheight;
    oOption.scrollbars	= winscroll;
    oOption.toolbar		= wintoolbar;
    oOption.resizable	= winresize;
    oOption.menubar		= winmenubar;
    oOption.location    = winlocationbar;

    // these values are hard coded
    oOption.top			= ((screen.availHeight / 2) - (winheight / 2));
    oOption.left		= ((screen.availWidth / 2) - (winwidth / 2));
    oOption.directories = false;
    oOption.status		= true;
    oOption.dependent	= false;

    var sOptions = oOption.build();

    // this is special to the bbw site, grab the location.href and make sure
    // that it's appended onto whatever query string we're opening so any
    // backward url calls can reference the correct url and navid (if applicable)
    winlink = winlink + ((winlink.indexOf("?") > 0) ? "&" : "?") + "opener=" + escape(location.href);

    // if you don't first check for the existence of the object then it gets
    // closed about the same time that it's getting opened below
    // I don't understand it but it happens on Mac OSX (both IE and Safari)
    // so just do the if check before attempting to close the popup
    if (aWin[winname])
    {
        if (aWin[winname] != null)
        {
            // this popup already exists so close it down
            // before continuing
            aWin[winname].close();
        }
    }

    // now open our popup window
    aWin[winname] = window.open(winlink, winname, sOptions);
    aWin[winname].focus();
}

document.onmousemove = getMousePosition;

if (!document.all) document.captureEvents(Event.MOUSEMOVE);

var _x = 0;
var _y = 0;

function getMousePosition(e)
{
    if (document.all)
    {
        // grab the x-y pos.s if browser is IE
        if (document.documentElement)
        {
            // this is IE6 specific
            _x = event.clientX + document.documentElement.scrollLeft;
            _y = event.clientY + document.documentElement.scrollTop;
        }
        else
        {
            _x = event.clientX + document.body.scrollLeft;
            _y = event.clientY + document.body.scrollTop;
        }
    }
    else
    {
        // grab the x-y pos.s if browser is NS
        _x = e.pageX;
        _y = e.pageY;
    }
    return true;
}

/**
* creates a dhtml popup window
*
* @param string url
* @param string width
* @param string height
*/
function localpopup(winlink, winwidth, winheight)
{
    // note: this function requires the following xhtml markup at then end of
    // the rendered page
    /*
    <div id="localpopupcontainer">
        <div id="localpopupheader"><a href="javascript:closelocalpopup();"><img src="/images/shoppinglist/confirm/btn_close.gif" width="53" height="14" alt="CLOSE"/></a></div>
        <div id="localpopupoutline"><iframe name="localpopupcontent" id="localpopupcontent" src="/images/spacer.gif" frameborder="0" scrolling="no"></iframe></div>
    </div>
    */

    // as long as we have a link to work with, load it up
    if (winlink != null)
    {
        // use the variables from sniffer.js to determine if we should use
        // the frame loader or dom loader
        if (is_mac && (is_safari || is_ie))
        {
            // some browsers may prefer to use the frame loading technique
            // (namely Mac IE) instead of the dom loading technique
            frames['localpopupcontent'].location.href = winlink;
        }
        else
        {
            // others prefer the standard compliant method of dom loading
            document.getElementById('localpopupcontent').src = winlink;
        }

        // set popup width
        document.getElementById('localpopupwrapper').style.width = winwidth + 'px';
        document.getElementById('localpopupheader').style.width = winwidth + 'px';
        document.getElementById('localpopupoutline').style.width = winwidth + 'px';

        // set popup height
        document.getElementById('localpopupwrapper').style.height = (winheight + 21) + 'px';
        document.getElementById('localpopupoutline').style.height = winheight + 'px';

        // force y position to be on screen if not already
        _y = (_y <= 0) ? 100 : _y;

        // move the window within the users view
        moveElement('localpopupcontainer', 0, _y);
    }
}

/**
* closes the dhtml popup window
*
* @param void
*/
function closelocalpopup()
{
    // move the popup off screen
    moveElement('localpopupcontainer', -2000, -2000);
}

// how many hours to keep our cookies alive for (30 days)
var iCookieHours = 30 * 24;

/**
* performs whatever is necessary after the page loads
*
* @param void
*/
function init()
{

    // do some moving around of the popup container (mostly to fix weirdness
    // on the mac)
    moveElement('localpopupcontainer', -2000, -2000);
    showElement('localpopupcontainer');

    // now alert mac ie users to the fact that we no longer "technically"
    // support their browser
    if (readCookie('browserwarning') != '1')
    {
        // use the variables from sniffer.js to determine whether this user
        // needs a browser warning or not
        if (bBrowserMac)
        {
            // we want to give mac users their own special warning
            localpopup('/macwarning.html', 350, 144);

            // once is enough for 30 days
            setCookie('browserwarning', '1', iCookieHours);
        }
        else if (bBrowserOther)
        {
            if (readCookie('suppresswarning') != '1')
            {
                // everyone gets the same warning (until they decide to
                // suppress it)
                localpopup('/browserwarning.html', 350, 260);

                // now that they've seen it we need to set a temporary
                // suppression cookie so they won't see it again until their
                // session expires (or they choose the suppress it and
                // overwrite this session cookie with a 30 day cookie
                setCookie('suppresswarning', '1', null);
            }
        }
        else
        {
            // this user didn't need to be warned so record it as a
            // successful warning so they won't be bothered again and
            // move along
            setCookie('browserwarning', '1', iCookieHours);
        }
    }

    /** preload the image rollover handled by domroll.css */
    rollSetup();
}

/**
* suppresses the browser warning popup for 30 days
*
* @param void
*/
function suppresswarning()
{
    setCookie('suppresswarning', '1', iCookieHours);
    localpopup('/suppresswarning.html', 350, 150);
}

/**
* just loads a url into a new window (unaltered window)
*
* @param string url
*/
function loadbrowser(winlink)
{
    window.open(winlink);
}

// if you don't call the onload init function it won't work (it's not auto)
window.onload = init;

