/*
  ----------------------------------------------------------------------------
    BBScripts
  ----------------------------------------------------------------------------
*/

/*
  ----------------------------------------------------------------------------
    Retrieve Value
    
    gets the value of most form elements
    
    aFormElement is a DOM form object
    
    returns the value of aFormElement
    
    Ex: <form action="#" onsubmit="someNeededValue = retrieveValue('selectA')">
          <select name="selectA">
            <option value="1">1</option>
            <option value="2">2</option>
          </select>
  ----------------------------------------------------------------------------
*/
function retrieveValue(aFormObject) {
  var value = null;
  if (aFormObject.type == "select-one") {
    value = aFormObject.options[aFormObject.selectedIndex].value;
  } else if (aFormObject.type == "radio") {
    value = getRadioButtonValue(document.getElementsByName(aFormObject.name));
  } else {
    value = aFormObject.value;
  }
  return value;
}

/*
  ----------------------------------------------------------------------------
    Get Radio Button Value
    
    gets the value of radio buttons or other linked form elements that use value
    
    retrieveValue calls this fuction when necessary
    
    button is the name of the button group
    
    return the value of the selected button
    
    Ex: <form action="#" onsubmit="radioValue = getRadioButtonValue(radioA)">
          <input type="radio" name="radioA" value="1">
          <input type="radio" name="radioA" value="2">
          <input type="radio" name="radioA" value="3">
  ----------------------------------------------------------------------------
*/  
function getRadioButtonValue(radioButtonObjects) {
  var count = -1;
  var button = radioButtonObjects;
  for (var i = 0; i < button.length; i++) {
    if (button[i].checked) {
      count = i; 
      break;
    }
  }
  if (count > -1) {
    return button[count].value;
  } else {
    return null;
  }
}

/*
  ----------------------------------------------------------------------------
    Check for Valid Email
    
    checks for a period and the at symbol
    
    anId is the ID of the input field
    
    return true if passed, false if failed
    
    Ex: <form action="#" onsubmit="return checkEmail('emailA')">
          <input name="emailA" id="emailA" type="text">
  ----------------------------------------------------------------------------
*/  
function checkEmail(anId) {
  var e = document.getElementById(anId);
  var ok = false;
  if (e != null) {
    if (e.value.indexOf(".") != -1 && e.value.indexOf("@") != -1) {
      ok =  true;
    }
  }
  return ok;
}

/*
  ----------------------------------------------------------------------------
    GetXmlHttpObject
    
    creates the HttpRequest if the browser can support it
    
    AJAX object
    
    returns HttpRequest object
    
    Ex: http://www.w3schools.com/ajax/
  ----------------------------------------------------------------------------
*/  
function GetXmlHttpObject() {
  var xmlHttp=null;
  try {
    // Firefox, Opera 8.0+, Safari, non IE
    xmlHttp=new XMLHttpRequest();
  } catch (e) {
    // Internet Explorer  6+
    try {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try { // IE 5
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) { // NO AJAX
        alert("Your browser does not support AJAX.")
      }
    }
  }
  return xmlHttp;
}

/*
  ----------------------------------------------------------------------------
    Check Search for Invalid Characters
    
    Scrubs search and appends an asterisk for more results.  Could use a tilda
    or nothing at all.
    
    returns ok if scrubbing succeeded otherwise false
    
    Ex: <form action="#" onsubmit="return checkSearch('searchTerm')">
          <input name="searchTerm" id="searchTerm" type="text">
  ----------------------------------------------------------------------------
*/
function checkSearch(anId) {
  var ok = false;
  var term = document.getElementById(anId);
  if (term != null && term.value.length > 0) {
    var stuff = new RegExp("[^a-zA-Z0-9_ .~-]","g");
    term.value = term.value.replace(stuff,"");
    term.value = term.value + "*";
    ok = true;
  }
  return ok;
}
  
/*
  ----------------------------------------------------------------------------
    Prevent Enter
    
    prevents the enter key from submition
    
    Ex: <form action="#" onkeypress="return preventEnter()">
          <input type="text" name="name" onkeypress="return preventEnter()">
  ----------------------------------------------------------------------------
*/
function preventEnter() {
  //return !(window.event && window.event.keyCode == 13);
  
  try {
    if (window.addEventListener) { // FF & Opera
      window.addEventListener("keypress", checkEnter, false) //invoke function
    }
  } catch (e) { // IE 
    if (window.attachEvent) {
      window.attachEvent("onkeypress", checkEnterIE) //invoke function 
    }
  }
}  

function checkEnter(e) {
  if (e != null) {
    if (e.keyCode == 13) {
      e.preventDefault();
    }
  } else {
    if (window.event.keyCode == 13) {
      event.returnValue == false;
    }
  }
}

function checkEnterIE() {  
  alert("working...");
}
  
/*
  ----------------------------------------------------------------------------
    No Dashed Lines
    
    makes the clickable objects on a webpage look nicer
    
    anObjct is the element that should not have dashed lines
    
    prevents the enter key from submition
    
    Ex: <a href="#" onFocus="noDashedLines(this)">Link</a>
  ----------------------------------------------------------------------------
*/  
function noDashedLines(anObject) {
  if(anObject.blur) {
    anObject.blur();
  }
}
  
/*
  ----------------------------------------------------------------------------
  Check For Number Not Zero
  
  anId is the id for the element
  
  returns true for numbers != 0 otherwise false
  ----------------------------------------------------------------------------
*/
function checkForNumber(anId) {
  var ok = true;
  var e = document.getElementById(anId);
  if (e.value.search("\\D") != -1 || e.value == "0") {
    ok = false;
  }
  return ok;
}  
  
/*
  ----------------------------------------------------------------------------
  bookmarkthis
  
  Creates a bookmark
  
  title is optional pagetitle
  
  Ex: <a href="#" onclick="bookmarkthis(null)">Bookmark This Page</a>
  ----------------------------------------------------------------------------
*/
function bookmarkthis(title) {
  var url = location.href;
  if (title == null || title == "null") {
    title = "Bookmark";
  }
  if (window.sidebar != null && window.sidebar) { // firefox
     window.sidebar.addPanel(title, url, "");
  } else if (window.opera != null && window.opera && window.print != null && window.print) { // opera
     var elem = document.createElement('a');
     elem.setAttribute('href',url);
     elem.setAttribute('title',title);
     elem.setAttribute('rel','sidebar');
     elem.click();  
  } else if (document.all != null && document.all) { // IE
     window.external.AddFavorite(url, title);
  }
}

/*
  ----------------------------------------------------------------------------
    Create Popup Window
    
    creates a popup window with the parameters hardcoded.
    
    url is the page that the popup uses
    
    title is the optional title
    
    returns the handle to the popup window
    
    Ex: <a href="#" onclick="createPopupWindow('/cardCodeInformation.html','Card Code Information')">
          Card Code Information
        </a>
  ----------------------------------------------------------------------------
*/
function createPopupWindow(url, title) {
  if (title == null || title == "null") {
    title = "Popup";
  }
  var windowHandle = window.open(url, title, 
    'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,copyhistory=no,width=400,height=400');
  return windowHandle;
}

