/*
 * Copyright 2006, Jeffrey Palm.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

var SQUARE = 1;
var states = new Array();

// Create the paypal domain based on the debug flag
var PAYPAL;
if (DEBUG) {
  PAYPAL = 'developer.paypal.com';
} else {
  PAYPAL = 'www.paypal.com';
}

function show(tag) {
  if (!states[tag]) states[tag] = 'hidden';
  if (states[tag] != 'shown') {
    states[tag] = 'shown';
    doAppear(tag);
  }
}

function hide(tag) {
  if (!states[tag]) states[tag] = 'shown';
  if (states[tag] != 'hidden') {
    states[tag] = 'hidden';
    doFade(tag);
  }
}

// To keep multiple currencies
var MULTIPLE_CURRENCIES = true;
var currentCurrency = "USD"; // we'll start with that

function getCurrentCurrencySign() {
  return getCurrencySign(currentCurrency);
}

function getCurrencySign(cur) {
  var signs = {
    USD: "$"
    ,AUD: "$"
    ,CAD: "$"
    ,EUR: "&#8364;"
    ,GBP: "&pound;"
    ,JPY: "&yen;"
  };
  var sign = signs[cur];
  return sign;
}

function getPriceForCurrentCurrency(price) {
  return getPriceForCurrency(price,currentCurrency);
}

function getPriceForCurrency(price,cur) {

  // This is for gift certificates
  if (price < 0) return 0;

  var exchanges = {
    USD:  1
    ,AUD: 1.30685
    ,CAD: 1.1209
    ,EUR: 0.781555 
    ,GBP: 0.529717
    ,JPY: 110.89
  };
  var ex = exchanges[currentCurrency];
  var newPrice = price * ex;
  return newPrice;
}

/**
 * Span Price Currency -> _
 */
function updatePrices(s,originalPrice,cur) {
  currentCurrency = cur;
  //
  // Change the current price on the page and
  // in the form
  //
  // Taken from: http://www.x-rates.com/
  //
  var newPrice = getPriceForCurrency(originalPrice,cur);
  var newFormattedPrice = formatPrice(newPrice);
  //
  // Get the new symbol
  //
  var sign = getCurrencySign(cur);
  //
  // Now insert this price in the page and in the paypal button thingy
  //
  $("buttonAmount").value = newFormattedPrice;
  $("buttonCurrency").value = currentCurrency;
  $("productPriceSpan"+s).innerHTML = sign + newFormattedPrice;
}

/**
 * Double[original price] Span -> HTML
 */
function currencyChanger(price,ss) {
	
  if (!MULTIPLE_CURRENCIES) return "";

  function addCur(cur,str) {
    var t = '<option value="' + cur + '"';
    if (cur == currentCurrency) t += ' selected';
    t += '>' + str + '</option>';
    return t;
  }

  var s = ' &nbsp; <select id="" name="currency_code" class="tbox" '
    +     'onChange="updatePrices(' + ss + ',' + price 
    +     ',this.options[this.selectedIndex].value);">';
  s += addCur("USD","U.S. Dollars");
  s += addCur("AUD","Australian Dollars");
  s += addCur("CAD","Canadian Dollars");
  s += addCur("EUR","Euros");
  s += addCur("GBP","Pounds Sterling");
  s += addCur("JPY","Yen");
  s += '</select>';
  return s;
}

function formatPrice(price) {
  //
  // no decimals for Yens
  var format;
  if (currentCurrency != "JPY") {
    format = "%.2f";
  } else {
    format = "%.2f";
  }
  s = sprintf(format,price);
  s = s.replace(/\.00/,'');
  return s;
}

/**
 * This is true when the collection is hidden.
 * I keep track of this so that even if a collection is being shown
 * the collections may not be showing, so we want to still 're-show'
 * that collection.  This was a SHITTY explanation.
 */
