Professional Documents
Culture Documents
/*
cart headers:
you can set these to which ever order you would like, and the cart will displa
y the appropriate headers
and item info. any field you have for the items in the cart can be used, and
'Total' will automatically
be price*quantity.
there are keywords that can be used:
1) "_input" - the field will be a text input with the value set to the given
field. when the user
changes the value, it will update the cart. this can be useful for quantity
. (ie "Quantity_input")
2) "increment" - a link with "+" that will increase the item quantity by 1
3) "decrement" - a link with "-" that will decrease the item quantity by 1
4) "remove" - a link that will remove the item from the cart
5) "_image" or "Image" - the field will be an img tag with the src set to the
value. You can simply use "Image" if
you set a field in the items called "Image". If you have a field named some
thing else, like "Thumb", you can add
the "_image" to create the image tag (ie "Thumb_image").
6) "_noHeader" - this will skip the header for that field (ie "increment_noHe
ader")
*/
/******************************************************
add/remove items to cart
******************************************************/
me.add = function () {
var me=this;
/* load cart values if not already loaded */
if( !me.pageIsReady
) {
me.initializeView();
me.update();
}
if( !me.isLoaded
) {
me.load();
me.update();
}
var newItem = new CartItem();
/* check to ensure arguments have been passed in */
if( !arguments || arguments.length === 0 ){
error( 'No values passed for item.');
return;
}
var argumentArray = arguments;
me.checkout = function() {
if( simpleCart.quantity === 0 ){
error("Cart is empty");
return;
}
switch( simpleCart.checkoutTo ){
case PayPal:
simpleCart.paypalCheckout();
break;
case GoogleCheckout:
simpleCart.googleCheckout();
break;
case Email:
simpleCart.emailCheckout();
break;
default:
simpleCart.customCheckout();
break;
}
};
me.paypalCheckout = function() {
var me = this,
winpar = "scrollbars,location,resizable,status,width=800,height=600",
strn = "https://www.paypal.com/cgi-bin/webscr?cmd=_cart" +
"&upload=1" +
"&business=" + me.email +
"¤cy_code=" + me.currency,
counter = 1,
itemsString = "";
if( me.taxRate ){
strn = strn +
"&tax_cart=" + me.currencyStringForPaypalCheckout( me.taxCost );
}
for( var current in me.items ){
var item = me.items[current];
var optionsString = "";
for( var field in item ){
if( typeof(item[field]) != "function" && field != "id" && field != "price" &
& field != "quantity" && field != "name" && field != "shipping") {
optionsString = optionsString + ", " + field + "=" + item[field] ;
}
}
optionsString = optionsString.substring(2);
itemsString = itemsString
+ "&item_name_"
+ counter + "=" + item.name +
"&item_number_"
+ counter + "=" + counter +
"&quantity_"
+ counter + "=" + item.quantity +
"&amount_"
+ counter + "=" + me.currencyStringForPaypa
em.price ) +
"&on0_"
+ counter + "=" + "Options" +
"&os0_"
+ counter + "=" + optionsString;
counter++;
}
"item_name_"
"item_quantity_"
"item_price_"
+ counter, item.name
+ counter, item.q
+ counter, item.pric
"item_currency_"
+ counter, me.cur
"item_tax_rate_"
+ counter, me.tax
"_charset_", ""
) != "function" &&
"id"
&&
"quantity"
&&
"price" )
descriptionString = descriptionString.substring( 1 );
form.appendChild( me.createHiddenElement( "item_description_" + counter, desc
riptionString) );
counter++;
}
document.body.appendChild( form );
form.submit();
document.body.removeChild( form );
};
me.emailCheckout = function() {
return;
};
me.customCheckout = function() {
return;
};
/******************************************************
data storage and retrival
******************************************************/
/* load cart from cookie */
me.load = function () {
var me = this;
/* initialize variables and items array */
me.items = {};
me.total = 0.00;
me.quantity = 0;
/* retrieve item data from cookie */
if( readCookie('simpleCart') ){
var data = unescape(readCookie('simpleCart')).split('++');
for(var x=0, xlen=data.length;x<xlen;x++){
var info = data[x].split('||');
var newItem = new CartItem();
if( newItem.parseValuesFromArray( info ) ){
newItem.checkQuantityAndPrice();
/* store the new item in the cart */
me.items[newItem.id] = newItem;
}
}
}
me.isLoaded = true;
};
/******************************************************
view management
******************************************************/
me.initializeView = function() {
var me = this;
me.totalOutlets
= getElementsByClassName('simpleCart_total');
me.quantityOutlets
= getElementsByClassName('simpleCart_quantity');
me.cartDivs
= getElementsByClassName('simpleCart_items');
me.taxCostOutlets
= getElementsByClassName('simpleCart_taxCost');
me.taxRateOutlets
= getElementsByClassName('simpleCart_taxRate');
me.shippingCostOutlets
= getElementsByClassName('simpleCart_shippingCost');
me.finalTotalOutlets
= getElementsByClassName('simpleCart_finalTotal');
me.addEventToArray( getElementsByClassName('simpleCart_checkout') , simpleCart
.checkout , "click");
me.addEventToArray( getElementsByClassName('simpleCart_empty')
, simpleCart.e
mpty , "click" );
me.Shelf.readPage();
me.pageIsReady = true;
};
me.updateView = function() {
me.updateViewTotals();
if( me.cartDivs && me.cartDivs.length > 0 ){
me.updateCartView();
}
};
me.updateViewTotals = function() {
var outlets = [ ["quantity"
, "none"
] ,
["total"
, "currency"
] ,
["shippingCost"
, "currency"
] ,
["taxCost"
, "currency"
] ,
["taxRate"
, "percentage"
] ,
["finalTotal"
, "currency"
] ];
for( var x=0,xlen=outlets.length; x<xlen;x++){
var arrayName = outlets[x][0] + "Outlets",
outputString;
for( var element in me[ arrayName ] ){
switch( outlets[x][1] ){
case "none":
outputString = "" + me[outlets[x][0]];
break;
case "currency":
outputString = me.valueToCurrencyString( me[outlets[x][0]] );
break;
case "percentage":
outputString = me.valueToPercentageString( me[outlets[x][0]] );
break;
default:
outputString = "" + me[outlets[x][0]];
break;
}
me[arrayName][element].innerHTML = "" + outputString;
}
}
};
me.updateCartView = function() {
var newRows = [],
x,newRow,item,current,header,newCell,info,outputValue,option,headerInfo;
/* create headers row */
newRow = document.createElement('div');
for( header in me.cartHeaders ){
newCell = document.createElement('div');
headerInfo = me.cartHeaders[header].split("_");
newCell.innerHTML = headerInfo[0];
newCell.className = "item" + headerInfo[0];
for(x=1,xlen=headerInfo.length;x<xlen;x++){
if( headerInfo[x].toLowerCase() == "noheader" ){
newCell.style.display = "none";
}
}
newRow.appendChild( newCell );
}
newRow.className = "cartHeaders";
newRows[0] = newRow;
/* create a row for each item in the cart */
x=1;
for( current in me.items ){
newRow = document.createElement('div');
item = me.items[current];
for( header in me.cartHeaders ){
newCell = document.createElement('div');
info = me.cartHeaders[header].split("_");
switch( info[0].toLowerCase() ){
case "total":
outputValue = me.valueToCurrencyString(parseFloat(item.price)*parseInt(it
m.quantity,10) );
break;
case "increment":
outputValue = me.valueToLink( "+" , "javascript:;" , "onclick=\"simpleCar
.items[\'" + item.id + "\'].increment();\"" );
break;
case "decrement":
while( div.childNodes[0] ){
div.removeChild( div.childNodes[0] );
}
for(var j=0, jLen = newRows.length; j<jLen; j++){
div.appendChild( newRows[j] );
}
}
};
me.addEventToArray = function ( array , functionCall , theEvent ) {
for( var outlet in array ){
var element = array[outlet];
if( element.addEventListener ) {
element.addEventListener(theEvent, functionCall , false );
} else if( element.attachEvent ) {
element.attachEvent( "on" + theEvent, functionCall );
}
}
};
me.createHiddenElement = function ( name , value ){
var element = document.createElement("input");
element.type = "hidden";
element.name = name;
element.value = value;
return element;
};
/******************************************************
Currency management
******************************************************/
me.currencySymbol = function() {
switch(me.currency){
case JPY:
return "¥";
case EUR:
return "€";
case GBP:
return "£";
case USD:
case CAD:
case AUD:
case NZD:
case HKD:
case SGD:
return "$";
default:
return "";
}
};
me.currencyStringForPaypalCheckout = function( value ){
}
return false;
};
/******************************************************
Cart Update managment
******************************************************/
me.update = function() {
if( !simpleCart.isLoaded ){
simpleCart.load();
}
if( !simpleCart.pageIsReady ){
simpleCart.initializeView();
}
me.updateTotals();
me.updateView();
me.save();
};
me.updateTotals = function() {
me.total = 0 ;
me.quantity = 0;
for( var current in me.items ){
var item = me.items[current];
if( item.quantity < 1 ){
item.remove();
} else if( item.quantity !== null && item.quantity != "undefined" ){
me.quantity = parseInt(me.quantity,10) + parseInt(item.quantity,10);
}
if( item.price ){
me.total = parseFloat(me.total) + parseInt(item.quantity,10)*parseFloat(item
.price);
}
}
me.shippingCost = me.shipping();
me.taxCost = parseFloat(me.total)*me.taxRate;
me.finalTotal = me.shippingCost + me.taxCost + me.total - me.couponcode;
if (me.finalTotal <= 0) {
me.finalTotal = 0;
}
};
me.applydiscount = function() {
var ccode = document.getElementById('ccv').value;
if (ccode == "abc123") {
me.couponcode = 1;
alert("Discount Applied");
} else {
me.couponcode = 0;
}
document.getElementById('couponcode').innerHTML = "Discount: $" + me.couponcod
e.toFixed(2) + " <br />";
me.update();
}
me.shipping = function(){
if( parseInt(me.quantity,10)===0 )
return 0;
var shipping =
parseFloat(me.shippingFlatRate) +
parseFloat(me.shippingTotalRate)*parseFloat(me.total) +
parseFloat(me.shippingQuantityRate)*parseInt(me.quantity,10),
nextItem,
next;
for(next in me.items){
nextItem = me.items[next];
if( nextItem.shipping ){
if( typeof nextItem.shipping == 'function' ){
shipping += parseFloat(nextItem.shipping());
} else {
shipping += parseFloat(nextItem.shipping);
}
}
}
return shipping;
}
me.initialize = function() {
simpleCart.initializeView();
simpleCart.load();
simpleCart.update();
};
}
/*******************************************************************************
*************************
*
Cart Item Object
*******************************************************************************
*************************/
function CartItem() {
this.id = "c" + NextId++;
}
CartItem.prototype.set = function ( field , value ){
field = field.toLowerCase();
if( typeof( this[field] ) != "function" && field != "id" ){
if( field == "quantity" ){
value = value.replace( /[^(\d|\.)]*/gi , "" );
value = value.replace(/,*/gi, "");
value = parseInt(value,10);
} else if( field == "price"){
value = value.replace( /[^(\d|\.)]*/gi, "");
value = value.replace(/,*/gi , "");
value = parseFloat( value );
}
}
}
};
CartItem.prototype.parseValuesFromArray = function( array ) {
if( array && array.length && array.length > 0) {
for(var x=0, xlen=array.length; x<xlen;x++ ){
/* ensure the pair does not have key delimeters */
array[x].replace(/||/, "| |");
array[x].replace(/\+\+/, "+ +");
/* split the pair and save the unescaped values to the item */
var value = array[x].split('=');
if( value.length>1 ){
if( value.length>2 ){
for(var j=2, jlen=value.length;j<jlen;j++){
value[1] = value[1] + "=" + value[j];
}
}
this[ unescape(value[0]).toLowerCase() ] = unescape(value[1]);
}
}
return true;
} else {
return false;
}
};
CartItem.prototype.remove = function() {
simpleCart.remove(this.id);
simpleCart.update();
};
/*******************************************************************************
*************************
*
Shelf Object for managing items on shelf that can be added to cart
*******************************************************************************
*************************/
function Shelf(){
this.items = {};
}
Shelf.prototype.readPage = function () {
this.items = {};
var newItems = getElementsByClassName( "simpleCart_shelfItem" );
for( var current in newItems ){
var newItem = new ShelfItem();
this.checkChildren( newItems[current] , newItem );
this.items[newItem.id] = newItem;
}
};
Shelf.prototype.checkChildren = function ( item , newItem) {
for(var x=0;item.childNodes[x];x++){
if( this[field].value ){
valueString = this[field].value;
} else if( this[field].innerHTML ) {
valueString = this[field].innerHTML;
}
/* remove all characters from price except digits and a period */
valueString = valueString.replace( /[^(\d|\.)]*/gi , "" );
valueString = valueString.replace( /,*/ , "" );
break;
case "image":
valueString = this[field].src;
break;
default:
if( this[field].value ){
valueString = this[field].value;
} else if( this[field].innerHTML ) {
valueString = this[field].innerHTML;
} else if( this[field].src ){
valueString = this[field].src;
} else {
valueString = this[field];
}
break;
}
outStrings.push( field + "=" + valueString );
}
}
simpleCart.add( outStrings );
};
/*******************************************************************************
*************************
* Thanks to Peter-Paul Koch for these cookie functions (http://www.quirksmode.o
rg/js/cookies.html)
*******************************************************************************
*************************/
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
//******************************************************************************
*******************
/*
Developed by Robert Nyman, http://www.robertnyman.com
Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
var getElementsByClassName = function (className, tag, elm){
if (document.getElementsByClassName) {
getElementsByClassName = function (className, tag, elm) {
elm = elm || document;
var elements = elm.getElementsByClassName(className),
nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
returnElements = [],
current;
for(var i=0, il=elements.length; i<il; i+=1){
current = elements[i];
if(!nodeName || nodeName.test(current.nodeName)) {
returnElements.push(current);
}
}
return returnElements;
};
}
else if (document.evaluate) {
getElementsByClassName = function (className, tag, elm) {
tag = tag || "*";
elm = elm || document;
var classes = className.split(" "),
classesToCheck = "",
xhtmlNamespace = "http://www.w3.org/1999/xhtml",
namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespac
e)? xhtmlNamespace : null,
returnElements = [],
elements,
node;
for(var j=0, jl=classes.length; j<jl; j+=1){
classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + "
')]";
}
try
{
elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceRes
olver, 0, null);
}
catch (e) {
elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, nul
l);
}
while ((node = elements.iterateNext())) {
returnElements.push(node);
}
return returnElements;
};
}
else {
getElementsByClassName = function (className, tag, elm) {