/*
  Start Image Gallery
*/
  var ImageHolder = new Class({
    initialize: function() {
      this.larges = new Array();
      this.thumbs = new Array();
      this.zooms = new Array();
    },
    getImages: function(anIndex) {
      var result = [];
      if (anIndex < this.larges.length) {
        result[0] = this.larges[anIndex];
        result[1] = this.thumbs[anIndex];
        result[2] = this.zooms[anIndex];
      }
      return result;
    }
  });  
  
  /*
    ImageGallery
    
    tempImage: image to display until zoom has loaded
    onHover: boolean value for hover or click of thumbs
  */
  var ImageGallery =  new Class({
    initialize: function(zoomableClass, thumbClass, mainImageId, zoomDivId, imageHolder, tempImage, onHover) {
      var self = this;
      self.zoomableClass = zoomableClass;
      self.thumbClass = thumbClass;
      self.mainImage = $(mainImageId);
      self.zoomDiv = $(zoomDivId);
      self.imageHolder = imageHolder;
      self.currentIndex = 0;
      if (tempImage == null) {
        self.tempImage = '/images/spacer.gif';
      } else {
        self.tempImage = tempImage;
      }
      if (onHover == null) {
        self.actionType = 'click';
      } else {
        if (onHover) {
          self.actionType = 'mouseover';
        } else {
          self.actionType = 'click';
        }
      }
      var zoomTitle = new Element('div', {
        id: 'zoomTitle',
        html: 'Zoom'
      });
      zoomTitle.inject(self.zoomDiv,'top');
      zoomTitle.addClass('titleBarPopup');
      var tmpImg = new Image();
      var zoomImg = new Image();
      self.zoomImg = zoomImg;
      tmpImg.src = (self.tempImage);
      
      new Drag(self.zoomDiv, {
        onStart: function() {
          if(Browser.Engine.trident5) this.handles.ondragstart = function()
          { return false; };
          self.zoomDiv.setStyle('cursor','move');
        },
        onComplete: function() {
          self.zoomDiv.setStyle('cursor','auto');
        },
        onCancel: function(ev) {
          self.hideZoom();
          self.zoomDiv.setStyle('cursor','auto');
        }
      });
      var zC = $$('.'+self.zoomableClass);
      zC.addEvent('click', function() {
        self.displayZoom();
      });
      var tC = $$('.'+thumbClass);
      tC.each(function(anImage, anIndex) {
        anImage.addEvent(self.actionType, function() {
          self.zoomDiv.fade('hide');
          tC.each(function(img) {
            img.removeClass('active');
          });
          anImage.addClass('active');
          self.updateImages(anIndex);
        });
        if (self.actionType == 'mouseover') {
          anImage.addEvent('click', function() {
            self.displayZoom();
          });
        }
      });
      var zDImg = self.zoomDiv.getElement('img'); 
      zDImg.addEvent('load', function() {
        self.zoomImg.src = self.zoomDiv.getElement('img').src;
        try {
          var x1 = self.zoomImg.width.toInt() - 10;
          if ($('zoomTitle') != null) {
            $('zoomTitle').setStyle('width', x1);
          }
        } catch (e) {
          //
        }
        self.zoomDiv.position({relativeTo: $$('.contentTable')[0], position: 'topLeft'});
      });      
    },
    displayZoom: function() {
      var self = this;
      self.updateImages(self.currentIndex);
      self.zoomDiv.setStyle('opacity','0');
      self.zoomDiv.setStyle('display','block');
      self.zoomDiv.fade('in');
    },
    hideZoom: function() {
      this.zoomDiv.fade('out');
    },
    updateImages: function(anIndex) {
      var self = this;      
      self.mainImage.set('src', self.imageHolder.larges[anIndex].src);
      self.zoomDiv.getElement('img').set('src', self.tempImage);
      self.zoomDiv.getElement('img').set('src', self.imageHolder.zooms[anIndex]);      
      self.currentIndex = anIndex;
    }
  });  
/*
  End Image Gallery
*/