var collectionsHidden;
function swapCollection(newP,newSection) {	
  if (newP == 'under100') {
    var search = String(document.location.search);
    if (search && search.match(/_under_100/)) {
      alert("We don't do shit under $100, stupid head");
    }
  }
  //
  // we set this to 1 because not all the types
  // have the same number of sections
  //
  if (!newSection) newSection = 1;
  if (newP == currentCollectionType
      && newSection == currentCollectionSection
      && !collectionsHidden) {
    return;
  }
  //
  // Make all the of the new images not hidden and have src, no use in hiding
  // the old ones
  //
  hideCollection(currentCollectionType,currentCollectionSection);
  showCollection(newP,newSection);
}

function addImages(type) {
  for (var i=0; i<9; i++) {
    var img = $(createImgId(type,i));
    var imgSrc = getProductIdFromType(type,i);
    img.src = getImageThumb(imgSrc);
    img.style.display = "normal";
  }
}

function typeString(typeName,section) {
  return typeName + (section ? section : 1);
}

function hideCollection(typeName,section) {
  hide('productsPane_'+typeString(typeName,section));
}

/*
 * TODO: Why weren't these defined!!!
 */
PREFIX = '/';
SUFFIX = '.gif';

function getImageSmallThumb(n) {
  if (ROOSTER_SAUCE) {
    return "/rooster-75.png";
  }
  return PREFIX+"HiRez/square/75/" + n + SUFFIX;
}

function getImageFull(n) {
  if (ROOSTER_SAUCE) {
    return "/rooster-459.png";
  }
  if (SQUARE) {
    return PREFIX+"HiRez/square/459/" + n + SUFFIX;
  } else {
    return PREFIX+"HiRez/15/" + n + SUFFIX;
  }
}

function getImageOriginal(n) {
  return PREFIX+"HiRez/" + n + SUFFIX;
}

function getImageTiny(n) {
  if (ROOSTER_SAUCE) {
    return "/rooster-75.png";
  }
  return PREFIX+"HiRez/square/75/" + n + SUFFIX;
}

/**
 * Will try to show the last collection, if there wasn't one
 * show the first -- i.e. right now necklaces
 */
function showLastCollection() {
  var c = currentCollectionType ? currentCollectionType : 'fallPreview';
  showCollection(c);
}

var currentCollectionType;
var currentCollectionSection;

/**
 * Shows the collectio with String <code>type</code> and
 * 1..getNumSections(type)
 *
 * @param typeName    String type
 * @param section     1..getNumSections(type)
 */
function showCollection(typeName,section) {

  ensureSlideShowEnded();

  currentCollectionType = typeName;
  currentCollectionSection = section;
  if (!section) section = 1;

  recordPageView(typeName,section);

  var type =  typeString(typeName,section);
  //
  // TODO: This is a total hack to have the page 1 2 ... N box at the
  //       top right for necklaces. Abstract this out to automate it,
  //       poohead!
  //       @pageHack
  //
  function sn(type,n,s) {
    return '<a href="javascript:swapCollection(\'' + type + '\',' + n + ')">' + (s==0 ? n : s) + '</a>';
  }
  //
  // print out the sections pager if we have more than one
  // section.  remember these will be shown as 1..N but are indexed
  // from 0..N-1
  //
  var numSections = getNumSections(typeName);
  if (numSections > 1) {
    //
    // put arrows in for pagination
    //
    var ltChar = "&#171;";
    var gtChar = "&#187;";
    var html = 'page ';
    html += (section>1 ? sn(typeName,section-1,ltChar) : ltChar) + ' ';
    for (var i=1; i<=numSections; i++) {
      html += (i==section ? "<u>"+i+"</u>" : sn(typeName,i,0)) + ' ';
    }
    html += section < numSections ? sn(typeName,section+1,gtChar) : gtChar;
    $('pagesBox').innerHTML = html;
  } else {
    $('pagesBox').innerHTML = '';
  }
  //
  // we do this as a sanity check, though if I were lazily creating the page
  // this is where it would be
  //
  var ids = getProductIDs(typeName,section);
  for (var i=0; i<ids.length; i++) {
    var n = '_' + type + '_' + ids[i];
    if (!document.getElementById('collectionHref'+n)) {
      alert(type + ":" + 'collectionHref'+n + " not found!");
      return;
    }
    var img = $(createImgId(type,i));
    var id = ids[i];
    //img.alt = getProduct(id).getName();
    img.alt = "";
    img.src = getImageThumb(id);
    //$(createImgId(type,i)).alt = getProduct(ids[i]).getName();
    $(createImgId(type,i)).alt = "";
		
  }
  //
  // Now actually do something
  //
  hideProduct();
  hideCurrentPage();
  show('productsPane_'+type);
  show('rightnav');

  collectionsHidden = false;
}

