/* ##########################################################################
    Copyright 2005 BBB Systems, LLC, All rights reserved

    We don't mind if you learn from our scripts, or even use portions of
    them, but please be tactful and ethical.  If you find our scripts
    useful, let us know, we would like to hear from you.
    (www.bbbsystems.net has a contact form)

    AJAX Note:
    We got much of our information for fixing the broken back button here:
    http://www.contentwithstyle.co.uk/Articles/38/

########################################################################## */

var ajaxURL = window.location.href;

var skipInitObjects = false;

/*
var plusImg = new Image( );
plusImg.src = "/images/plus.gif";
var minusImg = new Image( );
minusImg.src = "/images/minus.gif";
*/
var sGlobals = new Object( );
sGlobals.bScrollAmount = 20;
sGlobals.slowScroll = 75;
sGlobals.fastScroll = 25;
sGlobals.isScrollingR = false;
sGlobals.isScrollingL = false;

var navHistory = new Array( );
var curNavPoint = -1;

var globals = new Array( );

var currentLocation = '';

var recursionCount = 0;//this is so we can better test recursive funtions.

var fieldLen = 0;//personalizedProduct

var bgzDDEnabled = true;

//format: html_id > type
var ajaxTabList = new Array( );

//don't forget to update the number in the loop
for(var i = 0; i < 1; i++){ ajaxTabList[i] = new Object( ); }
ajaxTabList[0].html_id = 'pageTabs';
ajaxTabList[0].ajax_type = 'page';

//detect safari
//In my opinion, safari isn't quit up to speed with the other modern browsers,
//although I hate to have safari hacks, I think it's a necessity in this
//application.  Hopefully they will patch most of their bugs in the future.
var is_safari = (document.childNodes)&&(!document.all)&&(!navigator.taintEnabled)&&(!navigator.accentColorName)?true:false;

if(imgRotatorThinking == undefined){
    var imgRotatorThinking = false;
}

window.js_initialized = false;

if(window.special_init){
    window.load_function = special_init;
}
else{
    window.load_function = function( ){ init( ); }
}
if(document.addEventListener){
    document.addEventListener('DOMContentLoaded', function( ){ window.load_function( ); }, false);
    document.addEventListener('load', function( ){ window.load_function( ); }, false);
}
else if(document.attachEvent){
    document.attachEvent('onreadystatechange', function( ){ window.load_function( ); });
}
else if(window.onload){
    window.onload = function( ){ window.load_function( ); }
}

if(window.load_maps && window.onunload){
    window.onunload = function( ){ GUnload( ); }
}