// When the page finishes loading...
window.addEvent('domready', function() {
/*
  if (Browser.Engine.trident5) {
    var inputButtons = $$('input.button');
    inputButtons.setStyles({
      'padding-top':'0',
      'padding-bottom':'0px',
      'border-top-width':'1px;',
      'border-top-style':'solid',
      'height':'17px'
    });
    var anchorButtons = $$('a.button');
    anchorButtons.setStyles({
      'padding-top':'0px',
      'padding-bottom':'0px'
    });
  }
*/  
  if ($('noscript') != null) {
    $('noscript').setStyle('display','none'); // Opera fix for noscript
  }
  // image gallery
  if ($('imageZoomDiv') != null) {
    var imageGallery = new ImageGallery('zoomable','thumb','mainImage','imageZoomDiv',imageHolder,'/images/loading.jpg',false);
  }
  // reviews
  var detailReviewAll = $$('.detailReviewAll');
  if (detailReviewAll != null) {
  	detailReviewAll.each(function(dra) {
	    dra.addEvent('click', function(e) {
	      var reviewsWindow = $('reviewsWindow');
	      var innerRW = $('innerRW');
	      if (reviewsWindow == null) {
	        reviewsWindow = new Element('div', {
	          id: 'reviewsWindow'
	        });
	        innerRW = new Element('div', {
	          id: 'innerReviewsWindow',
	          'events': {
	            'mousedown': function(e) {
	              e.stop();
	            },
	            'click': function(e) {
	              reviewsWindow.fade('out');
	            }
	          }
	        });
	        var reviewsTitle = new Element('div', {
	          id: 'reviewsTitle',
	          html: 'Reviews'
	        });
	        reviewsTitle.addClass('titleBarPopup');
	        reviewsWindow.adopt(reviewsTitle);
	        reviewsWindow.adopt(innerRW);
	        reviewsWindow.setStyle('opacity','0');
	        reviewsWindow.inject($('reviewsTable'), 'after');	        
	        new Drag(reviewsWindow, {
	          onStart: function(e) {
	            if(Browser.Engine.trident5) this.handles.ondragstart = function()
	            { return false; };
	            reviewsWindow.setStyle('cursor','move');
	          },
	          onCancel: function(e) {
	            reviewsWindow.fade('out');
	            reviewsWindow.setStyle('cursor','auto');
	          },
	          onComplete: function(e) {
	            reviewsWindow.setStyle('cursor','auto');
	          }
	        });
	        var urlString = dra.get('href')+'&Ajax=Y';
	        new Request({
	          url: urlString,
	          noCache: 'true',
	          onSuccess: function(responseText) {
	            innerRW.set('html', responseText);
	          },
	          onRequest: function() {
	            innerRW.set('html', '<div>Loading...</div>');
	          },
	          onFailure: function(xhr) {
	            innerRW.set('html', '<div>Error: ' + xhr + '</div>');
	          },
	          onException: function(headerName, value) {
	            innerRW.set('html', '<div>Error: ' + headerName + ' ' +value + '</div>');
	          }
	        }).send();
	        //innerRW.load(detailReviewAll.get('href')+'&Ajax=Y');
	      }
	      reviewsWindow.position({relativeTo: dra});
	      reviewsWindow.fade('in');
	      var clicked = $(e.target);
	      if (clicked.get('tag') != 'a') clicked = clicked.getParent('a');
	      if (clicked) e.preventDefault();
	    });	    
  	});
  }
  
  // add to cart
  var orderForms = $$('.orderForm');  
  if (orderForms.length > 0) {
    var self = this;    
    orderForms.each(function(thisForm, anIndex, allForms) {      
      thisForm.addEvent('submit', function(event) {
        event.stop();
        var theURL = '/updateBasketAjax.jsp?';
        theURL += assembleParamters(thisForm);
        var reveal = showMessageFlare('Adding to cart...',thisForm.getElement('.addToCart'));
        var flare = thisForm.getElement('.addToCart').getElement('.flare');
        var addToCartResponse = new Request.JSON({
          noCache: 'true',
          onSuccess: function(result) {
            if (result == null) {
              showMessageFlare('Add to cart failed', thisForm.getElement('.addToCart'));
            } else {
              var addToBasketMessage = 'Added to basket';
              if (result.statusOk == true) {
                $$('.cartItemsSummary').set('html', result.numberOfItems);
                $$('.cartTotalSummary').set('html', result.total);
                var cartHeaderLinks = $$('.cartSummary')[0].getElements('a');
                if (result.numberOfItems > 0) {
                  if (!cartHeaderLinks.hasClass('second')) {
                    cartHeaderLinks.addClass('populated');
                  }
                  if (result.numberOfItems != 1) {
                    $$('.cartSummary')[0].getElement('.s').setStyle('display','inline');
                  } else {
                    $$('.cartSummary')[0].getElement('.s').setStyle('display','none');
                  }
                } else {
                  cartHeaderLinks.removeClass('populated');
                }
              } else {
                var messages = result.messages;
                if (messages > 0) {
                  messages.each(function(message) {
                    showMessage('generalError', message.message, message.status);
                  });
                }
                addToBasketMessage = 'Added to basket failed';
              }              
            }
            flare.set('html',addToBasketMessage);
            reveal.wait(4000).dissolve({duration: 2000}).chain(function(){flare.dispose()});
          },
          onRequest: function() {
            //showMessage('Adding to cart...',true);            
          },
          onFailure: function() {
            flare.set('html','Added to basket failed');
            flare.nix();
          },
          onException: function() {
            flare.set('html','Added to basket failed');
            flare.nix();
          }
        }).post(theURL);
      });
    });
  }
  
  
  if ($$('.accountTable') != null && $$('.accountTable')[0] != null && $$('.accountTable')[0].getElements('.delete') != null) {
    var accountDelete = $$('.accountTable')[0].getElements('.delete');
    accountDelete.addEvent('click', function(event) {
      var self = this;
      event.stop();
      var confirmWindow = $('confirmWindow');
      if (confirmWindow == null) {
        confirmWindow = new Element('div', {
          'id': 'confirmWindow'
        });
        var infoDiv = new Element('div', {
          'class': 'infoDiv',
          'html': 'Delete user and all stored information?<br />Information could be lost.'
        });
        infoDiv.inject(confirmWindow,'top');
        var div = new Element('div', {'html':'&nbsp;'});
        div.inject(infoDiv);
        var cancel = new Element('input', {
          'type': 'button',
          'class': 'button',
          'styles': {'float':'left'},
          'value': 'Cancel',
          'events': {
            'click': function() {
              confirmWindow.fade('hide');
            }
          }
        });
        cancel.inject(div);
        var accept = new Element('input', {
          'type': 'button',
          'class': 'button',
          'styles': {'float':'right'},
          'value': 'OK',
          'events': {
            'click': function() {
              document.location.href = self.get('href');
            }
          }
        });
        accept.inject(div);
        new Element('div', {
          'class': 'title',
          'html': self.get('title')
        }).inject(confirmWindow,'top');                
        confirmWindow.inject($$('.contentTable')[0]);
        confirmWindow.position({'relativeTo':$$('.tableBorders')[0]});
        new Drag(confirmWindow, {
          onStart: function(e) {
            if(Browser.Engine.trident5) this.handles.ondragstart = function()
            { return false; };
            confirmWindow.setStyle('cursor','move');
          },
          onComplete: function(e) {
            confirmWindow.setStyle('cursor','auto');
          }
        });                
      }
      confirmWindow.fade('in');
    });
  }
  
  // SortyBy
  var sortBy = $$('.sortByAction');
  if (sortBy != null) {
    try {
      var selectEl = sortBy;
      selectEl.addEvent('change', function() {
        location.href = this.options[this.selectedIndex].value;
      });
    } catch (e) {

    }
  }
  
  var giftGuideFormTable = $$('.giftGuideFormTable');
  if (giftGuideFormTable != null) {
    var keypresses = $$('.keypress');
    keypresses.each(function(item) {
      item.addEvent('keypress', function(event) {
        if (event.key != 'tab') {
          var label = item.getParent().getParent().getElement('label');
          $(label.get('for')).set('checked',true);
        }
      });
    });
  }
  
  var addressesTds = $$('.addressesTd');
  if (addressesTds != null) {
    addressesTds.each(function(addressesTd) {
      var select = addressesTd.getElement('select');
      select.addEvent('change', function() {
        var addresses = addressesTd.getElements('div.address');
        if (addresses != null && addresses.length > 0) {
          addresses.each(function(address) {
            address.addClass('hidden');
          });
          addresses[select.selectedIndex].removeClass('hidden');
        }
      });
      select.fireEvent('change');
    });
  }
  
  var forms = $$('.checkout4');
  if (forms != null) {
    forms.each(function(form) {
      form.addEvent('submit', function() {
        var stdFormFields = form.getElements('.stdFormField');
        if (stdFormFields != null) {
          stdFormFields.tidy();
        }
        var requireds = $$('.requiredField');
        var ok = true;
        var errorCount = 0;
        disabledFieldCount = 0;
        if (requireds != null) {
          requireds.each(function(requiredField) {
            if (requiredField.get('disabled') == true) {
              disabledFieldCount++;
            }
            if (requiredField.get('disabled') == false && requiredField.get('value') != null && requiredField.get('value').length > 0) {
              requiredField.removeClass('showErrorField');
            } else if (requiredField.get('disabled') == false) {
              requiredField.addClass('showErrorField');
              errorCount++;
            }
          });
        }
        if (errorCount > 0 && errorCount < disabledFieldCount) {
          ok = false;
        } else {
          requireds.each(function(requiredField) {
            requiredField.removeClass('showErrorField');
          });
        }
        return ok;
      });
    });
  }
  
  var shippingBlockTds = $$('.shippingBlockTd');
  if (shippingBlockTds != null) {
    var shippingTotal = Number(0);
    var shippingTotalSpan = $$('.estimatedShippingTotal').getElement('span');
    var showUPSStdMessage = false;
    shippingBlockTds.each(function(shippingBlockTd, index) {
      var shippingOptionsDiv = shippingBlockTd.getElements('div.shippingOptions');
      var selectCarrier = shippingBlockTd.getElement('select.selectCarrier');
      if (shippingOptionsDiv != null) {
        if (selectCarrier != null) {
          selectCarrier.addEvent('change', function() {
            var shippingOptionsDiv = shippingBlockTd.getElements('div.shippingOptions');
            var inputs = shippingOptionsDiv.getElements('input');
            shippingOptionsDiv.each(function(shippingOptions) {
              shippingOptions.addClass('hidden');
            });
            inputs.each(function(input) {
              input.set('disabled',true);
            });
            var selectedIndex = selectCarrier.selectedIndex;
            shippingOptionsDiv[selectedIndex].removeClass('hidden');
            inputs = shippingOptionsDiv[selectedIndex].getElements('input');
            inputs.each(function(input) {
              input.set('disabled',false);
            });
            var selectCarriers = $$('select.selectCarrier');
            var hasUPS = false;
            selectCarriers.each(function(aCarrier) {
              var options = aCarrier.getElements('option');
              options.each(function(anOption) {
                if (anOption.value == '1' && anOption.selected) { // UPS Carrier Id = 1
                  hasUPS = true;
                }
              });
            });
            if (hasUPS) {
              $$('.upsStdMessage').removeClass('hidden');
            } else {
              $$('.upsStdMessage').addClass('hidden');
            }
            if (inputs[0] != null) {
              inputs[0].fireEvent('click');
            }
          });
          selectCarrier.fireEvent('change');
        }
        if ($$('estimatedShippingTotal') != null) {
          if (shippingTotalSpan != null) {
            var inputs = new Array();
            var labels = new Array();
            shippingBlockTds.each(function(shippingBlockTd) {
              inputs.extend(shippingBlockTd.getElements('input[type=radio]'));
              labels.extend(shippingBlockTd.getElements('label'));
              inputs.each(function(input, inputIndex) {
                input.addEvent('click', function() {
                  var shippingTotal = 0;
                  var shippingAmount = 0;
                  inputs.each(function(anInput, anInputIndex) {
                    if (anInput.checked && !anInput.disabled) {
                      var label = (labels[anInputIndex]).get('html');
                      var loc1 = label.indexOf('$');
                      shippingAmount = label.substring(loc1+1, label.length);
                      var loc2 = shippingAmount.indexOf('.');
                      shippingAmount = shippingAmount.substring(0, loc2+3);
                      shippingTotal += Number(shippingAmount);
                    }
                  });
                  if (shippingTotalSpan != null) {
                    shippingTotalSpan.set('html', addCommas(shippingTotal.toFixed(2)));
                  }
                });
              });
            });
          }
        }
        if (selectCarrier != null) {
          selectCarrier.fireEvent('change');
        } else {
          shippingBlockTds.getElement('input[type=radio]').fireEvent('click');
        }
      }
    });
  }
  if (Browser.Engine.trident && Browser.Engine.version < 5) {
    // IE6 can't use
  } else {
    var searches = $$('input.search');
    if (searches != null) {
      searches.each(function(search) {
        new AjaxAutocomplete(search, '/searchAjax.jsp', {position: 'right'});
      });
    }
  }
  
  GenerateQuestionsAnswers();
  
  var expandingNavs = $$('.ExpandingNav');
  if (expandingNavs != null) {
    expandingNavs.each(function(expandingNav) {
      new ExpandingNav(expandingNav);
    });
  }
  var imageDiv = $$('.imageDiv');
  if (imageDiv != null) {
    imageDiv.each(function(anImageDiv) {
      var imageDescription = anImageDiv.getElement('.imageDescription');
      anImageDiv.getElement('img').addEvents({
        'mouseover': function(event) {
        /*
          event.stop();
          imageDescription.setStyle('width', anImageDiv.getParent().getCoordinates().width - anImageDiv.getStyle('padding-left').toInt() - anImageDiv.getStyle('padding-right').toInt() - anImageDiv.getStyle('border-right').toInt() - anImageDiv.getStyle('border-left').toInt() - 6);
          imageDescription.position({relativeTo: anImageDiv, position: 'upperLeft', offset: {x: -5, y: -5}});
          imageDescription.setStyle('display', 'block');
        */
        },
        'mouseout': function(event) {
          event.stop();
        }
      });
      if (imageDescription != null) {
	      imageDescription.addEvents({
	        'mouseout': function(event) {
	          event.stop();
	        },
	        'mouseover': function(event) {
	          event.stop();
	        }
	      });
      }
    });
    /*
    $$('body')[0].addEvent('mouseover', function() {
      imageDiv.getElement('.imageDescription').setStyle('display', 'none');
    });
    */
  }
  
  var anchors = null;
  try {
    anchors = $$('.showcase')[0].getElements('.btn-orng a');
  } catch (e) {
  
  }
  if (anchors != null) {
    anchors.each(function(anAnchor) {
      anAnchor.addEvent('click', function(event) {
        event.stop();
        var imageDescription = anAnchor.getParent('.showcase-td').getElement('.imageDescription');
        var anImageDiv = anAnchor.getParent('.showcase-td').getElement('.imageDiv');
        if (imageDescription.getStyle('display') == 'none') {
          imageDescription.setStyle('width', anImageDiv.getParent().getCoordinates().width - anImageDiv.getStyle('padding-left').toInt() - anImageDiv.getStyle('padding-right').toInt() - anImageDiv.getStyle('border-right').toInt() - anImageDiv.getStyle('border-left').toInt() - 6);
          imageDescription.position({relativeTo: anImageDiv, position: 'upperLeft', offset: {x: -5, y: -5}});
          imageDescription.setStyle('display', 'block');
          anAnchor.set('html','View Image');
        } else {
          imageDescription.setStyle('display', 'none');
          anAnchor.set('html','Description');
        }
      });
    });
    var uncompares = $$('.uncompare');
    uncompares.each(function(uncompare) {
      uncompare.addEvent('click', function(event) {
        var imageDescription = uncompare.getParent('.showcase-td').getElement('.imageDescription');
        imageDescription.setStyle('display', 'none');
        uncompare.getParent('.showcase-td').getElement('.btn-orng a').set('html','Description');
      });
    });
  }
  
  var showcase = $$('.showcase');
  if (showcase != null && showcase.length == 1) {
  	var tr = showcase[0].getElements('.showcase-tr');
  	tr.each(function(aTr) {
  		var maxHeight = 0;
  		var maxImageHeight = 0;
  		var imgDiv = aTr.getElements('.imageDiv');
  		if (imgDiv != null) {
  			imgDiv.each(function(aID) {  				
  				var aImg = aID.getElement('img');
  				if (aImg != null) {
  					var ih = aImg.height;
  					if (ih > maxImageHeight) {
  						maxImageHeight = ih;
  					}
  				}
  			});
  			imgDiv.each(function(aID) {
  				var aImg = aID.getElement('img');
  				if (aImg != null) {
  					aImg.setStyle('margin-bottom', (maxImageHeight - aImg.height) / 2 + 'px');
  					aImg.setStyle('margin-top', (maxImageHeight - aImg.height) / 2 + 'px');
  				}
  			});
  		}
  		if (imgDiv != null) {
  			imgDiv.each(function(aID) {
  				var h = aID.getCoordinates().height;
  				if (h > maxHeight) {
  					maxHeight = h;
  				}  				
  			});
  			imgDiv.each(function(aID) {
  				aID.setStyle('height', maxHeight + 'px');
  			});
  		}
  	});  	
  }
  
  
  
});
// End domready