function hideProduct() {
  var s;
  s=1;
  hide('productImgPane'+s);
  hide('descriptionPane'+s);
  hide('pricePane'+s);
  s=2;
  hide('productImgPane'+s);
  hide('descriptionPane'+s);
  hide('pricePane'+s);
}

/**
 * @return the next product id in <code>type</code> or <code>-1</code>
 *         for the end of the line
 */
function getNextProductID(type,n) {
  var ids = getProductIDs(type); // we want all of them
	
  // find the next and previous links
  // TODO: This is slow and sucks
  var index = -1;
  for (var i=0; i<ids.length; i++) {
    if (ids[i] == n) {
      index = i;
      break;
    }
  }
  var next = index<ids.length-1 ? ids[index+1] : -1;
  return next;
}

/**
 * @return the previous product id in <code>type</code> or <code>-1</code>
 *         for the start of the line
 */
function getPrevProductID(type,n) {
  var ids = getProductIDs(type); // we want all of them
	
  // find the next and previous links
  // TODO: This is slow and sucks
  var index = -1;
  for (var i=0; i<ids.length; i++) {
    if (ids[i] == n) {
      index = i;
      break;
    }
  }
  var prev = index>0 ? ids[index-1] : -1;
  return prev;
}

// we'll use a back buffer so we can
// fade the product pane in/out
// TODO: Ii should really abstract this into
//       a pane

var currentProductPane;
var productFront = true;

// keep track of this for the slide show
var currentProductID;
var currentProductType;
var currentProductSection;

function _showProduct(n,swap) {
  try {
    _showProduct(n,swap);
  } catch (e) {handle(e);}
}

/**
 * Show product with integer id <code>n</code>.
 */