function init( ){
    if(window.js_initialized){ return; }
    window.js_initialized = true;
    if(!document.getElementsByTagName){
        return;//if it doesn't support this, it doesn't support a whole lot.
    }
    //force ie < 6 to fail (we can't support ie5 forever)
    document.getElementsByTagName("a")[0].style.cursor = 'pointer';

    if(window.ajaxEnabled){
        ajaxCheck( );
    }
    else{
        window.ajaxEnabled = false;
        window.b_xml = false;
    }
    if(window.limitedAjax != true){
        window.limitedAjax = false;
    }

    initTopMenuLinks( );
    initA( );
    initAppObjects( );
    valignProductImages( );
    fixPNGs( );

    if(!skipInitObjects){
        initObjects( );
    }

    appThink( );

    updateCardImg( );

    if(window.load_maps){
        loadGoogleMaps( );
    }

    if(!imgRotatorThinking){
        initImgRotator( );
    }

    editableEnabled = false;

    try{
        editorInit( );
    }
    catch(e){

    }
    if(window.ajaxEnabled && (window.isOldIE || window.isNewIE) && !document.getElementById('ieHistoryHack')){
        var ieHREF = window.location.href;
        ieHREF = ieHREF.replace(/^(http(s)?\:\/\/)([^\/]+)/, '');
        ieHREF = ieHREF.replace(/(\/\#)/, '');
        var ifrm = document.createElement('iframe');
        ifrm.name = 'ieHistoryHack';
        ifrm.id = 'ieHistoryHack';
        ifrm.src = '/iehack.php?' + ieHREF.replace(/^(\/\#)/, '');
        document.body.appendChild(ifrm);
    }

    if(window.load_cufon){ loadCufonFonts( ); }
    if(window.load_colorbox){ initColorBox( ); }
}

function xmlInit( ){
    initA( );
    initAppObjects( );
    if(!skipInitObjects){
        initObjects( );
    }

    if(!imgRotatorThinking){
        initImgRotator( );
    }

    initAjaxTabs( );
    valignProductImages( );
    fixPNGs( );


    if(window.load_maps){
        loadGoogleMaps( );
    }

    editableEnabled = false;
    try{
        editorInit( );
    }
    catch(e){

    }

    if(window.load_cufon){ loadCufonFonts( ); }
    if(window.load_colorbox){ initColorBox( ); }
}

function initA( ){
    if(document.getElementsByTagName){
        var as = document.getElementsByTagName("a");
        for(var i = 0; i < as.length; i++){

            if(as[i].parentNode.id != ''){
                if(as[i].parentNode.id == 'bLeftArrow' || as[i].parentNode.id == 'bRightArrow'){
                    as[i].onclick = function( ){
                        return false;
                    }
                    continue;
                }
            }

            var hostnm = as[i].href.replace(/http(s)?\:\/\//, "");
            hostnm = hostnm.replace(/\/.*/, "");

            if((hostnm != window.location.hostname && hostnm != '') || as[i].href.match(/\/ad\.\php\?/) || as[i].href.match(/\.pdf/i)){
                as[i].target = "_blank";
                continue;
            }

            if(window.ajaxEnabled && as[i].className != "noAJAX" && !as[i].href.match(/\/members\//) && !as[i].href.match(/feed\.php/)){
                if(b_xml){
                    if( as[i].href.match(/(#)$/) ){
                        continue;
                    }

                    if(as[i].href.match(/#\w+/)){
                        continue;
                    }

                    if(!as[i].href || as[i].href == ''){
                        continue;
                    }

                    as[i].onclick = function( ){
                        if(this.href.match(/\.pdf/)){
                            pdfPopup = window.open(this.href, "PDF");
                            pdfPopup.focus( );
                            return false;
                        }

                        //alert(b_xml.isCurrentRequest);
                        if(b_xml.isCurrentRequest){
                            return false;
                        }

                        /*var curWinLoc = window.location;
                        var curLoc = '';
                        if(window.location.match(/\#\w+/)){
                            alert(curWinLoc);
                            var curLocA = curWinLoc.split("#");
                            if(curLocA.length > 1){
                                curLoc = curLocA[1];
                            }
                            alert(curLoc);
                        }*/

                        //we need the protocol

                        hostnm = window.location.hostname;

                        var newHREF = this.href;
                        var backup_href = this.href;

                        //is this tmenu? set this to cur then set all others to nothing
                        if(this.parentNode.parentNode.parentNode.parentNode.id == 'tmenu'){
                            tmenu_obj = document.getElementById('tmenu');
                            tmenu_as = tmenu_obj.getElementsByTagName('a');
                            tmenu_as_len = tmenu_as.length;
                            for(i = 0; i < tmenu_as_len; i++){
                                t_a = tmenu_as[i];
                                t_a.className = '';
                            }
                            if(!this.className.match(' cur')){
                                this.className = this.className + ' cur';
                            }
                        }

                        newHREF = newHREF.replace(/^(http(s)?\:\/\/)([^\/]+)/, '');
                        newHREF = newHREF.replace(/(\/\#)/, '');
                        newHREF = newHREF.replace(/([\&\?]*refer\=.*)$/, '');
                        //double slashes kill the caller
                        newHREF = newHREF.replace(/^\/+/, '/');


                        this.href = '/#' + newHREF;

                        if((window.isNewIE || window.isOldIE) && document.getElementById('ieHistoryHack') && newHREF.match(/^(\/)/) ){
                        //if( (window.isNewIE || window.isOldIE) && document.getElementById('ieHistoryHack')){
                            //add the anchor for our happy ie hack
                            ieHistoryHack.src = '/iehack.php?' + newHREF.replace(/^(\/\#)/, '');
                            ieHistoryHack.window.location = ieHistoryHack.src;
                        }

                        currentLocation = newHREF;

                        if(newHREF.match(/\?/)){
                            newHREF += "&xmlOnly=1";
                        }
                        else{
                            newHREF += "?xmlOnly=1";
                        }

                        var tHREF = window.location.href.replace(/^(http(s)?\:\/\/)([^\/]+)/, '');

                        //if(tHREF.match(/^\/\#/)){
                            /*if(this.href != window.location.href){
                                imgRotatorThinking = false;
                            }*/
                            //imgRotatorThinking = false;
                            b_xml.request(newHREF);
                        //}

                        document.getElementById('content').scrollTop = 0;

                        if(b_xml.isSupported){
                            return true;
                        }

                        return true;
                    }
                }
            }
        }//end for a

        if(window.ajaxEnabled){
            if(!b_xml){
                return;
            }

            var prodCatTabs = document.getElementById('prodCatTabs');
            if(prodCatTabs){
                i = 0;
                as = prodCatTabs.getElementsByTagName("a");
                for(i = 0; i < as.length; i++){
                    as[i].onclick = function( ){
                        if(b_xml.isCurrentRequest){ return false; }
                        //ul = a->li->ul (this->parent->parent)
                        var ul = this.parentNode.parentNode;
                        var p_as = ul.getElementsByTagName('a');

                        for(var j = 0; j < p_as.length; j++){ p_as[j].className = ''; }
                        this.className = 'cur';
                        var newHREF = this.href;
                        newHREF = newHREF.replace(/(\#.*)$/, '');
                        newHREF = newHREF.replace(/(\/content\/)/, '/ajax.php/');
                        newHREF = newHREF + '/type/prodcattabs';
                        //alert(newHREF);
                        b_xml.request(newHREF);
                        if(b_xml.isSupported){ return false; }
                        return true;
                    }//end onclick
                }//end foreach a in prodCatTabs
            }

            var bb_cart_tabs = document.getElementById('bb_cart_tabs');
            if(bb_cart_tabs){
                i = 0;
                as = bb_cart_tabs.getElementsByTagName("a");
                for(i = 0; i < as.length; i++){
                    as[i].onclick = function( ){
                        if(b_xml.isCurrentRequest){ return false; }
                        //ul = a->li->ul (this->parent->parent)
                        var ul = this.parentNode.parentNode;
                        var p_as = ul.getElementsByTagName('a');

                        for(var j = 0; j < p_as.length; j++){ p_as[j].className = ''; }
                        this.className = 'cur';
                        var newHREF = this.href;
                        newHREF = newHREF.replace(/(\#.*)$/, '');
                        newHREF = newHREF.replace(/(\/content\/)/, '/ajax.php/');
                        //if(window.location.hostname.match(/\/members\//)){
                            newHREF = newHREF.replace(/\/p\/\d+/, '');
                        //}
                        newHREF = newHREF + '/type/bbcarttabs';
                        //alert(newHREF);
                        b_xml.request(newHREF);
                        if(b_xml.isSupported){ return false; }
                        return true;
                    }//end onclick
                }//end foreach a in productsBlockTabs
            }

            var member_tools_tabs = document.getElementById('member_tools_tabs');
            if(member_tools_tabs){
                i = 0;
                as = member_tools_tabs.getElementsByTagName("a");
                for(i = 0; i < as.length; i++){
                    as[i].onclick = function( ){
                        if(b_xml.isCurrentRequest){ return false; }
                        //ul = a->li->ul (this->parent->parent)
                        var ul = this.parentNode.parentNode;
                        var p_as = ul.getElementsByTagName('a');

                        for(var j = 0; j < p_as.length; j++){ p_as[j].className = ''; }
                        this.className = 'cur';
                        var newHREF = this.href;
                        newHREF = newHREF.replace(/(\#.*)$/, '');
                        newHREF = newHREF.replace(/(\/members\/)/, '/members/ajax.php/');
                        newHREF = newHREF + '&type=mtoolstabs';
                        //alert(newHREF);
                        b_xml.request(newHREF);
                        if(b_xml.isSupported){ return false; }
                        return true;
                    }//end onclick
                }//end foreach a in productsBlockTabs
            }

            var prodContentTabs = document.getElementById('prodContentTabs');
            if(prodContentTabs){
                i = 0;
                as = prodContentTabs.getElementsByTagName("a");
                for(i = 0; i < as.length; i++){
                    as[i].onclick = function( ){
                        if(b_xml.isCurrentRequest){ return false; }
                        //ul = a->li->ul (this->parent->parent)
                        var ul = this.parentNode.parentNode;
                        var p_as = ul.getElementsByTagName('a');

                        for(var j = 0; j < p_as.length; j++){ p_as[j].className = ''; }
                        this.className = 'cur';
                        var newHREF = this.href;
                        newHREF = newHREF.replace(/(\#.*)$/, '');
                        newHREF = newHREF.replace(/(\/content\/)/, '/ajax.php/');
                        newHREF = newHREF + '/type/pctabs';
                        //alert(newHREF);
                        b_xml.request(newHREF);
                        if(b_xml.isSupported){ return false; }
                        return true;
                    }//end onclick
                }//end foreach a in prodContentTabs
            }
        }
    }
    var bbb = document.getElementById('bbb');
    if(bbb){
        bbb.innerHTML = '<a href="http://www.bbbsystems.com/" target="_blank">Custom Software Development: BBB Systems, LLC</a>';
    }
}

function initAjaxTabs( ){
    var html_id;
    var ajax_type;
    var hObj = null;

    for(var cnt = 0; cnt < ajaxTabList.length; cnt++){

        html_id = ajaxTabList[cnt].html_id;
        ajax_type = ajaxTabList[cnt].ajax_type;

        hObj = document.getElementById(html_id);

        if(hObj){
            i = 0;
            as = hObj.getElementsByTagName("a");
            for(i = 0; i < as.length; i++){
                as[i].parent_class = as[i].parentNode.className;

                as[i].ajax_type = ajax_type;
                as[i].onclick = function( ){
                    if(this.ajax_type == 'dir' && window.is_ie && this.innerHTML == 'Reviews'){
                        return true;
                    }

                    if(b_xml.isCurrentRequest){ return false; }
                    //ul = a->li->ul (this->parent->parent)
                    //table = a->td->tr->table (this->parent->parent-parent)
                    var table = this.parentNode.parentNode;
                    var p_as = table.getElementsByTagName('a');

                    for(var j = 0; j < p_as.length; j++){ p_as[j].className = ''; p_as[j].parentNode.className = 'page_tab_c'; }
                    this.className = 'a_cur';
                    this.parentNode.className = this.parent_class + ' li_cur';
                    var newHREF = this.href;
                    newHREF = newHREF.replace(/(\#.*)$/, '');
                    newHREF = newHREF.replace(/(\/content\/)/, '/ajax.php/');
                    newHREF = newHREF + '/type/' + this.ajax_type;
                    //alert('here');
                    //alert(newHREF);

                    b_xml.request(newHREF);

                    if(b_xml.isSupported){ return false; }

                    return true;
                }//end onclick

                as[i].onmouseover = function( ){
                    this.parentNode.className = this.parent_class + ' li_cur';
                }
                as[i].onmouseout = function( ){
                    if(this.className != 'a_cur'){
                        this.parentNode.className = this.parent_class;
                    }
                }
            }//end foreach a in homeArticlesMenu
        }

    }//end for each ajaxTabList
}

function initAjaxContentA( ){
    var tc_obj = document.getElementById('pageTabContent');
    if(tc_obj && b_xml){
        tc_as = tc_obj.getElementsByTagName('a');
        as_length = tc_as.length;
        for(var i = 0; i < as_length; i++){
            t_href = tc_as[i].href;
            if(t_href.match(/tab_index\//)){
                var parent_class = tc_as[i].parentNode.className;
                tc_as[i].onclick = function( ){
                    //check to see if classes need updated on tabs
                    pt_obj = document.getElementById('pageTabs');
                    var p_as = pt_obj.getElementsByTagName('a');

                    stripped_href = this.href.replace('#page_tabs', '');
                    for(var j = 0; j < p_as.length; j++){

                        if(p_as[j].href == stripped_href){
                            p_as[j].className = 'a_cur';
                            p_as[j].parentNode.className = parent_class + ' li_cur';
                        }
                        else{
                            p_as[j].className = '';
                            p_as[j].parentNode.className = 'page_tab_c';
                        }
                    }

                    //move to anchor
                    window.location.hash = 'page_tabs';

                    //update content
                    var newHREF = this.href;
                    newHREF = newHREF.replace(/(\#.*)$/, '');
                    newHREF = newHREF.replace(/(\/content\/)/, '/ajax.php/');
                    newHREF = newHREF + '/type/page';

                    b_xml.request(newHREF);

                    if(b_xml.isSupported){ return false; }

                    return true;
                }
            }
        }
    }
}

function initProductPackage( ){
    var content = document.getElementById('content');
    var ppc = document.getElementById('productPackageContainer');
    var p_info = document.getElementById('ppkg_price_info');
    if(!ppc){
        if(p_info){
            p_info.parentNode.removeChild(p_info);
        }
        return;
    }

    if(!p_info){
        p_info = document.createElement('div');
        p_info.id = 'ppkg_price_info';

        var p_div = document.createElement('div');

        var p_span1 = document.createElement('span');
        p_span1.innerHTML = 'Current Package Price: $';
        p_span1.id = 'ppkg_price_text';

        var p_strong = document.createElement('strong');
        p_strong.innerHTML = '0.00';
        p_strong.id = 'ppkg_price_value';

        var p_input = document.createElement('input');
        p_input.id = 'ppkg_price_submit';
        p_input.className = 'button';
        p_input.type = 'submit';
        p_input.name = 'b_submit';
        p_input.value = 'Add Package to Cart';
        p_input.style.marginLeft = '12px'

        if(window.dlgi){
            var w_input = document.createElement('input');
            w_input.id = 'ppkg_price_submit_wishlist';
            w_input.className = 'button';
            w_input.type = 'submit';
            w_input.name = 'b_submit';
            w_input.value = 'Add Package to Wishlist';
            w_input.style.marginLeft = '12px'
        }
        else{
            var w_input = document.createElement('span');
            w_input.style.marginLeft = '12px';
            w_input.innerHTML = '<a href="#" onclick="openLoginForm( ); return false;">Login to add to wishlist</a>';
        }

        p_div.appendChild(p_span1);
        p_div.appendChild(p_strong);
        p_div.appendChild(w_input);
        p_div.appendChild(p_input);
        p_info.appendChild(p_div);
        content.parentNode.appendChild(p_info);

        p_input.onclick = function( ){
            submitProductPackage(1);
        }
        if(window.dlgi){
            w_input.onclick = function( ){
                submitProductPackage(2);
            }
        }
    }

    if(content.clientWidth){
        p_info.style.width = content.clientWidth + 'px';
    }
    else if(content.offsetWidth){
        p_info.style.width = content.offsetWidth + 'px';
    }

    var bquotes = ppc.getElementsByTagName('blockquote');

    for(var i = 0; i < bquotes.length; i++){
        var bq = bquotes[i];

        var divs = bq.getElementsByTagName('div');
        for(var j = 0; j < divs.length; j++){
            var div = divs[j];

            if(div.className == 'pkg_product_container'){
                var input = div.getElementsByTagName('input')[0];

                input.onclick = function(e){
                    if(this.checked){
                        var pnode = this.parentNode.parentNode;
                        var divs = pnode.getElementsByTagName('div');

                        var pid = this.id.replace(/^.*\_(\d+)$/, "$1");

                        for(var cnt = 0; cnt < divs.length; cnt++){
                            var div = divs[cnt];
                            var re = new RegExp("product_option_container_\\d+_" + pid);
                            if(div.id.match(re)){
                                div.style.display = 'block';
                            }
                            else if(div.className == 'product_option_container'){
                                div.style.display = 'none';
                            }
                        }
                    }
                }
            }
            else if(div.className == 'product_option_container'){
                div.style.display = 'none';
            }
        }
    }

    updateProductPackage(false);

    ppc.onclick = function( ){
        updateProductPackage(false);
    }
}

function submitProductPackage(p_type){
    var frm = document.getElementById('product_package_form');
    var pp_action = document.getElementById('product_package_action');

    if(updateProductPackage(true)){
        var p_action = 'add_to_cart';
        if(p_type == 2){
            p_action = 'add_to_wishlist';
        }
        pp_action.value = p_action;

        frm.submit( );
    }
}

function updateProductPackage(displayErrors){
    var ppc = document.getElementById('productPackageContainer');
    var ppkg_price_value = document.getElementById('ppkg_price_value');

    var p_options_valid = false;
    var groups_valid = false;

    var errors = new Array( );

    //check the product options
    var poptContainer = document.getElementById('productOptionsContainer');
    var trs = poptContainer.getElementsByTagName('tr');
    var tr;

    var curOption = 0;
    var curOptionRequired = 0;
    var curOptionName = '';
    var curOptionChecked = false;
    var curOptionDeps = new Array( );
    var curOptionPrice = 0;

    var base_price = parseFloat(document.getElementById('product_pkg_base_price').innerHTML);
    var totalPrice = base_price;

    var i = 0;
    for(i = 0; i < trs.length; i++){
        tr = trs[i];

        if(tr.id != '' && tr.className != ''){
            if(curOption > 0 && curOptionRequired == 1 && !curOptionChecked){
                errors.push(curOptionName + ' is required');
            }

            curOption = parseInt(tr.id.replace(/^poption\_/, ''));
            curOptionRequired = parseInt(tr.className.replace(/^.*\_(\d+)$/, "$1"));
            curOptionName = tr.getElementsByTagName('td')[1].innerHTML;
            curOptionName = curOptionName.replace(/\s+\<span.*$/i, '');
            curOptionChecked = false;
            continue;
        }

        var input = tr.getElementsByTagName('input')[0];
        if(input.checked){
            curOptionChecked = true;
            curOptionPrice = parseFloat(document.getElementById('pkg_item_price_' + input.value).innerHTML);
            totalPrice += curOptionPrice;

        }

    }
    if(curOption > 0 && curOptionRequired == 1 && !curOptionChecked){
        errors.push(curOptionName + ' is required');
    }

    //check the groups
    var divs = ppc.getElementsByTagName('div');
    var div;

    var optIdToName = new Array( );
    var depList = new Array( );
    var optChecked = new Array( );
    var optValues = new Array( );

    var hasOptions = false;

    curOption = 0;
    curOptionRequired = 0;
    curOptionName = '';
    curOptionChecked = false;
    curOptionDeps = new Array( );

    for(i = 0; i < divs.length; i++){
        div = divs[i];

        if(div.className == 'product_option_div'){
            if(div.id && div.id.match(/\_1$/)){
                var pnode = div.parentNode.parentNode;
                var pinput = pnode.getElementsByTagName('input')[0];

                if(pinput.checked){
                    var h5 = div.getElementsByTagName('h5')[0];
                    var po_name = h5.innerHTML;

                    var inputs = div.getElementsByTagName('input');
                    var chk = false;
                    for(var j = 0; j < inputs.length; j++){
                        if(inputs[j].checked){

                            var opt_price_span = document.getElementById('option_item_price_' + curOption + '_' + inputs[j].value);
                            if(opt_price_span){
                                var opt_price = parseFloat(opt_price_span.innerHTML);
                                if(opt_price != NaN){
                                    totalPrice += opt_price;
                                }
                            }

                            chk = true;
                        }
                    }
                    if(!chk){
                        errors.push(curOptionName + " requires You to select a " + po_name);
                    }
                }
            }
            continue;
        }

        if(!div.id || !div.id.match(/^pkg\_grp\_[\d]+$/)){ continue; }

        if(curOption > 0 && !curOptionChecked && hasOptions){
            errors.push(curOptionName + ' must be selected');
        }
        optChecked[curOption + ""] = curOptionChecked;

        curOption = div.id.replace(/^pkg\_grp\_([\d]+)$/, "$1");
        curOptionDeps = div.className.replace(/deps\_/, "").split(/\-/);
        curOptionName = document.getElementById('pkg_grp_name_' + curOption).innerHTML;
        curOptionRequired = parseInt(document.getElementById('pkg_grp_required_' + curOption).value);
        curOptionChecked = false;
        hasOptions = false;
        optIdToName[curOption + ""] = curOptionName;

        if(curOptionDeps.length > 0 && curOptionDeps[0] > 0){
            depList[curOption + ""] = curOptionDeps;
        }

        optValues[curOption + ""] = 0;
        var inputs = div.getElementsByTagName('input');
        for(var j = 0; j < inputs.length; j++){
            var input = inputs[j];
            if(input.type != 'radio'){ continue; }

            hasOptions = true;

            if(input.checked){
                curOptionChecked = true;
                optValues[curOption + ""] = input.value;
                //pkg_grp_inp_3_23521
                var opt_price_span = document.getElementById('pkg_grp_item_price_' + curOption + '_' + input.value);
                if(opt_price_span){
                    var opt_price = parseFloat(opt_price_span.innerHTML);
                    if(opt_price != NaN){
                        totalPrice += opt_price;
                    }
                }
                break;
            }
        }

        //if(curOptionDeps.length > 0 && curOptionDeps[0] > 0){
        //    alert(curOption + ' - ' + curOptionDeps + ' - ' + curOptionName + ' - ' + curOptionRequired);
        //}

    }
    if(curOption > 0 && !curOptionChecked && hasOptions){
        errors.push(curOptionName + ' is required');
    }
    optChecked[curOption + ""] = curOptionChecked;

    //find the dependencies
    for(i in depList){
        var dep = depList[i];
        for(var j = 0; j < dep.length; j++){
            var gid = dep[j];
            if( (!optChecked[gid] && optValues[i] != 0) || (optValues[gid] == 0 && optValues[i] != 0) ){
                errors.push(optIdToName[i] + ' requires ' + optIdToName[gid]);
            }
        }
    }

    //update the price
    ppkg_price_value.innerHTML = totalPrice.toFixed(2);

    //alert the errors
    if(errors.length > 0 && displayErrors){
        var error_str = '';
        for(i = 0; i < errors.length; i++){
            error_str += "* " + errors[i] + "\n";
        }
        alert(error_str);
    }

    if(errors.length > 0){
        return false;
    }
    return true;
}

function productPkgHelp(group_id){
    var group_t = document.getElementById('pkg_grp_name_' + group_id);
    var group_h = document.getElementById('pkg_help_content_' + group_id);

    if(group_h.style.display == 'block'){
        group_h.style.display = 'none';
    }
    else{
        group_h.style.top = group_t.offsetTop + 'px';
        group_h.style.display = 'block';
    }
}



function initObjects( ){
    var objects = document.getElementsByTagName("div");
    var len = objects.length;

    var tLoc = window.location.href;

    var prot = 'http';
    if(document.all && tLoc.match(/^https/)){
        prot = 'https';
    }

    for(var i = 0; i < len; i++){
        var obj = objects[i];
        if(obj.className && obj.className == 'bgzobject'){
            var paramStr = '';
            var objStr = '\n<object ';
            var embedStr = '\n<embed ';
            var params = obj.getElementsByTagName('param');
            var plen = params.length;
            var o_type = '';
            var o_filename = '';
            var o_width = '';
            var o_height = '';
            //need o_type, it will be first or second in the list, but just in case.
            for(j = 0; j < plen; j++){
                var param = params[j];
                var pn = param.name;
                var pv = param.value;
                if(pn == 'o_type'){
                    o_type = pv;

                    //do this here because we have to force video type for wmv files
                    var isWindows = false;
                    //if( o_type != 'wmv' && !document.all){
                    //     isWindows = false;
                    //}else if(o_type == 'wmv' || navigator.userAgent.match(/windows/i)){
                    if(o_type == 'wmv' || navigator.userAgent.match(/windows/i)){
                        isWindows = true;
                    }

                    break;
                }
            }
            for(j = 0; j < plen; j++){
                var param = params[j];
                var pn = param.name;
                var pv = param.value;

                switch(pn){
                case 'o_type':
                    if(o_type == 'swf'){
                        embedStr += ' type="application/x-shockwave-flash" ';
                        objStr += ' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
                        objStr += ' codebase="' + prot + '://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" ';
                    }
                    else if(isWindows && o_type != 'mov'){

                        embedStr += ' type="application/x-mplayer2" ';
                        embedStr += '  pluginspage="' + prot + '://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/" ';
                        objStr += ' classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95" ';
                        objStr += ' standby="Loading..." ';
                        objStr += ' type="application/x-oleobject" ';
                        objStr += ' codebase="' + prot + '://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,5,715" ';
                    }
                    else{
                        embedStr += ' pluginspage="' + prot + '://www.apple.com/quicktime/download/" ';
                        objStr += ' classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" ';
                        objStr += ' codebase="' + prot + '://www.apple.com/qtactivex/qtplugin.cab" ';
                    }
                    break;
                case 'o_filename':
                    o_filename = pv;
                    if(o_type == 'swf'){
                        paramStr += ' <param name="movie" value="/docs/' + pv + '" /> \n';
                    }
                    else if(isWindows && o_type != 'mov'){
                        paramStr += ' <param name="filename" value="/docs/' + pv + '" /> \n';
                    }
                    else{
                        paramStr += ' <param name="src" value="/docs/' + pv + '" /> \n';
                    }
                    embedStr += ' src="/docs/' + pv + '" ';

                    break;
                case 'o_width':
                    o_width = pv;
                    obj.width = pv;
                    embedStr += ' width="' + pv + '" ';
                    objStr += ' width="' + pv + '" ';
                    break;
                case 'o_height':
                    o_height = pv;
                    obj.height = pv;
                    embedStr += ' height="' + pv + '" ';
                    objStr += ' height="' + pv + '" ';
                    break;
                default:
                    pn = pn.replace(/^(o\_)/, '');

                    if(!isWindows && pn == 'showcontrols'){
                        pn = 'controller';
                    }

                    if(pn == 'transparency'){
                        pn = 'wmode';
                        pv = 'transparent';

                        if(document.all){
                            //for some reason flash transparency is screwing up on this site,
                            //if we ever figure it out, delete this code
                            //seems to work now *shrug* - hobbit
                            //continue;
                        }
                    }

                    paramStr += ' <param name="' + pn + '" value="' + pv + '" /> ';

                    if(pv.toLowerCase( ) == 'false'){
                        pv = '0';
                    }
                    else if(pv.toLowerCase( ) == 'true'){
                        pv = '1';
                    }

                    if(pn == 'showcontrols'){
                        if(pv == '0'){
                            paramStr += ' <param name="ShowStatusBar" value="false" /> \n';
                            embedStr += ' showstatusbar="0" ';
                        }
                        else{
                            paramStr += ' <param name="ShowStatusBar" value="true" /> \n';
                            embedStr += ' showstatusbar="1" ';
                        }
                    }

                    embedStr += ' ' + pn + '="' + pv + '" ';


                    break;
                }
            }//end params

            embedStr += '></embed>\n';
            objStr += '>\n';
            //alert(objStr + paramStr + embedStr + '</object>');

            obj.innerHTML = objStr + paramStr + embedStr + '</object>\n';
            obj.style.display = 'block';

            obj.className = 'bgzobject_loaded';

        }//end if bgzobject
    }//end foreach object

}

function bScrollLeft( ){
    if(sGlobals.isScrollingL){
        bottomBaseScroll(-1 * sGlobals.bScrollAmount);
        setTimeout('bScrollLeft( );', sGlobals.scrollTime);
    }
}

function bScrollRight( ){
    if(sGlobals.isScrollingR){
        bottomBaseScroll(sGlobals.bScrollAmount);
        setTimeout('bScrollRight( );', sGlobals.scrollTime);
    }
}

function initAppObjects( ){
    var bBaseGallery = document.getElementById('bBaseGallery');
    var bbc = document.getElementById('bottomBase');

    if(!bbc){
        return;
    }

    var clientW = bbc.clientWidth;
    var scrollW = bbc.scrollWidth;
    var i;

    if(curNavPoint < 0){
        curNavPoint = 0;

        var newHREF = window.location.href;
        if(newHREF.match(/\?/)){
            newHREF += "&xmlOnly=1";
        }
        else{
            newHREF += "?xmlOnly=1";
        }

        navHistory.push(newHREF);
    }

    if(bBaseGallery && bBaseGallery.clientWidth < bbc.scrollWidth){
        if(document.all){
            bBaseGallery.style.width = parseInt(bbc.scrollWidth + 32) + "px";
        }
        else{
            bBaseGallery.style.width = parseInt(bbc.scrollWidth) + "px";
        }
    }
    else if(bBaseGallery){
        bBaseGallery.style.width = "auto";
    }

    var bLeftArrow = document.getElementById('bLeftArrow');
    var bRightArrow = document.getElementById('bRightArrow');

    if(document.addEventListener){
        bbc.addEventListener('DOMMouseScroll', captureScroll, false);
    }
    //else{
        //make opera happy, it lies about addEventListener!
        bbc.onmousewheel = captureScroll;
    //}


    bLeftArrow.onmouseover = function( ){
        sGlobals.isScrollingL = true;
        sGlobals.scrollTime = sGlobals.slowScroll;
        bScrollLeft( );
    }
    bLeftArrow.onmouseout = function( ){
        sGlobals.isScrollingL = false;
        sGlobals.scrollTime = sGlobals.slowScroll;
    }
    bLeftArrow.onmousedown = function( ){
        if(is_safari){
            return false;
        }
        sGlobals.isScrollingL = true;
        sGlobals.scrollTime = sGlobals.fastScroll;
    }
    bLeftArrow.onmouseup = function( ){
        if(is_safari){
            return false;
        }
        sGlobals.isScrollingL = true;
        sGlobals.scrollTime = sGlobals.slowScroll;
        return false;
    }
    bLeftArrow.onclick = function( ){ return false }


    bRightArrow.onmouseover = function( ){
        sGlobals.isScrollingR = true;
        sGlobals.scrollTime = sGlobals.slowScroll;
        bScrollRight( );
    }
    bRightArrow.onmouseout = function( ){
        sGlobals.isScrollingR = false;
        sGlobals.scrollTime = sGlobals.slowScroll;
    }
    bRightArrow.onmousedown = function( ){
        if(is_safari){
            return false;
        }
        sGlobals.isScrollingR = true;
        sGlobals.scrollTime = sGlobals.fastScroll;
    }
    bRightArrow.onmouseup = function( ){
        if(is_safari){
            return false;
        }

        sGlobals.isScrollingR = true;
        sGlobals.scrollTime = sGlobals.slowScroll;
        return false;
    }
    bRightArrow.onclick = function( ){ return false }


    //gallery caption box, onclick/contextmenu on the image will open it, click x will close it
    var gDisplayCloseBox = document.getElementById('gDisplayCloseBox');
    var gDisplayImage = document.getElementById('gDisplayImage');

    var gDisplayImageCaption = document.getElementById('gDisplayImageCaption');

    if(gDisplayImageCaption && gDisplayCloseBox && gDisplayImage){

        gDisplayImageCaption.style.opacity = '.65';
        if(document.all){
            gDisplayImageCaption.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=65)";
        }

        gDisplayImage.onclick = function( ){
            globals['dImageDir'] = 1;
            captionBoxRun( );
            return false;
        }
        gDisplayCloseBox.onclick = function( ){
            globals['dImageDir'] = -1;
            captionBoxRun( );
            return false;
        }
    }

    var navBack = document.getElementById('navBack');
    var navForward = document.getElementById('navForward');
    if(navBack && navForward && navHistory){
        if(curNavPoint == 0){ navBack.className = "navBackDisabled"; }
        else{ navBack.className = "navBack"; }

        if(curNavPoint == navHistory.length - 1){ navForward.className = "navForwardDisabled"; }
        else{ navForward.className = "navForward"; }
    }

    //init the thumbnails in bottom base
    var aS = bbc.getElementsByTagName('a');
    var span1, span2, span3;

    for(i = 0; i < aS.length; i++){
        span1 = document.createElement('span');
        span1.className = 'tpMiddle';
        span2 = document.createElement('span');
        span2.className = 'tpLeft';
        span3 = document.createElement('span');
        span3.className = 'tpRight';

        if(document.insertAdjacentElement){
            aS[i].insertAdjacentElement("beforeEnd", span1);
            aS[i].insertAdjacentElement("beforeEnd", span2);
            aS[i].insertAdjacentElement("beforeEnd", span3);
        }
        else{
            aS[i].appendChild(span1);
            aS[i].appendChild(span2);
            aS[i].appendChild(span3);
        }
    }

}

function captionBoxRun( ){
    var gDisplayImageCaption = document.getElementById('gDisplayImageCaption');
    var alpha = parseInt(gDisplayImageCaption.style.opacity * 100)

    if(alpha > 0 && globals['dImageDir'] < 0){
        var newAlpha = alpha - 5;
        gDisplayImageCaption.style.opacity = (newAlpha)/100;

        if(document.all){
            gDisplayImageCaption.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + newAlpha + ")";
        }
        setTimeout('captionBoxRun( )', 50);
    }
    else if(alpha < 65 && globals['dImageDir'] > 0){
        var newAlpha = alpha + 5;
        gDisplayImageCaption.style.opacity = (newAlpha)/100;

         gDisplayImageCaption.style.display = 'block';

        if(document.all){
            gDisplayImageCaption.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + newAlpha + ")";
        }
        setTimeout('captionBoxRun( )', 50);
    }
    else if(alpha <= 0){
        gDisplayImageCaption.style.display = 'none';
    }
}

function initImgRotator( ){
    var jsIR = document.getElementById('jsImgRotate');
    if(!jsIR || !imgRotatorA){
        return;
    }

    jsIR.innerHTML = "";
    jsIR.curImg = -1;
    jsIR.lastImg = null;

    for(var i = 0; i < imgRotatorA.length; i++){
        var iObj = imgRotatorA[i];
        var gid = iObj.gid;
        var imgName = iObj.imgName;
        var pid = iObj.pid;
        var fullImg = iObj.fullImg;

        var img = document.createElement('img');

        img.srcStr = imgName;
        img.src = "/uimages/" + imgName

        img.gid = gid;
        img.pid = pid;
        img.fullImg = fullImg;

        img.className = 'noAJAX';

        jsIR.appendChild(img);

        if(img.complete == null){
            //safari needs to fix these little issues.
            img.complete = true;
            img.style.width = "290px";
            img.style.height = "200px";
        }

        img.style.opacity = 0;
        if(document.all){
            img.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=0)";
        }

        img.onclick = function( ){
            var anch = this.srcStr.replace(/\./, "_");

            var gHREF = "/content/?gid=" + this.gid + "&img=" + this.fullImg;

            if(window.ajaxEnabled){
                gHREF += "&xmlOnly=1";
                b_xml.request(gHREF);
            }
            else{
                window.location = gHREF;
            }
        }
    }

    if(!imgRotatorThinking){
        imgRotatorThinking = true;
        imgRotatorThink( );
    }
}

function imgRotatorThink( ){
    var jsIR = document.getElementById('jsImgRotate');

    if(!jsIR || !imgRotatorA){
        return;
    }

    //alert("cur" + jsIR.curImg);
    //alert("last" + jsIR.lastImg);
    //alert(jsIR.innerHTML);
    if(jsIR.curImg >= 0){
        jsIR.lastImg = jsIR.curImg;
    }
    jsIR.curImg++;
    if(jsIR.curImg >= imgRotatorA.length){
        jsIR.curImg = 0;
    }

    var jsImages = jsIR.getElementsByTagName('img');
    var curImgObj = jsImages[jsIR.curImg];

    if(!curImgObj){
        return;
    }

    if(curImgObj.complete){
        curImgObj.style.opacity = 0;
        if(document.all){
            curImgObj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=0)";
        }
        curImgObj.style.visibility = 'visible';
        //alert('initchange');
        imgRotatorChange( );
    }
    else{
       imgRotatorWait( );
    }
}

function imgRotatorChange( ){
    var jsIR = document.getElementById('jsImgRotate');
    if(!jsIR || jsIR == null){
        return;
    }

    var jsImages = jsIR.getElementsByTagName('img');

    if(jsIR.curImg < 0){
        jsIR.curImg = 0;
    }

    var curImgObj = jsImages[jsIR.curImg];
    var lastImgObj = null;

    if(!curImgObj){
        return;
    }

    if(jsIR.lastImg >= 0){
        lastImgObj = jsImages[jsIR.lastImg];
    }

    var alphaInc = 5;
    var speed = 80;

    var curAlpha = parseInt(curImgObj.style.opacity * 100);
    var newAlpha = curAlpha + alphaInc;

    if(newAlpha >= 100){
        newAlpha = 100;
    }

    curImgObj.style.opacity = newAlpha / 100;

    if(document.all){
        curImgObj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + newAlpha + ")";
    }

    if(lastImgObj){
        var lastAlpha = parseInt(lastImgObj.style.opacity * 100);
        var newLastAlpha = lastAlpha - alphaInc;

        if(lastAlpha <= 0){
            newLastAlpha = 0;
            lastImgObj.style.visibility = "hidden";
        }
        lastImgObj.style.opacity = newLastAlpha / 100;
        if(document.all){
            lastImgObj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + newLastAlpha + ")";
        }
    }

    if(newAlpha >= 100){
        if(lastImgObj){
            lastImgObj.style.visibility = "hidden";
        }
        //alert('think');
        imgRotatorThinking = true;
        setTimeout('imgRotatorThink( )', 3000);
    }
    else{
        setTimeout('imgRotatorChange( )', speed);
    }
}
function imgRotatorWait( ){
    var jsIR = document.getElementById('jsImgRotate');
    var jsImages = jsIR.getElementsByTagName('img');
    var curImgObj = jsImages[jsIR.curImg];
    var lastImgObj = jsImages[jsIR.lastImg];

    if(!curImgObj){
       return;
    }

    if(curImgObj.complete){
        curImgObj.style.opacity = 0;
        if(document.all){
            curImgObj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=0)";
        }
        curImgObj.style.visibility = 'visible';

        imgRotatorChange( );
    }
    else{
       setTimeout('imgRotatorWait( )', 50);
    }
}


function appThink( ){
    if(document.getElementById('bottomBaseContainer')){
        var bbc = document.getElementById('bottomBase');

        var bLeftArrow = document.getElementById('bLeftArrow');
        var bRightArrow = document.getElementById('bRightArrow');

        //alert(bbc.offsetWidth);
        //alert(bbc.clientWidth);
        //alert(bbc.scrollWidth);
//*
        if(bbc.clientWidth < bbc.scrollWidth && bRightArrow.style.display != 'block'){
            bLeftArrow.style.display = "block";
            bRightArrow.style.display = "block";

            bLeftArrow.style.opacity = 1;
            bRightArrow.style.opacity = 1;
        }
        else if(bbc.clientWidth >= bbc.scrollWidth){
            bLeftArrow.style.display = "none";
            bRightArrow.style.display = "none";
            bbc.scrollLeft = 0;
        }
        else if(bbc.scrollWidth < bbc.scrollLeft){
            bbc.scrollLeft = 0;
        }

        //else if(bbc.style.left != "0px"){
        //    bbc.style.left = "0px";
        //}
// */
    }

//from here down is all specificly ajax stuff

if(window.ajaxEnabled && !window.limitedAjax){

    var newHREF = window.location.href;

    //the big ieHack, this is sick, don't try this at home
    var didIE = false;
    var windowHREF = newHREF;//another piece of the ie hack
    //and the all new Safari hack, w00t

    if((window.isNewIE || window.isOldIE) && (windowHREF.match(/(\/#\/)/) || windowHREF.match(/\#/)) && document.getElementById('ieHistoryHack')){
        if(ieHistoryHack && ieHistoryHack.document && ieHistoryHack.document.body && ieHistoryHack.document.body.innerHTML != ''){
            windowHREF = windowHREF.replace(/^(http(s)?\:\/\/)([^\/]+)/, '');
            windowHREF = windowHREF.replace(/(\/\#\/)/, '');

            //if(ieHistoryHack.document.body.innerHTML != '/'){
                newHREF = ieHistoryHack.document.body.innerHTML;

                //alert(ieHistoryHack.document.body.innerHTML);
                //alert(document.getElementById('ieHistoryHack').contentWindow.document.body.innerHTML);
                didIE = true;
            //}
        }
    }

    newHREF = newHREF.replace(/^(http(s)?\:\/\/)([^\/]+)/, '');

    var tHREF = newHREF;

    newHREF = newHREF.replace(/(\/\#)/, '');

if(window.ActiveXObject){
/*
    //debug information... pick an id, any id (it beats infinite alerts).
    var tvar = newHREF + ' - ' + currentLocation + '<br />hash: ' + window.location.hash + '<br />location: ' + window.location + '<br />doc-location:' + document.location;
    tvar += '<br />------(' + tHREF + ')--------<br />';
    tvar += '<br />' + window.history.length + '<br />';
    document.getElementById('bbb_debug').innerHTML = tvar;
// */
}
    //alert(newHREF);


    //if(newHREF != '' && ( tHREF.match(/^\/#/) || tHREF == '/' || currentLocation == '' || currentLocation != newHREF ) ){
    //if(newHREF != '' && tHREF.match(/^\/#\//) && ( tHREF.match(/^\/#/) || tHREF == '/' || currentLocation == '' || currentLocation != newHREF) ){
    if(newHREF != '' && ( tHREF.match(/^(\/#\/)/) || tHREF == '/' || currentLocation == '' || (currentLocation != newHREF && tHREF.match(/^(\/#\/)/)) ) ){

        //if(recursionCount < 5){
        //    alert(newHREF + ' - ' + currentLocation + ' - ' + windowHREF);
        //    recursionCount++;
        //}

        //alert(newHREF + ' - ' + currentLocation + ' - ' + windowHREF);
        //check to see if the location has changed
        if(newHREF != currentLocation && !b_xml.isCurrentRequest && window.location.protocol.toLowerCase( ) != 'https'){
            if(window.ActiveXObject && didIE){

                //update the location in the address bar to complete the ie hack
                var ieURL = '/';
                if(newHREF != windowHREF){
                    ieURL = '/#' + newHREF;
                    if(newHREF == '/'){
                        window.location.href = '/';
                    }
                    else{
                        window.location.href = ieURL;
                    }
                }
            }

            currentLocation = newHREF;
            //if(recursionCount < 5){
            //    alert(newHREF + ' - ' + currentLocation + ' - ' + windowHREF);
            //    recursionCount++;
            //}


            if(newHREF.match(/\?/)){
                newHREF += "&xmlOnly=1";
            }
            else{
                newHREF += "?xmlOnly=1";
            }

            b_xml.request(newHREF);
        }
    }
}//End if window.ajaxEnabled

    //make the program think every 10th of a second
    setTimeout('appThink( )', 100);
}

//bottomBase scroll (-n goes left, +n goes right)
//(to the user it's the other way around -1 pushes <---, 1 pushes ---->)
function bottomBaseScroll(direction){

    var bbc = document.getElementById('bottomBase');
    var clientW = bbc.clientWidth;
    var scrollW = bbc.scrollWidth;
    var currentPos = bbc.scrollLeft;


    if(isNaN(currentPos)){
        currentPos = 0;
    }

    var newPos = currentPos;

    if(direction > 0){
        if(currentPos + direction > (scrollW - clientW)){
            newPos = scrollW - clientW;
        }
        else{
            newPos += direction;
        }
    }
    else if(direction < 0){
        if(scrollW + direction < 0){
            newPos = 0;
        }
        else{
            newPos += direction;
        }
    }

    bbc.scrollLeft = newPos;
}

function captureScroll(e){
    //alert(e.detail);
    if(!e){
        e = window.event;
    }
    //alert(e.wheelDelta);
    if(e.wheelDelta){
        var direction = e.wheelDelta / 40;
        if(!window.opera){
            direction = -1 * direction;
        }
    }
    else if(e.detail){
        var direction = e.detail;
    }
    //alert(direction);

    if(direction < 0){
        bottomBaseScroll(-1 * sGlobals.bScrollAmount * 2);
    }
    else{
        bottomBaseScroll(sGlobals.bScrollAmount * 2);
    }

    if(window.event){
        e.returnValue = true;
        e.cancelBubble = true;
    }
    else{
        e.stopPropagation( );
        e.preventDefault( );
    }
}

//Cool input effects
function inputOver(e){
    this.className = "buttonOver";
}

function inputOut(e){
    this.className = "button";
}

//Popups
function generalPopUp(loc, w, h){
    gPopUp = window.open(loc, "gpopup", "width=" + w + ",height=" + h + ", scrollbars=0, status=no,toolbar=no,resizable=yes");
    gPopUp.focus( );
}
function generalPopUp2(loc, w, h){
    gPopUp = window.open(loc, "gpopup", "width=" + w + ",height=" + h + ", scrollbars=1, status=no,toolbar=no,resizable=yes,menubar=yes");
    gPopUp.focus( );
}

function imageSelectPopUp(pwinvar){
    imgSelectPopUp = window.open("./imageselect.php?mode=1&fieldID=" + pwinvar, "ImageSelector", "width=780,height=480, scrollbars=0, status=no,toolbar=no,resizable=no");
    imgSelectPopUp.focus( );
}

function openUploader( ){
    var imgSelectPopUp = window.open("./imageselect.php", "ImageSelector", "width=780,height=680, scrollbars=0, status=no,toolbar=no,resizable=no");
    imgSelectPopUp.focus( );

    return false;
}

function fileSelectPopUp(pwinvar){
    imgSelectPopUp = window.open("./fileselect.php?mode=1&fieldID=" + pwinvar, "FileSelector", "width=780,height=580, scrollbars=0, status=no,toolbar=no,resizable=no");
    imgSelectPopUp.focus( );
}

function openFUploader( ){
    var imgSelectPopUp = window.open("./fileselect.php", "FileSelector", "width=780,height=580, scrollbars=0, status=no,toolbar=no,resizable=no");
    imgSelectPopUp.focus( );

    if(document.all){
        window.event.cancelBubble = true;
    }
    else{
        e.stopPropagation( );
        e.preventDefault( );
    }
    return false;
}

//drop down menus ##################################################

function initTopMenuLinks( ){
    var tmenu = document.getElementById('tmenu');

    if(!tmenu || !bgzDDEnabled){
        return;
    }

    var td = tmenu.getElementsByTagName('td')[0]

    while(td){
        if(!td.tagName || td.tagName.toLowerCase( ) != 'td'){
            td = td.nextSibling;
            continue;
        }

        var tbl = td.getElementsByTagName('table')[0];
        if(tbl){
            //add fancy css
            var nav = navigator.userAgent.toLowerCase();
            var is_bad_chrome = false;
            if(nav.match(/\b(chrome)\b/)){ if(nav.match(/525\.1/)){ is_bad_chrome = true; } }
            if(!is_bad_chrome){
                //tbl.style.MozBoxShadow = '#c8d8e1 2px 2px 2px';
                //tbl.style.WebkitBoxShadow = '#c8d8e1 2px 2px 2px';
            }

            td.bgzdd = new bgzDropDown( );
            td.bgzdd.init(td, tbl, 'down');
        }
        td = td.nextSibling;
    }

    //multi-dro ... -moz-hack ... text cuts off
    var liA = tmenu.getElementsByTagName('li')
    var len = liA.length;
    for(var i = 0; i < len; i++){
        var a = liA[i].getElementsByTagName('a')[0];
        a.innerHTML = a.innerHTML + ' &nbsp';
    }

}

function initLeftMenuLinks( ){
    var dleftmenu = document.getElementById('prodCats');

    if(!dleftmenu){ return; }

    var liA = dleftmenu.getElementsByTagName('li')
    var len = liA.length;

    for(var i = 0; i < len; i++){
        var li = liA[i];
        if(bgzDDEnabled){
            li.bgzdd = new bgzDropDown( );
            var ul = li.getElementsByTagName('ul')[0];
            if(ul){
                li.bgzdd.init(li, ul, 'down', 'click');
            }
        }
        else{
            li.onmouseover = pageON;
            li.onmouseout = pageOFF;
        }
    }
}
function pageON(index){
    var uls = this.getElementsByTagName('ul');
    if(uls.length > 0){
        show(uls[0]);
    }

}
function pageOFF(index){
    if(document.getElementById){
        if(!isHideCheck) hideMenu( );
    }
}
function show(menu){
    if(CurMenu)
        CurMenu.style.display = "none";
    menu.style.display = "block";
    isDropped = true;
    CurMenu = menu;
}
function hideMenu( ){
    if(CurMenu){
        isDropped = false;
        isHideCheck = true;
        setTimeout('checkDropped( );', 500);
        isHideCheck = false;
    }
}
function checkDropped( ){
    if(!isDropped) CurMenu.style.display = "none";
}
//############################################################

function printView(plink) {
    var plink2 = "/print/p/" + plink;
    window.open(plink2, "ShoppingList", "width=620,height=400,status=yes,toolbar=no,resizable=yes,raised=yes,scrollbars=yes");
}

function printPage(buttonID) {
    var printButton = document.getElementById(buttonID);
    printButton.style.visibility = "hidden";
    window.print();
    window.close();
}

var ipreviewWin = null;
function ipreview(lnk){
    ipreviewWin = window.open(lnk, "ipreviewWin", "width=780,height=480, menubar=yes, location=yes, scrollbars=yes, status=yes,toolbar=yes,resizable=yes");
    ipreviewWin.focus( );
    return false;
}

//category function
function lCategoryPopup(pwinvar){
    lCatPopUp = window.open("/include/category.php?lckey=" + pwinvar, "CategorySelect", "width=780,height=480, scrollbars=yes, status=yes,toolbar=no,resizable=yes");
    lCatPopUp.focus( );
}
function lCategoryPopupA(pwinvar){
    lCatPopUp = window.open("/include/category2.php?lckey=" + pwinvar, "CategorySelect", "width=780,height=480, scrollbars=yes, status=yes,toolbar=no,resizable=yes");
    lCatPopUp.focus( );
}
function lClassifiedPopup(pwinvar){
    lCatPopUp = window.open("/include/classified.php?lckey=" + pwinvar, "ClassifiedSelect", "width=780,height=480, scrollbars=yes, status=yes,toolbar=no,resizable=yes");
    lCatPopUp.focus( );
}
function productSelect(pwinvar){
    prodPopup = window.open("./product_select.php?lckey=" + pwinvar, "ProductSelect", "width=780,height=480, scrollbars=yes, status=yes,toolbar=no,resizable=yes");
    prodPopup.focus( );
}
function wsbPopup(loc){
    lCatPopUp = window.open(loc, "wsb", "width=782,height=480, menubar=yes, location=yes, scrollbars=yes, status=yes,toolbar=yes,resizable=yes");
    lCatPopUp.focus( );
}

function whatisPopup(loc){
    whatisPopUp = window.open(loc, "whatis", "width=300,height=300, menubar=no, location=no, scrollbars=yes, status=no,toolbar=no,resizable=yes");
    whatisPopUp.focus( );
}

function disableBoxes(form, check){
    for(var i = 0; i < form.elements.length; i++){
        if(form.elements[i].type == 'checkbox' && form.elements[i].id != 'acheck'){
            form.elements[i].disabled = check;
            form.elements[i].checked = check;
        }
    }
}

function optionInfoPopUp(povar){
    poInfoPopUp = window.open("/view_poption.php?poid=" + povar, "ProductOptionInfo", "width=500,height=480, scrollbars=yes, status=yes,toolbar=no,resizable=yes");
    poInfoPopUp.focus( );

    var winX = screen.width/2 - 500/2;
    var winY = screen.height/2 - 480/2;

    poInfoPopUp.moveTo(winX, winY)
}

function priceChk(rID, rClass, poiID, poiClass, poiPrice, newImg){
    var poiID = document.getElementById(poiID);
    var poiSpan = poiID.getElementsByTagName("span");
    var mainPrice = poiPrice;

    //update subtotal
    var radioID = document.getElementById(rID);
    var oldTotal = document.getElementById("total_price").innerHTML;
    var diff = poiSpan[0].innerHTML.replace(/\$/, "");

    var newTotal = parseFloat(oldTotal) + parseFloat(diff);
    var newTotal = newTotal.toFixed(2);
    document.getElementById("total_price").innerHTML = newTotal;

    inputs = document.getElementsByTagName("input");
    for(var z = 0; z < inputs.length; z++){
        var tmpin = inputs[z];
        if(tmpin.className == rClass){
            if(tmpin.id != radioID.id){
                //enable radio where it needs to be
                tmpin.disabled = false;
            }
            else{
                //disable radio so they can't keep clicking on it
                radioID.disabled = true;
            }
        }
    }
    spans = document.getElementsByTagName("span");
    for(var j = 0; j < spans.length; j++){
        var pois = spans[j];
        if(pois.className == poiClass){
            if(pois.id != poiID.id){
                //make sure everything is visibile where it needs to be
                pois.style.visibility = "visible";
                poiprices = pois.getElementsByTagName("span");

                for(var k = 0; k < poiprices.length; k++){
                    var prices = poiprices[k];
                    var pricesC = prices.className;

                    var otherPrice = pricesC.replace(/poi\_/, "");
                    var otherPrice = otherPrice.replace(/\_/, ".");

                    var totalp = otherPrice - mainPrice;
                    var total = totalp.toFixed(2);

                    if(total.match(/\-/)){
                        prices.innerHTML = total.replace(/\-/, "-$");
                    }
                    else{
                        //update prices
                        prices.innerHTML = "+$" + total;
                    }
                }
            }
            else{
                //hide the price
                poiID.style.visibility = "hidden";
            }
        }
    }

    if(newImg){
        var rcl1 = rClass.replace(/po/, "");
        var tmpid = rcl1.replace(/_radio/, "");
        var imgid = "img_" + tmpid;
        var img = document.getElementById(imgid);
        img.src = newImg;
    }
}

function setcookie(cookieName,cookieValue){
    //sets a cookie that expires at the end of the session
    document.cookie = cookieName + "=" + escape(cookieValue) + ";path=/";
}

function setCookie(cookieName,cookieValue){
    var dateNow = new Date( );
    var expire = new Date();
    expire.setTime(dateNow.getTime() + 7200000);
    document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString( ) + ";path=/";
}

function getCookie(cname){
    var dc = document.cookie;
    var prefix = cname + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1){
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else{
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1){
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/* GOOGLE MAPS */

function setDirections(toAddress, fromAddress){
    if(!fromAddress || !toAddress){
        return;
    }

    var mapObj = document.getElementById("google_map");
    if(!mapObj){
        return;
    }

    var directions = document.getElementById('directions');
    if(!directions){
        return;
    }

    var map = new GMap2(mapObj);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());

    gdir = new GDirections(map, directions);
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);

    gdir.load("from: " + fromAddress + " to: " + toAddress);

}

function handleErrors( ){
    if (gdir.getStatus( ).code == G_GEO_UNKNOWN_ADDRESS)
        alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);

    else if (gdir.getStatus( ).code == G_GEO_SERVER_ERROR)
        alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus( ).code == G_GEO_MISSING_QUERY)
        alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus( ).code == G_GEO_BAD_KEY)
        alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus( ).code == G_GEO_BAD_REQUEST)
        alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

    else alert("An unknown error occurred.");
}

function onGDirectionsLoad( ){
    var directions = document.getElementById('directions');
    directions.style.display = 'block';
}

var map;
var myPano;
var panoClient;
function loadGoogleMaps( ){
    if(GBrowserIsCompatible( )){
        maps = document.getElementsByTagName("div");

        for(var i = 0; i < maps.length; i++){
            var curMap = maps[i];
            if(curMap.id == "google_map"){
                var map_inner = curMap.innerHTML;

                var address = map_inner.replace(/address\:/, '');

                var info = '';
                var eid = 0;
                if(address.match(/\|\|info\:/g)){
                    var addA = address.split('||');
                    address = addA[0];

                    var info = addA[1].replace(/info\:/, '');

                    if(addA[2]){
                        eid = addA[2].replace(/^\s*|\s*$/, '');;
                    }
                }

                if(map_inner.match(/address\:/g)){
                    markAddress(address, curMap, info, eid);
                }
                else{
                    var coords = address.split(",");
                    if(!coords[1]){
                        return;
                    }

                    var map = new GMap2(curMap);
                    var point = new GLatLng(coords[0], coords[1]);

                    map.setCenter(point, 13);
                    map.addControl(new GSmallMapControl());
                    map.addControl(new GMapTypeControl());

                    var marker = new GMarker(point);
                    map.addOverlay(marker);

                    /*var sv_container = document.getElementById("google_pano");
                    if(sv_container){
                        var myPano = new GStreetviewPanorama(sv_container);
                        GEvent.addListener(myPano, "error", handleNoFlash);
                        svOverlay = new GStreetviewOverlay( );
                        map.addOverlay(svOverlay);
                        GEvent.addListener(map, "click", function(overlay,latlng) {
                            sv_container.style.display = 'block';
                            myPano.setLocationAndPOV(latlng);
                        });
                    }*/

                    var sv_container = document.getElementById("google_pano");
                    if(sv_container){
                        panoClient = new GStreetviewClient();

                        GEvent.addListener(map, "click", function(overlay,latlng) {
                            panoClient.getNearestPanorama(latlng, showPanoData);
                        });

                        myPano = new GStreetviewPanorama(sv_container);
                        svOverlay = new GStreetviewOverlay( );
                        map.addOverlay(svOverlay);
                        myPano.setLocationAndPOV(point);
                        GEvent.addListener(myPano, "error", handleNoFlash);
                        panoClient.getNearestPanorama(point, showPanoData);

                    }

                    GEvent.addListener(marker, "click", function(overlay,latlng){
                        map.openInfoWindowHtml(point, "<div style=\"line-height: 1.2em; font-size: .9em\">" + info + "</div>");
                    });

                    marker.openInfoWindowHtml("<div style=\"line-height: 1.2em; font-size: .9em\">" + info + "</div>");

                }
            }
        }
    }
}

function markAddress(address, curMap, info, eid){
    var map = new GMap2(curMap);
    var geocoder = new GClientGeocoder( );

    geocoder.getLatLng(address,
        function(point){
            if(!point){
                alert("Google was unable to find " + address + " at this time, please make sure the address provided, is correct.");
            }
            else{
                map.setCenter(point, 13);
                map.addControl(new GSmallMapControl());
                map.addControl(new GMapTypeControl());

                var marker = new GMarker(point);
                map.addOverlay(marker);

                var sv_container = document.getElementById("google_pano");
                if(sv_container){
                    panoClient = new GStreetviewClient();

                    GEvent.addListener(map, "click", function(overlay,latlng) {
                        panoClient.getNearestPanorama(latlng, showPanoData);
                    });

                    myPano = new GStreetviewPanorama(sv_container);
                    svOverlay = new GStreetviewOverlay( );
                    map.addOverlay(svOverlay);
                    myPano.setLocationAndPOV(point);
                    GEvent.addListener(myPano, "error", handleNoFlash);
                    panoClient.getNearestPanorama(point, showPanoData);

                }

                GEvent.addListener(marker, "click", function(overlay,latlng){
                    map.openInfoWindowHtml(point, "<div style=\"line-height: 1.2em; font-size: .9em\">" + info + "</div>");
                });

                marker.openInfoWindowHtml("<div style=\"line-height: 1.2em; font-size: .9em\">" + info + "</div>");

                var lat_long = new String(point);
                var lat_long = lat_long.replace(/\)|\(/g, '');
                var lat_longA = lat_long.split(/,/);

                var lat = lat_longA[0].replace(/^\s*|\s*$/, '');
                var lon = lat_longA[1].replace(/^\s*|\s*$/, '');
            }
        }
    );

}

function handleNoFlash(errorCode){
    if(errorCode == 603){
        //alert("Error: Flash doesn't appear to be supported by your browser");
        return;
    }
}

function showPanoData(panoData) {
    if (panoData.code != 200) {
        //GLog.write('showPanoData: Server rejected with code: ' + panoData.code);
        return;
    }

    var sv_container = document.getElementById("google_pano");
    sv_container.style.display = 'block';

    myPano.setLocationAndPOV(panoData.location.latlng);
}



/* END GOOGLE MAPS */

function checkShippingInfo() {
	var check_box = document.form.sSameAsBilling;
	if (check_box.checked) {
		document.form.sStreet1.disabled = true;
		document.form.sStreet2.disabled = true;
		document.form.sCity.disabled = true;
		document.form.sState.disabled = true;
		document.form.sZIP.disabled = true;
		document.form.sStreet1.style.backgroundColor = "#FAFAFA";
		document.form.sStreet2.style.backgroundColor = "#FAFAFA";
		document.form.sCity.style.backgroundColor = "#FAFAFA";
		document.form.sState.style.backgroundColor = "#FAFAFA";
		document.form.sZIP.style.backgroundColor = "#FAFAFA";
	}
	else {
		document.form.sStreet1.disabled = false;
		document.form.sStreet2.disabled = false;
		document.form.sCity.disabled = false;
		document.form.sState.disabled = false;
		document.form.sZIP.disabled = false;
		document.form.sStreet1.style.backgroundColor = "";
		document.form.sStreet2.style.backgroundColor = "";
		document.form.sCity.style.backgroundColor = "";
	    document.form.sState.style.backgroundColor = "";
		document.form.sZIP.style.backgroundColor = "";
    }
}

function personalizedProduct(inputField, optionCost, charCost, maxChar){
    var diff = 0;

    //alert("fieldLen " + fieldLen);
    //alert("inputField " + inputField.value.length);
    if(fieldLen > inputField.value.length){
        diff = (inputField.value.length - fieldLen) * charCost;

        if(inputField.value.length <= 0 && optionCost != 0){
            diff = diff - optionCost;
        }
    }
    else if(fieldLen < inputField.value.length){
        diff = (inputField.value.length - fieldLen) * charCost;

        if((inputField.value.length == 1 || (fieldLen == 0 && inputField.value.length > 0)) && optionCost != 0){
            diff = diff + optionCost;
        }
    }

    //alert(diff);

    fieldLen = inputField.value.length;

    var inputVal = inputField.value;
    if(inputVal.length > maxChar){
        inputField.value = inputVal.substring(0, maxChar);
    }
    else if(inputVal != "" || (inputVal == "" && diff != 0)){

        var oldTotal = document.getElementById("total_price").innerHTML;

        var newTotal = parseFloat(oldTotal) + parseFloat(diff);
        var newTotal = newTotal.toFixed(2);
        document.getElementById("total_price").innerHTML = newTotal;
    }

}
function loadGalleryImage(gID, imgID, imgSrc, imgWidth){
    var prodImgC = document.getElementById("prodImgContain");
    var prodImg = prodImgC.getElementsByTagName("img");

    if(prodImg.length == 0){
        return;
    }

    var newSrc = "/uimages/" + imgSrc;

    prodImg[0].src = newSrc;

    if(imgWidth > 550){
        prodImg[0].width = 550;
    }
    else{
        prodImg[0].width = imgWidth;
    }

    if(is_safari){
        generalPopUp('/view_image.php?gid=' + gID + '&img=' + imgSrc, 400, 400);
    }
}

function add2Cart(thisA, pid, qty, cart_p){
    if(b_xml.isCurrentRequest){ return false; }

    if(cart_p){
        window.location = '/content/p/' + cart_p + '/pid/' + pid + '/pqty/' + qty;
        return;
    }

    //alert('/ajax.php/pid/' + pid + '/qty/' + qty + '/ctype/p/type/add2cart');
    b_xml.request('/ajax.php/pid/' + pid + '/qty/' + qty + '/ctype/p/type/add2cart');

    if(b_xml.isSupported){ return false; }
}

function removeFromCart(thisA, ckey){
    if(b_xml.isCurrentRequest){ return false; }

    var cartItems = getCookie('cartItems');

    //alert('/ajax.php/remove/1/ckey/' + ckey + '/type/remove/items/' + cartItems);
    b_xml.request('/ajax.php/remove/1/ckey/' + ckey + '/type/remove/items/' + cartItems);
    if(b_xml.isSupported){ return false; }
}

function updatePrice(priceID, newTotal){
    updateID = document.getElementById(priceID);

    if(!updateID){
        return;
    }

    var newTotal = parseFloat(newTotal);
    updateID.innerHTML = '$' + newTotal.toFixed(2);
}

function openLoginForm(hst){

    //loc = '/members/?newlogin=1' + '&referer=' + escape(window.location.href);

    var referer = escape(window.location.href);

    var prot = 'http';
    if(window.location.href.match(/^https/)){
        prot = 'https';
    }
    var loginPopup = window.open("/members/login.php?prot=" + prot + "&referer=" + referer, "LoginForm", "width=320,height=320, scrollbars=1, status=yes, toolbar=no, resizable=yes");

    loginPopup.focus( );

    //alert(window.location.hostname + ' - ' + window.location.hst);

    if(window.location.hostname != hst){
        var loc = window.location.href.replace(/^(https?\:\/\/[\w\d\-\.]+\/)/, '/');
        loc = 'https://' + hst + loc;
        //alert(loc);

        //window.location.href = 'https://' + hst + loc;
    }

    return true;
}

function submitComment(fieldID){
    var bgzFrame = document.getElementById('bgz');
    var hidField = document.getElementById(fieldID);

    /*if(bgzFrame.contentDocument){
        var frameSrc = bgzFrame.contentDocument.body.innerHTML;
    }
    else{
        var frameSrc = document.frames['bgz'].document.body.innerHTML;
    }*/

    var frameSrc = getDocHTML( );

    //inject frameSrc into hidField value
    hidField.value = frameSrc;
}

function copyShipping(){
    var thisForm = document.getElementById('infoForm');
    var chkbox = document.getElementById('sameAsShipping');

    if(!chkbox){
        return;
    }

    if(chkbox.checked){
        //populate/update billing fields
        var sStreet1 = document.getElementById('sStreet1');
        var sStreet2 = document.getElementById('sStreet2');
        var sCity = document.getElementById('sCity');
        var sState = document.getElementById('sState');
        var sZipCode = document.getElementById('sZipCode');
        var sPhoneNumber = document.getElementById('sPhoneNumber');

        var bStreet1 = document.getElementById('bStreet1');
        var bStreet2 = document.getElementById('bStreet2');
        var bCity = document.getElementById('bCity');
        var bState = document.getElementById('bState');
        var bZipCode = document.getElementById('bZipCode');
        var bPhoneNumber = document.getElementById('bPhoneNumber');

        bStreet1.value = sStreet1.value;
        bStreet2.value = sStreet2.value;
        bCity.value = sCity.value;
        bState.value = sState.value;
        bZipCode.value = sZipCode.value;
        bPhoneNumber.value = sPhoneNumber.value;
    }
    else{
        var bStreet1 = document.getElementById('bStreet1');
        var bStreet2 = document.getElementById('bStreet2');
        var bCity = document.getElementById('bCity');
        var bState = document.getElementById('bState');
        var bZipCode = document.getElementById('bZipCode');
        var bPhoneNumber = document.getElementById('bPhoneNumber');

        //clear billing fields
        bStreet1.value = '';
        bStreet2.value = '';
        bCity.value = '';
        bState.value = '';
        bZipCode.value = '';
        bPhoneNumber.value = '';
    }
}

function updateBilling(srcVal, dest){
    var destId = document.getElementById(dest);
    var chkbox = document.getElementById('sameAsShipping');

    if(!chkbox){
        return;
    }

    if(chkbox.checked){
        destId.value = srcVal;
    }
}

function fillShipping(newVal){
    var chkbox = document.getElementById('sameAsShipping');

    if(newVal == 'new address'){
        document.getElementById('shippingName').value = '';
        document.getElementById('sFirstName').value = '';
        document.getElementById('sMiddleInitial').value = '';
        document.getElementById('sLastName').value = '';
        document.getElementById('sCompanyName').value = '';
        document.getElementById('sStreet1').value = '';
        document.getElementById('sStreet2').value = '';
        document.getElementById('sCity').value = '';
        document.getElementById('sState').value = '';
        document.getElementById('sZipCode').value = '';
        document.getElementById('sPhoneNumber').value = '';
        document.getElementById('sComments').value = '';

        if(chkbox.checked){
            document.getElementById('bStreet1').value = '';
            document.getElementById('bStreet2').value = '';
            document.getElementById('bCity').value = '';
            document.getElementById('bState').value = '';
            document.getElementById('bZipCode').value = '';
            document.getElementById('bPhoneNumber').value = '';
        }
    }
    else{
        if(!shipA[newVal]){
            return;
        }

        var thisShipping = shipA[newVal];

        document.getElementById('shippingName').value = thisShipping.shippingName;
        document.getElementById('sFirstName').value = thisShipping.sFirstName;
        document.getElementById('sMiddleInitial').value = thisShipping.sMiddleInitial;
        document.getElementById('sLastName').value = thisShipping.sLastName;
        document.getElementById('sCompanyName').value = thisShipping.sCompanyName;
        document.getElementById('sStreet1').value = thisShipping.sStreet1;
        document.getElementById('sStreet2').value = thisShipping.sStreet2;
        document.getElementById('sCity').value = thisShipping.sCity;
        document.getElementById('sState').value = thisShipping.sState;
        document.getElementById('sZipCode').value = thisShipping.sZipCode;
        document.getElementById('sPhoneNumber').value = thisShipping.sPhoneNumber;
        document.getElementById('sComments').value = thisShipping.sComments;

        if(chkbox.checked){
            document.getElementById('bStreet1').value = thisShipping.sStreet1;
            document.getElementById('bStreet2').value = thisShipping.sStreet2;
            document.getElementById('bCity').value = thisShipping.sCity;
            document.getElementById('bState').value = thisShipping.sState;
            document.getElementById('bZipCode').value = thisShipping.sZipCode;
            document.getElementById('bPhoneNumber').value = thisShipping.sPhoneNumber;
        }
    }
}

function fillBilling(newVal){
    var chkbox = document.getElementById('sameAsShipping');

    if(newVal == 'new card'){
        document.getElementById('billingName').value = '';
        document.getElementById('CCName').value = '';
        document.getElementById('CCNum').value = '';
        document.getElementById('expMonth').value = '';
        document.getElementById('expYear').value = '';

        if(!chkbox.checked){
            document.getElementById('bStreet1').value = '';
            document.getElementById('bStreet2').value = '';
            document.getElementById('bCity').value = '';
            document.getElementById('bState').value = '';
            document.getElementById('bZipCode').value = '';
            document.getElementById('bPhoneNumber').value = '';
        }

        updateCardImg( );
    }
    else{
        if(!billA[newVal]){
            return;
        }

        var thisBilling = billA[newVal];

        document.getElementById('billingName').value = thisBilling.billingName;
        document.getElementById('CCName').value = thisBilling.CCName;
        document.getElementById('CCNum').value = thisBilling.CCNum;
        document.getElementById('expMonth').value = thisBilling.expMonth;
        document.getElementById('expYear').value = thisBilling.expYear;

        if(!chkbox.checked){
            document.getElementById('bStreet1').value = thisBilling.bStreet1;
            document.getElementById('bStreet2').value = thisBilling.bStreet2;
            document.getElementById('bCity').value = thisBilling.bCity;
            document.getElementById('bState').value = thisBilling.bState;
            document.getElementById('bZipCode').value = thisBilling.bZipCode;
            document.getElementById('bPhoneNumber').value = thisBilling.bPhoneNumber;
        }

        updateCardImg( );
    }
}

function clearEventBilling( ){
    document.getElementById('saved_billing').value = 'new billing';
    document.getElementById('billing_name').value = '';

    var ccnum = document.getElementById('cc_num');
    if(ccnum.value.match(/\*/)){
        ccnum.value = '';
    }
    //var ach_account = document.getElementById('ach_account')
    //if(ach_account.value.match(/\*/)){
    //    ach_account.value = '';
    //}
    //var ach_routing = document.getElementById('ach_routing');
    //if(ach_routing.value.match(/\*/)){
    //    ach_routing.value = '';
    //}
}

function fillEventBilling(newVal){
    if(newVal == 'new billing'){
        if(document.getElementById('billing_name')){
            document.getElementById('billing_name').value = '';
        }

        document.getElementById('cc_name').value = '';
        document.getElementById('cc_num').value = '';
        document.getElementById('cc_mon').value = '';
        document.getElementById('cc_year').value = '';

        /*document.getElementById('ach_name').value = '';
        document.getElementById('ach_bank_name').value = '';
        document.getElementById('ach_type').value = '';
        document.getElementById('ach_routing').value = '';
        document.getElementById('ach_account').value = '';*/

        document.getElementById('billing_phone').value = '';
        document.getElementById('billing_street').value = '';
        document.getElementById('billing_street2').value = '';
        document.getElementById('billing_city').value = '';
        document.getElementById('billing_state').value = '';
        document.getElementById('billing_zip').value = '';
    }
    else{
        if(!billA[newVal]){
            return;
        }

        var thisBilling = billA[newVal];

        if(document.getElementById('billing_name')){
            document.getElementById('billing_name').value = thisBilling.billing_name;
        }

        if(thisBilling.cc_num){
            //document.getElementById('payment_type_cc').checked = 'check';
            //document.getElementById('payment_type_ach').checked = '';

            document.getElementById('cc_name').value = thisBilling.cc_name;
            document.getElementById('cc_num').value = thisBilling.cc_num;
            document.getElementById('cc_mon').value = thisBilling.cc_mon;
            document.getElementById('cc_year').value = '20' + thisBilling.cc_year;

            /*document.getElementById('ach_name').value = '';
            document.getElementById('ach_bank_name').value = '';
            document.getElementById('ach_type').value = '';
            document.getElementById('ach_routing').value = '';
            document.getElementById('ach_account').value = '';*/
        }
        /*else if(thisBilling.ach_account){
            //document.getElementById('payment_type_cc').checked = '';
            //document.getElementById('payment_type_ach').checked = 'check';

            document.getElementById('cc_name').value = '';
            document.getElementById('cc_num').value = '';
            document.getElementById('cc_mon').value = '';
            document.getElementById('cc_year').value = '';

            document.getElementById('ach_name').value = thisBilling.ach_name;
            document.getElementById('ach_bank_name').value = thisBilling.ach_bank_name;
            document.getElementById('ach_type').value = thisBilling.ach_type;
            document.getElementById('ach_routing').value = thisBilling.ach_routing;
            document.getElementById('ach_account').value = thisBilling.ach_account;
        }*/

        document.getElementById('billing_phone').value = thisBilling.billing_phone;
        document.getElementById('billing_street').value = thisBilling.billing_street;
        document.getElementById('billing_street2').value = thisBilling.billing_street2;
        document.getElementById('billing_city').value = thisBilling.billing_city;
        document.getElementById('billing_state').value = thisBilling.billing_state;
        document.getElementById('billing_zip').value = thisBilling.billing_zip;
    }
}

function setAttendeeInfo(new_val){
    if(new_val <= 0){
        document.getElementById('first_name').value = '';
        document.getElementById('last_name').value = '';
        document.getElementById('company_name').value = '';
        document.getElementById('street1').value = '';
        document.getElementById('street2').value = '';
        document.getElementById('city').value = '';
        document.getElementById('state').value = '';
        document.getElementById('zip').value = '';
        document.getElementById('email_address').value = '';
    }
    else{
        if(!attendeeA[new_val]){
            return;
        }

        var this_attendee = attendeeA[new_val];

        document.getElementById('first_name').value = this_attendee.first_name;
        document.getElementById('last_name').value = this_attendee.last_name;
        document.getElementById('company_name').value = this_attendee.company_name;
        document.getElementById('street1').value = this_attendee.street1;
        document.getElementById('street2').value = this_attendee.street2;
        document.getElementById('city').value = this_attendee.city;
        document.getElementById('state').value = this_attendee.state;
        document.getElementById('zip').value = this_attendee.zip;
        document.getElementById('email_address').value = this_attendee.email;
    }
}

function fillAddress(t_obj, pull_from, fill_to){
    if(!t_obj){ return; }

    if(t_obj.checked){
        var business_street1 = document.getElementById('Street1').value;
        var business_street2 = document.getElementById('Street2').value;
        var business_city = document.getElementById('City').value;
        var business_state = document.getElementById('State').value;
        var business_zip = document.getElementById('ZIP').value;

        var billing_street1 = document.getElementById('reg_street1').value;
        var billing_street2 = document.getElementById('reg_street2').value;
        var billing_city = document.getElementById('reg_city').value;
        var billing_state = document.getElementById('reg_state').value;
        var billing_zip = document.getElementById('reg_zip').value;

        if(pull_from == 'billing'){
            document.getElementById('reg_mailing_street1').value = billing_street1;
            document.getElementById('reg_mailing_street2').value = billing_street2;
            document.getElementById('reg_mailing_city').value = billing_city;
            document.getElementById('reg_mailing_state').value = billing_state;
            document.getElementById('reg_mailing_zip').value = billing_zip;
        }
        else if(pull_from == 'business' && fill_to == 'mailing'){
            document.getElementById('reg_mailing_street1').value = business_street1;
            document.getElementById('reg_mailing_street2').value = business_street2;
            document.getElementById('reg_mailing_city').value = business_city;
            document.getElementById('reg_mailing_state').value = business_state;
            document.getElementById('reg_mailing_zip').value = business_zip;
        }
        else if(pull_from == 'business' && fill_to == 'billing'){
            document.getElementById('reg_street1').value = business_street1;
            document.getElementById('reg_street2').value = business_street2;
            document.getElementById('reg_city').value = business_city;
            document.getElementById('reg_state').value = business_state;
            document.getElementById('reg_zip').value = business_zip;
        }
    }
    else if(fill_to == 'billing'){
        document.getElementById('reg_street1').value = '';
        document.getElementById('reg_street2').value = '';
        document.getElementById('reg_city').value = '';
        document.getElementById('reg_state').value = '';
        document.getElementById('reg_zip').value = '';
    }
    else if(fill_to == 'mailing'){
        document.getElementById('reg_mailing_street1').value = '';
        document.getElementById('reg_mailing_street2').value = '';
        document.getElementById('reg_mailing_city').value = '';
        document.getElementById('reg_mailing_state').value = '';
        document.getElementById('reg_mailing_zip').value = '';
    }
}

function disableBilling(t_obj){
    var event_form = document.getElementById('event_billing_form');
    var member_form = document.getElementById('member_signup_form');
    if(event_form){
        var d_flag = false;
        if(t_obj.checked){
            d_flag = true;
        }

        var event_form_len = event_form.elements.length;
        for(var i = 0; i < event_form_len; i++){
            if(event_form.elements[i] == t_obj || event_form.elements[i].type == 'submit' || event_form.elements[i].type == 'hidden'){
                continue;
            }

            event_form.elements[i].disabled = d_flag;
        }
    }
    else if(member_form){
        var d_flag = false;
        if(t_obj.checked){
            d_flag = true;
        }

        var member_form_len = member_form.elements.length;
        for(var i = 0; i < member_form_len; i++){
            if(member_form.elements[i] == t_obj || member_form.elements[i].id == 'reg_fee_override' || member_form.elements[i].type == 'submit' || member_form.elements[i].type == 'checkbox' || member_form.elements[i].type == 'hidden'){
                continue;
            }

            member_form.elements[i].disabled = d_flag;
        }
    }
}

function updateCardImg( ){
    var ccField = document.getElementById('CCNum');

    if(!ccField){
        return;
    }

    //add jcb and diners if and when supported
    var discover = document.getElementById('discCC');
    var mastercard = document.getElementById('masterCC');
    var visa = document.getElementById('visaCC');
    var amex = document.getElementById('amexCC');

    discover.src = "/images/discover_gray.gif";
    mastercard.src = "/images/mastercard_gray.gif";
    visa.src = "/images/visa_gray.gif";
    amex.src = "/images/amex_gray.gif";

    if(ccField.value == ''){
        return;
    }

    var ccnum = ccField.value;

    ccLen = ccnum.length;
    ccnum = ccnum.replace(/\*/g, '');
    //we have to base it off of the first digit and length because we don't know the rest of the #s
    if(ccnum.substr(0, 1) == 6 && ccLen == 16){
        discover.src = '/images/discover.gif';
    }
    else if(ccnum.substr(0, 1) == 5 && ccLen == 16){
        mastercard.src = '/images/mastercard.gif';
    }
    else if(ccnum.substr(0, 1) == 4 && (ccLen == 16 || ccLen == 13)){
        visa.src = '/images/visa.gif';
    }
    else if(ccnum.substr(0, 1) == 3 && ccLen == 15){
        amex.src = '/images/amex.gif';
    }
    else if((ccnum.substr(0, 1) == 3 && ccLen == 16) || (ccLen == 15 && (ccnum.substr(0, 4) == 2131 || ccnum.substr(0, 4) == 1800))){
        //jcb
    }
    else if(ccLen == 14 && ccnum.substr(0, 3) >= 300 && ccnum.substr(0, 3) <= 305){
        //diners 1
    }
    else if(ccLen == 14 && (ccnum.substr(0, 2) == 36 || ccnum.substr(0, 2) == 38)){
        //diners 2
    }


   /*
    if(ccnum.substr(0, 4) == 6011 && ccLen == 16){
        discover.src = '/images/discover.gif';
    }
    else if(ccnum.substr(0, 2)  && ccLen == 16){
        mastercard.src = '/images/mastercard.gif';
    }
    else if(ccnum.substr(0, 1) == 4 && (ccLen == 16 || ccLen == 13)){
        visa.src = '/images/visa.gif';
    }
    else if(ccnum.substr(0, 1) == 3 && ccLen == 15){
        amex.src = '/images/amex.gif';
    }
    else if((ccnum.substr(0, 1) == 3 && ccLen == 16) || (ccLen == 15 && (ccnum.substr(0, 4) == 2131 || ccnum.substr(0, 4) == 1800))){
        //jcb
    }
    else if(ccLen == 14 && ccnum.substr(0, 3) >= 300 && ccnum.substr(0, 3) <= 305){
        //diners 1
    }
    else if(ccLen == 14 && (ccnum.substr(0, 2) == 36 || ccnum.substr(0, 2) == 38)){
        //diners 2
    }
   */
}

function clearBilling( ){
    document.getElementById('savedBilling').value = 'new card';
    document.getElementById('billingName').value = '';

    var ccnum = document.getElementById('CCNum');
    if(ccnum.value.match(/\*/)){
        ccnum.value = '';
    }
}

function clearShipping( ){
    document.getElementById('savedShipping').value = 'new address';
    document.getElementById('shippingName').value = '';
}

function disableButton(buttonID, msg){
   tButton = document.getElementById(buttonID);

   if(!tButton){
        return;
   }

   tButton.value = msg;
   tButton.style.color = "#606060";
   tButton.style.backgroundColor = "#C0C0C0";
   tButton.disabled = true;
}


function toggleChecked(container_id, c_flag){
    if(!document.getElementById(container_id)){ return false; }

    c_obj = document.getElementById(container_id);

    var checkboxes = c_obj.getElementsByTagName('input');
    var c_len = checkboxes.length;


    for(var i = 0; i < c_len; i++){
        if(checkboxes[i].type != 'checkbox'){ continue; }
        if(c_flag){
            checkboxes[i].checked = true;
        }
        else{
            checkboxes[i].checked = false;
        }
    }
}

function updateTotal(obj_id, val_obj_id, cb_obj_id){
    //this is a free feature
    return;
    if(!document.getElementById(obj_id) || !document.getElementById(val_obj_id) || !document.getElementById(cb_obj_id)){ return false; }

    var g_obj = document.getElementById(obj_id);
    var val_obj = document.getElementById(val_obj_id);
    var cb_obj = document.getElementById(cb_obj_id);

    var g_total = g_obj.innerHTML;
    g_total = g_total.replace(/[^\d^\.]/, '');

    var total = parseFloat(g_total);

    var t_val = val_obj.value;

    if(cb_obj.checked){
        if(t_val.match(/^(\d+\.\d\d)$/)){
            total += Math.round(t_val * 100)/100;
        }
        else if(t_val.match(/^(\d+)$/)){
            t_val = t_val + ".00";
            total += Math.round(t_val * 100)/100;
        }
    }
    else{
        if(t_val.match(/^(\d+\.\d\d)$/)){
            total -= Math.round(t_val * 100)/100;
        }
        else if(t_val.match(/^(\d+)$/)){
            t_val = t_val + ".00";
            total -= Math.round(t_val * 100)/100;
        }
    }

    g_obj.innerHTML = '$' + total;
}

function changeImg(img_id, prod_id){
    if(!img_id){ return; }
    b_xml.request('/ajax.php/type/change_prod_img/prod_id/' + prod_id + '/img_id/' + img_id);
}

function refreshSImg(sImg){
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 8;
	var randomStr = '';
	for (var i = 0; i < string_length; i++) {
		var rnum = Math.floor(Math.random( ) * chars.length);
		randomStr += chars.substring(rnum, rnum+1);
	}

	var sImgSrc = sImg.src;
	if(sImgSrc.match('&')){
	    sImgSrcA = sImgSrc.split('&');
	    sImgSrc = sImgSrcA[0];
	}

    sImg.src = sImgSrc + '&' + randomStr;
}

function removeRecentItems( ){
    setcookie('recent_items', '');
    if(b_xml.isCurrentRequest){ return false; }

    b_xml.request('/ajax.php/type/recent_items');
    if(b_xml.isSupported){ return false; }
}

function hideById(tid){
    tObj = document.getElementById(tid);

    tObj.style.display = 'none';
}
function showById(tid, dispType){
    tObj = document.getElementById(tid);

    if(!dispType || window.is_ie){
        dispType = 'block';
    }

    tObj.style.display = dispType;
}
function toggleById(tid, dispType){
    tObj = document.getElementById(tid);

    if(!dispType || window.is_ie){
        dispType = 'block';
    }

    if(tObj.style.display == dispType){
        tObj.style.display = 'none';
    }
    else{
        tObj.style.display = dispType;
    }
}

function updateEventsBlock( ){
    if(!document.getElementById('bb_event_type')){ return; }

    etid = document.getElementById('bb_event_type').value;

    b_xml.request('/ajax.php/type/bbeventtype/?etid=' + etid);
    if(b_xml.isSupported){ return false; }
}

function checkAll(ck_class){
    inputsA = document.getElementsByTagName('input');
    input_len = inputsA.length;
    for(i = 0; i < input_len; i++){
        t_input = inputsA[i];
        if(t_input.type == 'checkbox' && t_input.className == ck_class && !t_input.checked){
            t_input.checked = true;
        }
    }
}

function uncheckAll(ck_class){
    inputsA = document.getElementsByTagName('input');
    input_len = inputsA.length;
    for(i = 0; i < input_len; i++){
        t_input = inputsA[i];
        if(t_input.type == 'checkbox' && t_input.className == ck_class && t_input.checked){
            t_input.checked = false;
        }
    }

}

function initColorBox( ){
    $("a[rel='cb-prod-pic']").colorbox( );
    $("a[rel='cb-prod-enlarge']").colorbox( );
    $("a[rel='cb-gallery']").colorbox( );
    $("a[rel='cb-pageGallery']").colorbox( );
}

function loadCufonFonts( ){
    Cufon.replace('#headmenu td a,#tmenu td a span',{
        fontFamily: 'verdana'
    });
    Cufon.replace('#pNumber',{
        fontFamily: 'times'
    });
    Cufon.replace('#tagline,.blockH h5,#prodName, h1,h2,h3,h4,h5',{
        fontFamily: 'times',
        textShadow: '#50d8f2 1px 1px',
        color: '-linear-gradient(0.3=#5788ba, 0.3#14589f, 0.3=#5788ba))'
    });
}

var image_attempts = 0;
function valignProductImages( ){
    $.each($('.prod_img_a'), function( ){
        container_height = $(this).height( );
        img_height = $(this).children('img').first( ).height( );

        if(img_height == 0){
            if(image_attempts < 2){
                setTimeout('valignProductImages( );', 500);
                image_attempts++;
            }
            return;
        }

        height_diff = (container_height - img_height) / 2;
        img_margin = parseInt(height_diff);

        $(this).children('img').first( ).css({'margin-top': img_margin + 'px'});
    });
}

function fixPNGs( ){
    if(window.isOldIE) {
        $('img[src$=.png]').each(function() {
        if (!this.complete) {
            this.onload = function() { fix(this) };
        }else {
            fix(this);
        }
     });
    }
}

function fix(png){
    var blank = new Image();
    blank.src = '/images/spacer.gif';

    var src = png.src;

    if(!png.style.width){
        png.style.width = $(png).width();
    }
    if(!png.style.height){
        png.style.height = $(png).height();
    }

    png.src = blank.src;
    png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
}