function showMessageFlare(message, element) {
  var flare = new Element('div', {
    'class': 'flare',
    'html': message
  });
  flare.inject(element,'top');
  return new Fx.Reveal(flare,{'link':'chain'}).reveal();
}

function showMessage(message, statusOk) {
  var disMessageType = 'generalError';
  var status = 'Error';
  if (statusOk) {
    disMessageType = 'generalMessage';
    status = 'Messge';  
  }
  var disMessage = $$(disMessageType)[0];
  if (disMessage == null) {
    var disMessage = new Element('div', {
      'class': disMessageType
    });    
    var h2 = new Element('h2', {
      'html': status
    });
    h2.inject(disMessage);
    disMessage.inject($$('.mainContent')[0],'top');
  }
  var div = new Element('div', {
    'html': message
  });
  div.inject(disMessage);  
  disMessage.addEvent('click', function() {
    var fxC = new Fx();
    //fxC.start().chain(function(){disMessage.fade('out');});
    fxC.start().chain(function(){disMessage.fade('out');fxC.start();}).chain(function(){disMessage.dispose();} );
  });
}

// Clear Message Box
function clearMessageBox(aSection, status) {
  section = $(aSection);
  var boxType = 'generalError'; // class
  var heading = 'Error';
  if (status != null && status == true) {
    boxType = 'generalMessage';
    heading = 'Message';
  }
  var messageBox = section.getElement('.'+boxType);
  if (messageBox != null) {
    messageBox.setStyle('display', 'none');
    $(messageBox).getElements('div').dispose();
  }
}