function showProduct(n,swap) {

  // Record the click
  recordProductView(n);
  
  var s = productFront ? '1' : '2';
  var t = productFront ? '2' : '1';

  var name = getName(n);
  var retail = getPrice(n);
  var subtitle = getSubtitle(n);

  //
  // forget this type
  //
  var typeAndSection = getTypeAndSectionFromProductID(n,
						      currentProductType,
						      currentCollectionSection);
  var type = typeAndSection[0];
  var section = typeAndSection[1];

  currentProductType = type;
  currentProductSection = section;
  currentProductPane = type;
  currentProductID = n;
  $('productImg'+s).src = getImageFull(n);
  $('productImg'+s).border = "0px";
  //
  // maybe they have a special offer
  //
  var price;
  //
  // Skip the mother's day offer
  //
  var multiply = 1;
  //
  // Look for discounts
  //
  if (getProduct(n).getDiscount() > 0) {
    multiply = (100-getProduct(n).getDiscount()) / 100;
  }
  //
  // Look for an offer in OFFERS
  //
  // we'll allow all offers now
  //else if (!getProduct(n).isPreview()) {
  else {
    for (i=0; i<OFFERS.length; i++) {
      offer = OFFERS[i];
      try {
        if (offer.isSet==1) {
          multiply = (100-offer.getDiscount())/100;
	}
      } catch (e) {handle(e);}
    }
  }

  //XXX
  if (currentCollectionType)       type = currentCollectionType;
  if (currentCollectionSection) section = currentCollectionSection;

  var origPrice = retail;

  // Do NOT apply a discount for a product that doesn't do discounts...
  if (!getProduct(n).usesDiscount()) {
    //multiply = 1;
  }
  price = multiply*retail;

  $('productPriceSpan'+s).innerHTML = "";
  if (multiply != 1) {
    discount = 100-100*multiply;
    $('productPriceSpanPre'+s).innerHTML = "<font color=red>(" + discount + "% off)</font></br><strike>$" 
      +                                    formatPrice(origPrice) + "</strike>&nbsp;&nbsp;";
  } else {
    $('productPriceSpanPre'+s).innerHTML = "";
  }
	
  $('productPriceSpan'+s).innerHTML += getCurrentCurrencySign() + formatPrice(getPriceForCurrentCurrency(price));
  $('productPriceChanger'+s).innerHTML = currencyChanger(price,s);

	
  $('productName'+s).innerHTML = name;
  $('productDescription'+s).innerHTML = getDescription(type,n);
  $('continueShoppingHref'+s).href = "javascript:showCollection('" + type + "', " +section+");";
  //
  // we want to back sure to go to the right collection -- i.e. if we
  // were on necklaces and got here we want to go to necklaces and not
  // the preview section
  //
  $('continueShoppingHref'+s).innerHTML = "&#171; Back to " + getProductTypeNameFromType(type);
  //
  // set up the nav links
  //
  var ids = getProductIDs(type);
	
  // find the next and previous links
  // TODO: This is slow and sucks
  var index = -1;
  for (var i=0; i<ids.length; i++) {
    if (ids[i] == n) {
      index = i;
      break;
    }
  }
  var prev = getPrevProductID(type,n);
  var next = getNextProductID(type,n);

  if (prev != -1) {
    var p = $('navPrevLink'+s);
    p.removeChild(p.firstChild);
    var link = $n('a',p);
    link.href = 'javascript:navLink(' + prev + ')';
    link.appendChild($t('Previous'));
  } else {
    var p = $('navPrevLink'+s);
    if (p.firstChild) p.removeChild(p.firstChild);
    p.appendChild($t('Previous'));
  }

  if (next != -1) {
    var p = $('navNextLink'+s);
    if (p.firstChild) p.removeChild(p.firstChild);
    var link = $n('a',p);
    link.href = 'javascript:navLink(' + next + ')';
    link.appendChild($t('Next'));
  } else {
    var p = $('navNextLink'+s);
    if (p.firstChild) p.removeChild(p.firstChild);
    p.appendChild($t('Next'));
  }
  //
  // slide show
  //
  if (slideShowGoing) {
    createStopSlideShowLink(s);
  } else {
    createStartSlideShowLink(s);
  }
  //
  // view larger image
  //
  {
    if (false) {
      var p = $('fullImageLink'+s);
      if (p.firstChild) p.removeChild(p.firstChild);
      var link = $n('a',p);
      link.target = '_';
      link.href = getImageOriginal(n);
      link.appendChild($t('View full image'));
    }
  }
  //
  // permalink
  //
  $('permaLink'+s).href = '/' + n;
  //
  // buttons
  //
  $('buyButtons'+s).innerHTML = createButtons(name,n,price);
  //
  // panes
  //
  show('productImgPane'+s);
  show('descriptionPane'+s);
  show('pricePane'+s);
  hide('productImgPane'+t);
  hide('descriptionPane'+t);
  hide('pricePane'+t);
  //
  // we want to hide this guy as fast as we can so that the new image
  // will show up
  //
  $('productImg'+t).src = "";
  productFront = !productFront;
  hide('rightnav');
  hideProducts();
  hideCurrentPage();
}

function navLink(id) {
  ensureSlideShowEnded();
  showProduct(id,true);
}

function hideProducts() {
  if (currentCollectionType) hideCollection(currentCollectionType);
  collectionsHidden = true;
  $('pagesBox').innerHTML = '';
}

function showCurrentPage() {
  if (currentPage) show(currentPage);
}

function hideCurrentPage() {
  if (currentPage) hide(currentPage);
  currentPage = 0;
}

/**
 * Show the pane called page + 'Page'
 */
var currentPage;
function showPage(page) {
  var p = page + 'Page';
  recordPageView(page,1);
  if (currentPage == p) return; // it's already showing
  show('rightnav');
  show(p);
  hideCurrentPage();
  hideProducts();
  currentPage = p;
}

/*
 * We're checking for the existance of 'p' in the following because in
 * the iphone pages, we won't have a product to get the subtitle.
 */