function assembleParamters(aForm) {
  var elements = grabFormElements(aForm);
  return constructQueryString(elements);
}

/*
  AjaxAutocomplete

  Options:
    minCharacters: numeric value, defaults to 2
    formMethod: get / post, defaults to post
    errorMessage: text, set to empty string to no display, defaults to Error
    position: left or right, default to right
    skipKeys: array of keys to skip processing,
      default to up, down, right, left, esc, end, home, pageup, pagedown
*/
var AjaxAutocomplete = new Class({
  Implements: [Class.Occlude, Events, Options],
  options: {
    minCharacters: 2,
    formMethod: 'post',
    errorMessage: 'Error',
    position: 'right',
    skipKeys: ['up', 'down', 'right', 'left', 'esc', 'end', 'home', 'pageup', 'pagedown', 'shift'],
    maxKeyCode: 153,
    minKeyCode: 9,
    spinOptions: {containerPosition: {
      offset: {x: 0, y: 24}
    }},
    injectBRTag: true
  },
  initialize: function(element, url, options) {
    this.element = document.id(element);
    this.url = url;
    this.FxMorph = new Fx.Morph(this.element, {fps: '25', duration: 'short', transition: Fx.Transitions.Sine.easeOut});
    this.setOptions(options);
    this.FxMorph.setOptions(options);
    if (this.occlude()) {
      return this.occluded;
    }
    this.buildList();
    var self = this;
    this.request = new Request({
      method: this.options.formMethod,
      url: this.url,
      noCache: true,
      onSuccess: this.requestSuccessful.bind(self),
      onFailure: this.requestUnSuccessful.bind(self),
      onException: this.requestUnSuccessful.bind(self),
      onRequest: this.requestRequested.bind(self)
    });
    this.attach();
  },
  buildList: function() {
    this.searchResults = new Element('div', {
      'class': 'searchResults',
      'styles': {
        'display': 'none',
        'min-width': this.element.getDimensions().width.toInt()
      }
    }).inject(this.element, 'after');
    this.searchResults.setStyle('min-width', this.searchResults.getStyle('min-width').toInt()  -
      this.element.getStyle('border-left-width').toInt() - this.element.getStyle('border-right-width').toInt() -
      this.element.getStyle('padding-left').toInt() - this.element.getStyle('padding-right').toInt() -
      this.searchResults.getStyle('border-left-width').toInt() - this.searchResults.getStyle('border-right-width').toInt());
    if (this.options.injectBRTag) {
      new Element('br').inject(this.element, 'after');
    }
    this.ul = new Element('ul').inject(this.searchResults);
    this.element.setAttribute('autocomplete', 'off');
    return this;
  },
  attach: function() {
    this.element.addEvent('keyup', this.makeRequest.bindWithEvent(this));
    $$('body')[0].addEvent('click', this.hideSearch.bindWithEvent(this));
    return this;
  },
  detach: function() {
    this.element.removeEvent('keyup', this.makeRequest.bindWithEvent(this));
    $$('body')[0].removeEvent('click', this.hideSearch.bindWithEvent(this));
    return this;
  },
  makeRequest: function(event) {
    if (!this.options.skipKeys.contains(event.key) && event.code < this.options.maxKeyCode && event.code > this.options.minKeyCode) {
      if (this.element.get('value').length >= this.options.minCharacters) {
        this.request.cancel();
        this.request.send(this.element.get('name') + '=' + this.element.get('value'));
      } else {
        this.hideSearch();
      }
    }
    return this;
  },
  unFocus: function(event) {
    this.hideSearch();
    return this;
  },
  hideSearch: function() {
    this.request.cancel();
    this.element.unspin();
    this.searchResults.dissolve();
    this.fireEvent('hideSearch');
    return this;
  },
  showSearch: function() {
    if (this.options.position == 'left') {
      var margin = this.searchResults.getDimensions().width - this.element.getDimensions().width;
      this.searchResults.setStyle('margin-left', -margin);
    }
    this.searchResults.reveal();
    this.fireEvent('showSearch');
    return this;
  },
  requestSuccessful: function(responseText) {
    var self = this;
    if (responseText.indexOf('<li>') >= 0) {
      responseText = self.findMatchingText(responseText);
      new Chain(
        self.ul.set('html', responseText),
        self.showSearch(),
        self.element.unspin()
      ).callChain();
    } else {
      this.hideSearch();
    }
    this.fireEvent('successfulRequest');
    return this;
  },
  requestUnSuccessful: function() {
    this.element.unspin();
    if (this.options.errorMessage.length > 0) {
      this.ul.set('html', '<li>'+this.options.errorMessage+'</li>').chain(this.showSearch());
    }
    this.fireEvent('unsuccessfulRequest');
    return this;
  },
  requestRequested: function() {
    this.element.spin(this.options.spinOptions);
  },
  findMatchingText: function(responseText) {
    var searchText = this.element.get('value');
    var resultsListA = responseText.split('</li>');
    var replacement = '<span>'+searchText+'</span>';
    var regExp = new RegExp(searchText, 'ig');
    responseText = '';
    for (var i = 0; i < resultsListA.length; i++) {
      try {
        var resp = resultsListA[i].split('<li>').clean();
        if (resp[1] != null) {
          var title = resp[1].stripTags('a');
          var href = resp[1].getTags('a');
          responseText += ('<li>' + href[0] + title.replace(regExp, replacement) + href[1] + '</li>');
        }
      } catch (e) {
      }
    }
    return responseText;
  }
});
// End AjaxAutocomplete

//Generate Questions Answers
function GenerateQuestionsAnswers() {
  var questionAnswers = $$('.questionAnswers');
  if (questionAnswers != null) {
    var search = location.search;
    if (search != null && search.length > 0) {
      search = search.substring(1, search.length);
    }
    var query = new Hash(search.parseQueryString());
    var urlQuestion = null;
    if (query.has('question')) {
      urlQuestion = query.get('question');
    }
    questionAnswers.each(function(aQuestionAnswers) {
      var accordion = new Fx.Accordion({
        alwaysHide: true,
        display: -1,
        show: -1
      });
      var questionAnswers = aQuestionAnswers.getElements('.questionAnswer');
      if (questionAnswers != null) {
        questionAnswers.each(function(questionAnswer, index) {
          var question = questionAnswer.getElement('h1');
          var answer = questionAnswer.getElement('div');
          if (question != null && answer != null) {
            accordion.addSection(question, answer);
          }
          if (urlQuestion != null && urlQuestion.stripTags() == question.get('html').stripTags()) {
            accordion.display(index);
            new Fx.Scroll(window).toElement(question);
          }
        });
      }
    });
  }
}
// End GenerateQuestionsAnswers

// ExpandingNav
var ExpandingNav = new Class({
  Implements: [Class.Occlude, Events, Options],
  options: {
    activeClass: 'categoryMatch',
    moreClass: 'more',
    injectMore: true,
    injectPosition: 'bottom',
    useImage: true,
    onlyExpandWhenImageClicked: true,
    imageSrcMore: '/images/more2.gif',
    imageSrcLess: '/images/less2.gif'
  },
  initialize: function(element, options) {
    var self = this;
    this.element = document.id(element);
    this.FxMorph = new Fx.Morph(this.element, {fps: '25', duration: 'short', transition: Fx.Transitions.Sine.easeOut});
    this.setOptions(options);
    this.FxMorph.setOptions(options);
    if (this.occlude()) {
      return this.occluded;
    }
    this.element.getElements('ul').setStyle('display', 'none');
    this.element.getChildren('ul').setStyle('display', 'block');
    
    var lis = self.element.getElements('li');
    lis.each(function(li) {
      if (self.options.injectMore && li.hasClass(self.options.moreClass)) {
        var otherLIs = li.getElements('li');
        var subsHaveOthers = false;
        if (otherLIs != null) {
          for (var i = 0; i < otherLIs.length; i++) {
            if (otherLIs[i].hasClass(self.options.activeClass)) {
              subsHaveOthers = true;
              break;
            }
          }
        }
        if (subsHaveOthers || li.hasClass(self.options.activeClass)) {
          if (self.options.useImage) {
            var img = new Element('img', {
              src: self.options.imageSrcLess
            }).inject(li.getElement('a'), self.options.injectPosition);
          }
          li.getParent().setStyle('display', 'block');
          li.getElement('ul').setStyle('display', 'block');
        } else {
          if (self.options.useImage) {
            var img = new Element('img', {
              src: self.options.imageSrcMore
            }).inject(li.getElement('a'), self.options.injectPosition);
          }
        }
      }
    });
    this.attach();
  },
  attach: function() {
    var self = this;
    if (!self.options.onlyExpandWhenImageClicked) {
      this.element.getElements('a').addEvent('click', this.toggleLevel.bindWithEvent(this));
      this.element.getElements('a').addEvent('dblclick', this.leaveLevel.bindWithEvent(this));
    }
    this.element.getElements('img').addEvent('click', this.imageClick.bindWithEvent(this));
    return this;
  },
  detach: function() {
    if (!self.options.onlyExpandWhenImageClicked) {
      this.element.getElements('a').removeEvent('click', this.toggleLevel.bindWithEvent(this));
      this.element.getElements('a').removeEvent('dblclick', this.leaveLevel.bindWithEvent(this));
    }
    this.element.getElements('img').removeEvent('click', this.imageClick.bindWithEvent(this));
    return this;
  },
  toggleLevel: function(event, parentThis) {
    var self = this;
    var theElement = event.target;
    var child = $(theElement).getParent().getElement('ul');
    if (parentThis != null) {
      child = $(theElement).getParent().getParent().getElement('ul');
    }
    if (child != null) {
      var anA = child.getParent().getElement('a');
      if (child.getStyle('display') == 'block') {
        child.dissolve();
        if (anA != null) {
          if (self.options.useImage) {
            anA.getElement('img').src = self.options.imageSrcMore;
          }
        }
      } else {
        child.reveal();
        if (anA != null) {
          if (self.options.useImage) {
            anA.getElement('img').src = self.options.imageSrcLess;
          }
        }
      }
      event.stop();
    }
    this.fireEvent('toggleLevel');
    return this;
  },
  leaveLevel: function(event) {
    var theElement = event.target;
    this.fireEvent('leaveLevel');
    var newLoc = theElement.get('href');
    if (newLoc == null) {
      newLoc = theElement.getParent().get('href');
    }
    location.href = newLoc;
    return this;
  },
  imageClick: function(event) {
    var event2 = new Event(event);
    event.stop();
    this.toggleLevel(event2, this);
  }
});
// End ExpandingNav

function retrieveValue(aFormObject) {
  var value = null;
  if (aFormObject.type == "select-one") {
    value = aFormObject.options[aFormObject.selectedIndex].value;
  } else if (aFormObject.type == "radio" || aFormObject.type == "checkbox") {
    value = this.getRadioButtonValue(document.getElementsByName(aFormObject.name));
  } else if (aFormObject.type == "textarea") {
    value = aFormObject.innerHTML;
  } else {
    value = aFormObject.value;
  }
  return value;
}
// getRadioButtonValue
function getRadioButtonValue(radioButtonObjects) {
  var count = -1;
  var button = radioButtonObjects;
  for (var i = 0; i < button.length; i++) {
    if (button[i].checked) {
      count = i;
      break;
    }
  }
  if (count > -1) {
    return button[count].value;
  } else {
    return null;
  }
}
// Construct Query String
function constructQueryString(anArray) {
  var result = "";
  anArray.each(function(item,index,array) {
    if (item.getProperty('name') != null && item.getProperty('disabled') != null &&
      item.getProperty('disabled') == false) {
      if (item.getProperty('type') == 'checkbox' || item.getProperty('type') == 'radio') {
        if (item.getProperty('checked') == true) {
          result += "&"+item.getProperty('name')+"="+item.getProperty('value');
        }
      } else {
        result += "&"+item.getProperty('name')+"="+item.getProperty('value');
      }
    }
  });
  return result;
}
// Grab Form Elements
function grabFormElements(aSection) {
  var elements = aSection.getElements('input');
  elements.extend(aSection.getElements('select'));
  elements.extend(aSection.getElements('textarea'));
  return elements;
}