function getPrice(n) {
  if (TESTING) return 0.01;
  var p = getProduct(n);
  return !p ? '' : (WHOLESALE ? p.getWholesale() : p.getPrice());
}

function getName(n) {
  var p = getProduct(n);
  return !p ? '' : p.getName();
}

function getSubtitle(n) {
  var p = getProduct(n);
  return !p ? '' : p.getSubtitle();

}

function getDescription(type,n) {
  var p = getProduct(n);
  return !p ? '' : p.getDescription();
}

// --------------------------------------------------
// Slide show
// --------------------------------------------------

var slideShowGoing = false;
var SLIDE_SHOW_TIME = 5; // secs

function nextSlideShow(type,n) {

  if (!slideShowGoing) return;

  showProduct(n,true);
  var next = getNextProductID(type,n);
  if (next != -1) {
    setTimeout('nextSlideShow("' + type + '",' + next + ')',SLIDE_SHOW_TIME*1000);
  }

}
function startSlideShow() {
  if (slideShowGoing) return;

  type = currentProductType;
  n = currentProductID;

  slideShowGoing = true;
  nextSlideShow(type,n);

  var s = productFront ? '2' : '1';  // there are reversed because we already reset it
  createStopSlideShowLink(s);

}

function ensureSlideShowEnded() {
  stopSlideShow(0,0);
}

function stopSlideShow(type,n) {
  if (!slideShowGoing) return;

  var s = productFront ? '2' : '1';  // there are reversed because we already reset it
  createStartSlideShowLink(s);

  slideShowGoing = false;
}


function createStartSlideShowLink(s) {
  var p = $('slideShowLink'+s);
  p.removeChild(p.firstChild);
  var link = $n('a',p);
  link.href = 'javascript:startSlideShow("' + currentProductType + '",' + currentProductID + ')';
  link.appendChild($t('Start slide show'));
}

function createStopSlideShowLink(s) {
  var p = $('slideShowLink'+s);
  p.removeChild(p.firstChild);
  var link = $n('a',p);
  link.href = 'javascript:stopSlideShow("' + currentProductType + '",' + currentProductID + ')';
  link.appendChild($t('Stop slide show'));
}


// --------------------------------------------------
// Buying buttons
// --------------------------------------------------

function createButtons(name,n,price) {
  var s = shoppingCartButton(name,n,price);
  //if (BUYNOW) s += buyNowButton(name,n,price);
  return s;
}

function oss(n,subtitle) {
  var s ='';
  //
  // First add the options
  //
  s += '<input type="hidden" name="on0" value="option">';
  if (!subtitle) {
    subtitle = getSubtitle(n);
  }
  var DEFAULT = '<input type="hidden" name="os0" value="none">';
  if (!subtitle) {
    s += DEFAULT;
  } else {

    var opts = subtitle.split(',');

    if (!opts || opts.length==0) return s+DEFAULT;
		
    s += '<select class="tbox" valign="top" name="os0">';
    for (var i=0; i<opts.length; i++) {
      // remove white space in the front and end
      var opt = opts[i].replace(/$\s+/,'').replace(/\s+^/,'');
      s += '<option value="' + opt + '">' + opt + '</option>';
    }
    s += '</select> ';
  }
  //
  // Now add the offer code
  //
  s += '<input type="hidden" name="on1" value="offerCode">';
  s += '<input type="hidden" name="os1" value="' + OFFER_CODE + '">';
  return s;
}

/**
 * Span Price Currency -> _
 */
function giftCertificateUpdatePrices(s,cur) {

  var originalPrice = $(s).value;

  currentCurrency = cur;
  //
  // Change the current price on the page and
  // in the form
  //
  // Taken from: http://www.x-rates.com/
  //
  var newPrice = getPriceForCurrency(originalPrice,cur);
  var newFormattedPrice = formatPrice(newPrice);
  //
  // Now insert this price in the page and in the paypal button thingy
  //
  $(s).value = newFormattedPrice;
}

/**
 * Double[original price] Span -> HTML
 */