function addCommas(nStr) {
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

function exit() {
    if ($('tooltip')) {
        $('tooltip').setStyle('display', 'none');
    }
}
function getShippingText(whichOption, caller) {
  var s = "";
  if (whichOption == 'USPS') {
    s = "<p><b>USPS (2-7 Day Delivery)</b>: Select this option to receive your order within an estimated 2 to 7 day delivery time based on destination location.  Orders placed after 1:30 PM ET or on weekends and holidays should ship the next business day, unless otherwise noted.</p>";
  } else if (whichOption == 'USPS_Priority') {
    s = "<p><b>USPS Priority (2-3 Day Delivery)</b>: Select this option to receive your order within 2 to 3 days of shipping from the US Postal Service. Delivery times are not guaranteed and are based on destination locations.  Orders placed after 1:30 PM ET or on weekends and holidays should ship the next business day, unless otherwise noted.</p>";
  } else if (whichOption == 'UPS_Ground') {
    s = "<p><b>UPS Ground (2-7 Day Delivery)</b>: Select this option to track and guarantee your orders arrival within 2 to 5 days, based on destination location. Orders placed after 1:30 PM ET or on weekends and holidays should ship the next business day, unless otherwise noted.<p><strong>Note:</strong> This service is NOT available for orders sent to APO, FPO, P.O. Box addresses, outside of the 48 contiguous states, and U.S. possessions.</p></p>";
  } else if (whichOption == 'UPS_Air') {
    s = "<p><b>UPS 3 Day Air (3 Day Delivery)</b>: Select this option to track and guarantee your orders arrival within 3 business days of shipping.  Orders placed after 1:30 PM ET or on weekends and holidays should ship the next business day, unless otherwise noted.<p><strong>Note:</strong> This service is NOT available for orders sent to APO, FPO, P.O. Box addresses, outside of the 48 contiguous states, and U.S. possessions.</p></p>";
  } else if (whichOption == 'UPS_2ndDay') {
    s = "<p><b>UPS 2nd Day Air (2 Day Delivery)</b>: Select this option to track and guarantee your orders arrival within 2 business days of shipping.  Orders placed after 1:30 PM ET or on weekends and holidays should ship the next business day, unless otherwise noted.<p><strong>Note:</strong> This service is NOT available for orders sent to APO, FPO, P.O. Box addresses, outside of the 48 contiguous states, and U.S. possessions.</p></p>";
  } else if (whichOption == 'UPS_NxDay') {
    s = "<p><b>UPS NEXT Day Air (Next Business Day)</b>: Select this option to track and guarantee your orders arrival by the end of the next business day of shipping.  Orders placed after 1:30 PM ET or on weekends and holidays should ship the next business day, unless otherwise noted.<p><strong>Note:</strong> This service is NOT available for orders sent to APO, FPO, P.O. Box addresses, outside of the 48 contiguous states, and U.S. possessions.</p></p>";
  } else if (whichOption == 'Canada_FC') {
    s = "<p><b>Canada Standard First Class</b>: Orders shipped to Canada should be delivered within 4 to 8 business days depending on location.</p>";
  } else if (whichOption == 'INT') {
    s = "<p><b>All Other International Countries</b>: Delivery timeframe for orders shipped to other countries varies by destination.</p>";
  } else if (whichOption == 'INT_Priority') {
    s = "<p><b>Priority Mail International (6-10 Day Delivery)</b>: Orders shipped Priority Mail to international locations should be received within 6 to 10 business days based on destination location.</p>";
  } else if (whichOption == 'Delivered_By') {
    s = "<p>The \"Delivered By\" date is guaranteed when all items are \"In Stock\".  If any item is not \"In Stock\" we will hold your entire order and ship everything together once everything is in stock.  When an item is not \"In Stock\" the \"Delivered By\" date is simply an estimate based upon the availability date listed in the cart above.  This real-time information is accurate and up-to-date.  It is the same information available to Customer Service.</p>";
  } else {
    s = "No Help Available.";
  }

  tooltip(s, caller);
}
function tooltip(tip, caller) {
    var lefttpos = null;
    var toptpos = null;

    if ($('tooltip') != null) {
        $('tooltipcontent').set('html', tip);
    } else {
        var tooldiv = new Element('div');
        tooldiv.id = 'tooltip';
        tooldiv.injectInside(document.body);

        var tooldivcontent = new Element('div');
        tooldivcontent.id = 'tooltipcontent';
        tooldivcontent.set('html', tip);
        tooldivcontent.injectInside(tooldiv);

        var tooldivbot = new Element('div');
        tooldivbot.addClass('tooltipbottom');
        tooldivbot.injectInside(tooldiv);
    }

    if (caller == undefined || caller == null) {
        if ($$('span.tip').length > 0) {
            caller = $$('span.tip')[0];
        }
    }

    if (caller != null) {
        if (!Browser.Engine.trident) {
            lefttpos = caller.getPosition().x;
            toptpos = caller.getPosition().y;
        } else {
            lefttpos = getIELeft(caller);
            toptpos = getIETop(caller);
        }

        $('tooltip').setStyle('display', 'block');

        $('tooltip').setStyle('left', lefttpos - 6);
        $('tooltip').setStyle('top', (toptpos - $('tooltip').getCoordinates().height));
    }
}
function tooltiphtml(turl, caller) {
    var lefttpos = null;
    var toptpos = null;

    var tipReq = new Request.HTML({
        noCache: 'true',
        onSuccess: function(html) {
            $('tooltip').setStyle('display', 'block');

            $('tooltipcontent').empty();
            $('tooltipcontent').adopt(html);

            $('tooltip').setStyle('left', lefttpos - 6);
            $('tooltip').setStyle('top', (toptpos - $('tooltip').getCoordinates().height));

            if ($('tooltip').getPosition().y < 0) {
                $('tooltip').setStyle('top', 0);
            }

            $('tipclose').onclick = function() {
                $('tooltip').setStyle('display', 'none');
                $('tooltipcontent').empty();
            }
        },
        onFailure: function() {
            $('tooltip').set('text', 'The request failed.');
        }
    });

    if ($('tooltip') != null) {
        $('tooltipcontent').empty();
    } else {
        var tooldiv = new Element('div');
        tooldiv.id = 'tooltip';
        tooldiv.injectInside(document.body);

        var tooldivcontent = new Element('div');
        tooldivcontent.id = 'tooltipcontent';
        tooldivcontent.injectInside(tooldiv);

        var tooldivbot = new Element('div');
        tooldivbot.addClass('tooltipbottom');
        tooldivbot.injectInside(tooldiv);
    }
    tipReq.cancel();

    tipReq.send({url: turl });

    if (!Browser.Engine.trident) {
        lefttpos = caller.getPosition().x;
        toptpos = caller.getPosition().y;
    } else {
        lefttpos = getIELeft(caller);
        toptpos = getIETop(caller);
    }

    $('tooltip').setStyle('display', 'none');
    if (!Browser.Engine.trident) {
        lefttpos = caller.getPosition().x;
        toptpos = caller.getPosition().y;
    } else {
        lefttpos = getIELeft(caller);
        toptpos = getIETop(caller);
    }


    return false;
}
function getIETop(whichelement) {
    var toppos = whichelement.offsetTop;
    var parentelement = whichelement.offsetParent;
    while (parentelement != null) {
        toppos += parentelement.offsetTop;
        parentelement = parentelement.offsetParent;
    }
    return toppos;
}

function getIELeft(whichelement) {
    var leftpos = whichelement.offsetLeft;
    var parentelement = whichelement.offsetParent;
    while (parentelement != null) {
        leftpos += parentelement.offsetLeft;
        parentelement = parentelement.offsetParent;
    }
    return leftpos;
}
   
    
function updateShipping(anIndex, aCurrency) {
  var shippingAmount = shippingAmountArray[anIndex];
  if ($('shippingAmount') != null && $('totalDue') != null && shippingAmount != null) { 
    $('shippingAmount').set('html', aCurrency + addCommas(shippingAmount.toFixed(2)));
    $('totalDue').set('html', aCurrency + addCommas((totalDueMinusShipping + shippingAmount).toFixed(2)));
  }
}

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

var bbCurrency = "$";

var ScrollerBB = new Class({
  Implements: [Class.Occlude, Events, Options],
  options: {
    alignment: 'vertical',
    dragUpArrowClass: 'dragUpArrow',
    dragDownArrowClass: 'dragDownArrow',
    sliderClass: 'slider',
    knobClass: 'knob',
    scrollContainerClass: 'scrollContainer',
    scrollContentClass: 'scrollContent'
  },
  initialize: function(element, options) {
    var self = this;
    this.element = document.id(element);
    this.setOptions(options);
    if (this.occlude()) {
      return this.occluded;
    }
    this.buildList();
    this.steps = this.scrollContent.getDimensions().height;
    this.sliderClass = new Slider(self.slider, self.knob, {
      mode: self.options.alignment,
      wheel: true,
      steps: self.steps,
      onChange: function(value) {
        var offsetValue = 0;
        var containerAmmount = 0;
        var srollContentAmmount = 0;
        var styleToChange = '';
        if (self.options.alignment == 'vertical') {
          containerAmmount = self.scrollContainer.getDimensions().height;
          srollContentAmmount = self.scrollContent.getDimensions().height;
          styleToChange = 'margin-top';
        } else {
          containerAmmount = self.scrollContainer.getDimensions().width;
          srollContentAmmount = self.scrollContent.getDimensions().width;
          styleToChange = 'margin-left';
        }
        offsetValue = Math.ceil((srollContentAmmount - containerAmmount) / self.steps * value);
        if (offsetValue > 0) {
          self.scrollContent.setStyle(styleToChange, '-' + offsetValue + 'px');
        } else {
          self.scrollContent.setStyle(styleToChange, '0');
        }
        self.stopTimer();
		  }
    });
    this.sliderClass.setOptions(options);
    this.timer = null;
    this.attach();
    return this;
  },
  buildList: function() {
    this.scrollContent = new Element('div', {
      'class': this.options.scrollContentClass
    }).wraps(this.element);
    this.scrollContainer = new Element('div', {
      'class': this.options.scrollContainerClass + ' ' + this.options.alignment
    }).wraps(this.scrollContent);
    this.dragUpArrow = new Element('div', {
      'class': this.options.dragUpArrowClass + ' ' + this.options.alignment
    }).inject(this.scrollContainer, 'after');
    this.slider = new Element('div', {
      'class': this.options.sliderClass + ' ' + this.options.alignment
    }).inject(this.dragUpArrow, 'after');;
    this.knob = new Element('div', {
      'class': this.options.knobClass
    }).inject(this.slider);
    this.dragDownArrow = new Element('div', {
      'class': this.options.dragDownArrowClass + ' ' + this.options.alignment
    }).inject(this.slider, 'after');
    if (this.options.alignment == 'vertical') {
      this.dragUpArrow.position({
        relativeTo: this.scrollContent,
        position: 'topRight'
      });
      //this.scrollContainer.setStyle('width', this.element.getDimensions().width - this.slider.getDimensions().width + 'px');
      this.slider.setStyle('height', this.scrollContainer.getDimensions().height - this.dragUpArrow.getDimensions().height -
        this.dragDownArrow.getDimensions().height + 'px');
      this.slider.position({
        relativeTo: this.dragUpArrow,
        position: 'bottomLeft'
      });
      this.dragDownArrow.position({
        relativeTo: this.slider,
        position: 'bottomLeft'
      });
    } else {
      this.dragUpArrow.position({
        relativeTo: this.scrollContent,
        position: 'leftBottom'
      });
      //this.scrollContainer.setStyle('width', this.element.getDimensions().width - this.slider.getDimensions().width + 'px');
      this.slider.setStyle('width', this.scrollContainer.getDimensions().width - this.dragUpArrow.getDimensions().width -
        this.dragDownArrow.getDimensions().width + 'px');
      this.slider.position({
        relativeTo: this.dragUpArrow,
        position: 'rightTop'
      });
      this.dragDownArrow.position({
        relativeTo: this.slider,
        position: 'rightTop'
      });
    }
    return this;
  },
  doTimer: function(sign) {
    this.adjustSlider(sign);
    return this;
  },
  adjustSlider: function(sign) {
    if (sign == 'plus') {
      this.sliderClass.set(this.sliderClass.step++);
      this.sliderClass.fireEvent('onChange', this.sliderClass.step++);
    } else {
      this.sliderClass.set(this.sliderClass.step--);
      this.sliderClass.fireEvent('onChange', this.sliderClass.step--);
    }
    this.timer = this.adjustSlider.delay(25, this, sign);
    return this;
  },
  stopTimer: function() {
    $clear(this.timer);
    return this;
  },
  attach: function() {
    var self = this;
    self.dragUpArrow.addEvents({
      'mousedown': function(){self.doTimer('minus')},
      'mouseup': function(){self.stopTimer()},
      'mouseout': function(){self.stopTimer()}
    });
    self.dragDownArrow.addEvents({
      'mousedown': function(){self.doTimer('plus')},
      'mouseup': function(){self.stopTimer()},
      'mouseout': function(){self.stopTimer()}
    });
    self.sliderClass.attach();
    return self;
  },
  detach: function() {
    var self = this;
    self.dragUpArrow.removeEvents({
      'mousedown': function(){self.doTimer('minus')},
      'mouseup': function(){self.stopTimer()},
      'mouseout': function(){self.stopTimer()}
    });
    self.dragDownArrow.removeEvents({
      'mousedown': function(){self.doTimer('plus')},
      'mouseup': function(){self.stopTimer()},
      'mouseout': function(){self.stopTimer()}
    });
    self.sliderClass.attach();
    return self;
  }
});