function giftCertificateCurrencyChanger(ss) {
	
  if (!MULTIPLE_CURRENCIES) return "";

  function addCur(cur,str) {
    var t = '<option value="' + cur + '"';
    if (cur == currentCurrency) t += ' selected';
    t += '>' + str + '</option>';
    return t;
  }

  var s = ' &nbsp; <select id="" name="currency_code" class="tbox" '
    +     'onChange="$(\'giftCertificate_hosted_button_id\').value = this.options[this.selectedIndex].value;">';
  //
  // These are taken from paypal when creating buttons
  //
  s += addCur("1672146","U.S. Dollars");
  s += addCur("1672153","Australian Dollars");
  s += addCur("1672160","Canadian Dollars");
  s += addCur("1672165","Euros");
  s += addCur("1672172","Pounds Sterling");
  s += addCur("1672178","Yen");
  s += '</select>';
  return s;
}


/**
 * Validates that 'v' is a valid number.
 */
function validateNumber(v) {
  alert(v);
  if (!v.match(/\d+.\d?\d?/)) {
    $('giftCertificateError').innerHTML = 'Please enter a valid currency amount';
    return false;
  }
  $('giftCertificatePrice').value = v;
  $('giftCertificateAmount').value = v;
  return true;
}

function debugAjax(msg) {
  var search = String(document.location.search);
  if (search && search.match(/_debug_ajax/)) {
    alert(msg);
  }
}

function ajax(url) {
  try {
    new Ajax.Request(url, {
	method: 'get',
	  onSuccess: function(transport){
	  var response = transport.responseText || "no response text";
	  debugAjax(response);
	}
        
    });
  } catch (e) {
    // ignore -- don't know why this would happen
  }
}

/**
 * Records that someone clicked buy to go to paypal.
 * @param v product id or -1 for gift certificates
 */
function recordBuyClick(v) {
  ajax('/record_buyclick.php?item_number=' + v);
}

/**
 * Records that someone viewed this type at this page.
 * @param type product type
 * @param page page number
 */
function recordPageView(type,page) {
  ajax('/record_pageview.php?type=' + type + '&page=' + page);
}

/**
 * Records that someone viewed this product.
 * @param id product id
 */
function recordProductView(id) {
  ajax('/record_productview.php?item_number=' + id);
}

function giftCertificateButton() { 
  return '<form id="giftCertificateForm" onsubmit="recordBuyClick(-1);" name="giftCertificateForm" action="https://' + PAYPAL + '/cgi-bin/webscr" method="post"  target="_blank">'
    //+ '<input id="giftCertificatePrice" class="tbox" style="text-align:right" type="text" size="20" value="100.00">'
    + '<br/>'
    + '<br/>'
    + '<input type="hidden" name="cmd" value="_s-xclick">'
    + '<input type="hidden" name="hosted_button_id" id="giftCertificate_hosted_button_id" value="1672146">'
    + '<input type="hidden" name="notify_url" value="http://shopvale.com/notify_gift.php">'
    + '<input type="hidden" name="return" value="http://shopvale.com/gc_success.php">'
    + '<input type="hidden" id="giftCertificateAmount" name="amount">'
    + (USE_PAYPAL_BUTTONS
       ?
       '<input type="image" src="https://' + PAYPAL + '/en_US/i/btn/btn_giftCC_LG.gif" border="0" name="submit" alt="Purchase" onsubmit="return validateNumber($(\'giftCertificatePrice\').value)">'
       :
       '<input class="button" type="submit" border="0" name="submit" alt="Purchase" value="Purchase" onsubmit="return validateNumber($(\'giftCertificatePrice\').value)">'
       )
    + '<img alt="" border="0" src="https://' + PAYPAL + '/en_US/i/scr/pixel.gif" width="1" height="1">'
    + giftCertificateCurrencyChanger("giftCertificatePrice")
    + '</form>'
    ;
}

function shoppingCartButton(name,n,price,subtitle) {

  return '<form id="shoppingCartForm" name="shoppingCartForm" onsubmit="recordBuyClick(' + n + ');" target="paypal" action="https://' + PAYPAL + '/cgi-bin/webscr" method="post">'
    + '<input class="tbox" size="2" value="1" name="quantity"> '
    + oss(n,subtitle)
    + (USE_PAYPAL_BUTTONS
       ? '<input class="" type="image" src="https://' + PAYPAL + '/en_US/i/btn/x-click-but22.gif" border="0" name="_submit" alt="Make payments with PayPal - it\'s fast, free and secure!">'
       : '<input class="button" type="submit" value="Add to Cart" name="_submit" alt="Make payments with PayPal - it\'s fast, free and secure!">'
       )
    + '<img alt="" border="0" src="https://' + PAYPAL + '/en_US/i/scr/pixel.gif" width="1" height="1"><input type="hidden" name="add" value="1">'
    + '<input type="hidden" name="cmd" value="_cart">'
    + '<input type="hidden" name="business" value="sales@shopvale.com">'
    + '<input type="hidden" name="item_name" value="' + name + '">'
    + '<input type="hidden" name="item_number" id="item_number" value="' + n + '">'
    + '<input type="hidden" name="notify_url" value="http://shopvale.com/notify.php">'
    + '<input type="hidden" name="amount" id="buttonAmount" value="' + price + '">'
    + '<input type="hidden" name="no_shipping" value="2">'
    + '<input type="hidden" name="return" value="http://shopvale.com/success.php">'
    + '<input type="hidden" name="no_note" value="1">'
    + '<input type="hidden" name="currency_code" id="buttonCurrency" value="' + currentCurrency + '">'
    + '<input type="hidden" name="bn" value="PP-ShopCartBF">'
    + '</form>'
    ;
}

function buyNowButton(name,n,price) {
  return '<form id="buyNowForm" name="buyNowForm" onsubmit="recordBuyClick(' + n + ');" action="https://' + PAYPAL + '/cgi-bin/webscr" method="post">'
    + oss(n)
    + '<input type="hidden" name="cmd" value="_xclick">'
    + '<input type="hidden" name="business" value="sales@shopvale.com">'
    + '<input type="hidden" name="item_name" value="' + name + '">'
    + '<input type="hidden" name="item_number" id="item_number" value="' + n + '">'
    + '<input type="hidden" name="notify_url" value="http://shopvale.com/notify.php">'
    + '<input type="hidden" name="amount" value="' + price + '">'
    + '<input type="hidden" name="no_shipping" value="2">'
    + '<input type="hidden" name="return" value="http://shopvale.com/success.php">'
    + '<input type="hidden" name="no_note" value="1">'
    + '<input type="hidden" name="currency_code" value="' + currentCurrency + '">'
    + '<input type="hidden" name="bn" value="PP-BuyNowBF">'

    + (USE_PAYPAL_BUTTONS
       ? '<input class="" type="image" src="https://' + PAYPAL + '/en_US/i/btn/x-click-but23.gif" border="0" name="submit" alt="Make payments with PayPal - it\'s fast, free and secure!">'
       : '<input class="button" type="submit" value="Buy Now" name="submit" alt="Make payments with PayPal - it\'s fast, free and secure!">'
       )
    + '<img alt="" border="0" src="https://' + PAYPAL + '/en_US/i/scr/pixel.gif" width="1" height="1">'
    + '</form>'
    ;
}


var Jeff = {};

if (Object.extend) {
  Jeff.ChangeColor = Class.create();
  Object.extend(Object.extend(Jeff.ChangeColor.prototype, Effect.Base.prototype), {
      initialize: function(element) {
	this.element = $(element);
	// make this work on IE on elements without 'layout'
	if(/MSIE/.test(navigator.userAgent) && (!this.element.hasLayout))
	  Element.setStyle(this.element, {zoom: 1});
	var options = Object.extend({
	    from: this.element.style.color || 0,
	    to:   3*256*256*256
	  }, arguments[1] || {});
	this.start(options);
      },
	update: function(position) {
	// convert to color
	var r = 0x66;
	var g = Math.round(position);
	var b = Math.round(position);
	var value = 'rgb(' + r + "," + g + "," + b + ')';
	Element.setStyle(this.element, {color: value});
      }
    });
}

