/****************************************************************
Copyright (c) <year> <copyright holders>

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.
******************************************************************/

function cart() {
	
	// paypal values
	this.currency = 'AUD';
	this.country_code = 'AU';
	
	
	
	//initialisation
    this.totalItems = 0;
	this.totalPrice	= 0.00;
	this.items = [];
	this.ItemColumns = ['Image','Name','Quantity', 'Price','Options','Total'];
	this.totalShippingCost = null;
	
	this.sliderOffset = 0;
	this.item_width = 120; // width including padding of an item in as it appears in the cart
	this.item_area_width = 760;
	this.slider_button_width = 30;
	
	
	/*
	 *	function to initialize the cart when the page is loaded
	 */
	this.initialize = function () {
		if( !readCookie("simpleCart") ) {
			this.totalItems  = 0;
			this.totalPrice = 0.00;
		} else {
			data = readCookie("simpleCart").split("&");
			this.totalItems = data[0]*1;
			this.totalPrice = data[1]*1;
			for(x=2;x < (data.length);x++) {
				newItem = new item();
				itemData = data[x].split(",");
				i=0;
				for(i=0;i<itemData.length;i++) {
					pair = itemData[i].split('=');
					newItem.addValue(pair[0],pair[1]);
				}
				if(!newItem.getValue('name') || !newItem.getValue('price') || !newItem.getValue('quantity')) {
					alert("item must have price, name, and quantity!");
					return false;
				}
				this.items[x-2] = newItem;
			}
			
		}
		this.setUpEvents();
		this.updateCookie();
		this.updatePageElements();
		return;
	};
	
	/* the two functions below are event listener functions.  when using 
	 * addEventListener, 'this' in the scope of the called function is either 
	 * the element with the listener or the document (in IE).  they simply avoid 
	 * using the this variable due to this scope issue.
	 */
	
	this.checkOutEvent = function() {
		simpleCart.checkOut();
		return false;
	};
	
	this.emptyEvent = function() {
		simpleCart.empty();
		return false;
	};
	
	/* set up the Event Listeners for the empty cart and checkout
	 * links in the page. 
	 */
	
	this.setUpEvents = function() {
			var x=0,element,elements = getElementsByClassName('simpleCart_total');
			
	$('.simpleCart_checkout').bind('click', function() { simpleCart.checkOut(); });
	$('.simpleCart_checkout').colorbox({width:"500px", height:"220px", inline:true, href:"#paypal"});
 
			x=0;
			elements = getElementsByClassName('simpleCart_empty');
			for( x=0;x<elements.length;x++) {
				element = elements[x];
				if( element.addEventListener ) {
					element.addEventListener("click", this.emptyEvent, false );
				} else if( element.attachEvent ) {
                    element.attachEvent( "onclick", this.emptyEvent );
				}
			}
			
			
			return;
	};
	

	
	/*	add an item to the shopping cart with the name and price.
	 *  if there is an item with the same value for every field, 
	 *  the quantity for that item will increase.  if any field 
	 *  is different, the item will be considered new.  if a quantity
	 *  is specified, that will be the quanitity of that item that 
	 *  that will be added.
	 */	
	this.add = function() {
		newItem = new item();
		var x=0;
		for(x=0;x<arguments.length;x++){
			temp = arguments[x];
			data = temp.split('=');
			newItem.addValue(data[0],data[1]);
		}
		if(!newItem.getValue('name') || !newItem.getValue('price')) {
			alert('Item must have name and price to be added to the cart!');
			return false;
		}
		if(!newItem.getValue('quantity')) {
			newItem.addValue('quantity',1);
		}
		
		
		// search to see if this product is already in the cart
		var x=0, item_index = -1;
		for( x=0;x < this.items.length;x++ ) {
			tempItem = this.items[x];
			if( tempItem.equalTo(newItem) ) {
				item_index = x;
			}
		}
		
		
		if( item_index == -1 ) { // is new
			this.items[this.items.length] = newItem;
			this.totalPrice = this.totalPrice + parseFloat(newItem.getValue('price'));
		    this.totalItems = this.totalItems + newItem.getValue('quantity');
		} else {
		
			this.changeQuantity (item_index,  newItem.getValue('quantity'));
		
		}
		
		this.updateCookie();
		this.updatePageElements();
		this.slideLeft(true);
		
		return;
	};
	
	

	
	/* this function will update the cookie used to store the cart info
	 * when anything is changed in the cart. 
	 */ 
	this.updateCookie = function () {
		cookieString = String(this.totalItems) + "&" + String(this.totalPrice);
		x=0;
		for(x=0;x<this.items.length;x++ ) {
			tempItem = this.items[x];
			cookieString = cookieString + "&" + tempItem.cookieString();
		}
		createCookie("simpleCart", cookieString, 30 );
	};
	
	// reset the variables of the cart, update the cookies
	this.empty = function () {
		this.items = [];
		this.totalItems = 0;
		this.totalPrice = 0.00;
		this.updateCookie();
		this.updatePageElements();
		return false;
	};
	
 
	
	this.removeEmptyProducts = function () {
	
		var temp = [];
		for(x=0; x < this.items.length;x++ ) {
		    if (parseInt((this.items[x].getValue('quantity'))) > 0) {
		       temp.push(this.items[x]);
		    }
		}
		
		this.items = temp;
	
	
	}
	
	
	// determine if there are any options 
	this.options = function() {
		var x=0;
		for(x=0;x<this.items.length;x++) {
			var temp = this.items[x];
			if( temp.optionList() ) {
				return true;
			}
		}
		return false;
	};
	
	this.updatePageElements = function () {
	
		var items_holder = document.getElementById('simpleCart_items');
		
		
		// make sure the width is a multiple of the item width so the button sits flush with the edge (plus 5 buffer)
		this.item_area_width = (Math.floor(this.item_area_width / this.item_width)) * this.item_width;
		$('#simpleCart_items').width(this.item_area_width);
        this.correctOffset();
		

	    $(items_holder).empty();
	
	    // create a div for each item
	    x=0;
	    for( x=0;x<this.items.length;x++ ) {
            tempItem = this.items[x];
				
            item_container = document.createElement('div');
            $(item_container).css('left', (this.item_width * x + this.sliderOffset)+'px')
            details = document.createElement('div');

            details.className = "itemDetails";
				
				
            // summary bits
            s_name = document.createElement('div');
            s_img = document.createElement('div');
				
            // details bits
            d_name = document.createElement('div');
            d_price = document.createElement('div');
            d_qty = document.createElement('div');
            d_img = document.createElement('div');
				
            s_name.className = "itemSummary_name";
            s_img.className = "itemSummary_img";
				
            d_name.className = "itemDetails_name";
            d_price.className = "itemDetails_price";
            d_qty.className = "itemDetails_qty";
            
				
            s_img.innerHTML = '<img src="http://'+this.siteroot+'img/'+tempItem.getValue('image')+'" alt="" />';
            s_name.innerHTML = this.shortenName(tempItem.getValue('name'), 18);
	
            d_name.innerHTML = tempItem.getValue('name');
            d_price.innerHTML = this.returnFormattedPrice( tempItem.getValue('price')) + " each";
				
						
			d_qty.innerHTML='<input type="button" class="qty_change" value="-" onclick="simpleCart.qtyLess('+x+'); return false;" /><input type="text" class="qty_field" id="qty_field_'+x+'" readonly="readonly" value="'+tempItem.getValue("quantity")+'" /><input type="button" class="qty_change" value="+" onclick="simpleCart.qtyMore('+x+'); return false;"/><br/><span>qty</span>';


            item_container.appendChild(s_img);
            item_container.appendChild(s_name);
				
            details.appendChild(d_name);
            details.appendChild(d_price);
            details.appendChild(d_qty);
				
            item_container.appendChild(details);
				
            item_container.className = "itemContainer";
				
            items_holder.appendChild(item_container);
            item_container.appendChild(details);
            
            
            
            $(item_container).mouseover(function() {
                $(this).children(".itemDetails").show();
            });
				
            $(item_container).mouseout(function() {
                $(this).children(".itemDetails").hide();
            });
				
				
        }
			
			
        this.updateTotals();
			
			
		if (this.totalItems > 0) {
			this.showShoppingCart();
		} else {
			this.hideShoppingCart();
		}
		
		
		
		// create the arrows
		$('#slide_left').remove();
		$('#slide_right').remove();
		btn_l = document.createElement('a');
		btn_r = document.createElement('a');
		$(btn_l).attr('id', 'slide_left');
		$(btn_r).attr('id', 'slide_right');
		$(items_holder).before(btn_l);
		$(items_holder).after(btn_r);
		
		
		var l_btn_l = 0+'px';
		var items_holder_l = this.slider_button_width + 'px';
		var r_btn_l = this.slider_button_width + this.item_area_width + 'px';
		
		
		$(btn_l).css('left', l_btn_l);
		$(btn_r).css('left', r_btn_l);
		$(items_holder).css('left', items_holder_l);
		
		
		// if there are more products than fit, add horzizontal scrolling buttons
		var total_products_width = this.item_width * this.items.length;
		if (this.item_area_width >= total_products_width) {
		
		    btn_l.className = "slide_left_hidden";
		    btn_r.className = "slide_right_hidden";
		    
		    
		} else {
		
		    btn_l.className = "slide_left";
		    btn_r.className = "slide_right";
		
		    
		    f_l = function (that) { 
		        return function () {
		           that.slideRight();
		        }; 
		      }(this);

		    f_r = function (that) { 
		        return function () {
		           that.slideLeft();
		        }; 
		      }(this);
		    
		    $('.slide_left').click(f_l);
		    $('.slide_right').click((f_r));
		    
		    
		     this.hideOffscreenItems(0);

		
		}
		

	
	
	}
	
	
	
	// ensures that the current offset does not mean that there are items off the viewing area
	// if there is space in the viewing area
	this.correctOffset = function () {
	
	
	   if (this.sliderOffset < 0) { // some items are hidden
	       var items_total_width = this.item_width * this.items.length;
	       
	       if (items_total_width <= this.item_area_width ) {
	           this.sliderOffset = 0;
	       } else {
	           var space_available = this.item_area_width - (this.sliderOffset + items_total_width);
	           if (space_available >= this.item_width) { // there is space for at least 1 item
	               var spaces_available = Math.floor(space_available / this.item_width);
	               this.sliderOffset += (spaces_available*this.item_width);
	           }
	       }
	   }
	   
	
	}
	
	
	// slide 1 spot right
	this.slideRight = function (full) {
	
	   // only slide if it is necessary
	   if (this.sliderOffset < 0) {
  	       this.sliderOffset += this.item_width;
  	       this.slide();
	   }
	}
	
	
	
	// slide 1 spot right
	this.slideLeft = function (full) {
	
	   
	   // only slide if it is necessary
	   if (this.sliderOffset + this.items.length * this.item_width > this.item_area_width) {
	   
	       if (full) {
	         this.sliderOffset = this.item_area_width - this.items.length * this.item_width;
	       } else {
	         this.sliderOffset -= this.item_width;
	       }
  	       
  	       this.slide();
  	       	   
	   }
	}
	

    // slide the items to the already set this.sliderOffset value
	this.slide = function () {
	
	  max = this.item_area_width - this.item_width;
	  min = 0;
	  
	  itms = $('#simpleCart_items').children();
	
	
	  for(i=0; i<itms.length; i++) {
	  
	      l = this.sliderOffset + (i * this.item_width);
	      
	      
	      // is going to be inside items area
	      if (l >= min && l <= max) {
	      
	          op = 1;
	        
	          if ($.support.opacity) {
	      
	              cb = null;
	              this.activateItem (itms[i]);
	        
	          } else {
	      
	              cb = (function (that, itm) {
	                  return (function () {
	                      that.activateItem (itm);
	                  });
	              }(this, itms[i]));
	        
	        }
	      
	      } else {
	      // is going to be outside items area
	        
	        
	          op = 0;
	        
	          if ($.support.opacity) {
	      
	              cb = (function (that, itm) {
	                  return (function () {
	                      that.deactivateItem (itm);
	                  });
	              }(this, itms[i]));
	        
	          } else {
	      
	              this.deactivateItem(itms[i]);
	              cb = null;
	              
	          }
	        
	      }
	        
	        
	        
	      	      
	      $(itms[i]).stop();
	      
	      if ($.support.opacity) {
	        $(itms[i]).animate(  { "left": l,  "opacity": op } , { duration:400, complete:cb });
	      } else {
	        $(itms[i]).animate(  { "left": l} , { duration:400, complete:cb });
	      }
	      
	           

	       
	   } // end for each item
	       
	
	
	}
	
	
	this.activateItem = function (itm) {
            $(itm).css('display', 'block');
            
	
	}
	
	this.deactivateItem = function (itm) {
            $(itm).css('display', 'none');
	
	}
	
	
	
	
	
    this.hideOffscreenItems = function (d) {
    
    
	  max = this.item_area_width - this.item_width;
	  min = 0;
	  
	  itms = $('#simpleCart_items').children();
	
	  for(i=0; i<itms.length; i++) {
	  
	      l = this.sliderOffset + (i * this.item_width);
	      // is outside items viewer
	      if (l < min || l > max) {
	          if ($.support.opacity) {
	              $(itms[i]).animate( { "left": l, "opacity": 0 }, { duration:d } );
	          }
	          this.deactivateItem(itms[i]);
	      }
	  
	  }

    }
	
	
	this.updateTotals = function () {
		$('#totalItems').val(String(this.totalItems));
		var totalprice = this.returnTotalPrice();
		var tp = document.getElementById('totalPrice');
		tp.innerHTML = totalprice;
	}
	
	
	this.shortenName = function (str, len) {
	
	  var newstr;
	    
	  if (str.length > len) {
	  
	    var arr =  str.split('', len);
	    newstr = '';
	    for (var i = 0; i<arr.length - 3; i++) {
	      newstr += arr[i];
	    }
	    
	    newstr += "..."; 
	  
	  } else {
	  
	    newstr = str;
	  
	  }
	  
	  return newstr;
	
	
	}
	




	// return the cart total 
	this.returnTotalPrice = function() {
		return this.returnFormattedPrice( this.totalPrice );
	};
	
	// return a price with the format $xxx.xx
	this.returnFormattedPrice = function( price ) {
		temp = Math.round(price*100);
		change = String(temp%100);
		if( change.length === 0) {
			change = "00";
		} else if( change.length == 1) {
			change = "0" + change;
		}
		temp = String(Math.floor(temp/100));
		return "$" + temp + "." + change;
	};
	
	
	
	
	//////////////////////////////////////////////////////////////////
	/**
	 * added for Bonsai Media.
	 * Performs custom shipping calculations for the order
	 * which are then passed to paypal... we do this instead of
	 * paypal's own shipping calculations due to custom business logic
	 * uses jquery btw ;)
	 */
	this.calcCustomShippingCost = function() {
	
	    // get the post code
	    var pc = $('#destination_postcode').val(); 
	    
	    if (this.validatePostcode(pc) === 0) {	      
	      this.displayCosts('Please enter a valid postcode');
	    } else if (this.validatePostcode(pc) === -1) {
	      this.displayCosts('Please enter your postcode');
	    } else if (this.validatePostcode(pc) === 1) {
	    
	    	this.displayCosts("Calculating ... please wait");

	    
	        itms = '';
	    
            for (var i = 0 ; i < this.items.length ; i++) {
	          
	           itms += "itm";
               itms += "_he" + this.items[i].getValue('height'); 
               itms += "_le" + this.items[i].getValue('length'); 
               itms += "_we" + this.items[i].getValue('width'); 
               itms += "_me" + this.items[i].getValue('weight'); 
               itms += "_qe" + this.items[i].getValue('quantity');
              
            }
              
              
	          var query = 'itms='+itms;
	          query += '&pc='+pc;
	          
	          var url = 'http://'+this.siteroot+"orders/postagecalc/";
	          
	          
	          //alert(url+'?'+query);
	
	          var that = this;
	          
              $.ajax({
                url: url,
                data: query,
                dataType: 'text',
                success: function(data, textStatus, XMLHttpRequest) {
  
                  //alert('data '+data);
    
                  data = data.split('<.>');
                  var charge = '';
                  //var qid = '';
                  var error = '';
  
                  for (var i = 0; i < data.length; i++) {
    
                    data[i] = data[i].split('=');
      
                    if (data[i][0] == 'charge') {
                        charge = data[i][1];
                    } else if (data[i][0] == 'qid') {
                        qid = data[i][1];
                    } else if (data[i][0] == 'err_msg') {
                        error = data[i][1];
                    }
    
                  }
                  
    
                  if (error == 'OK'){
                    that.setShippingCost(parseFloat(charge));   
                  } else {
                   that.displayCosts(error);
                  }
    
    
    
                }

              });        // end ajax call      
	       
	    
	    } // end if valid postcode


	};
	
	this.setShippingCost = function (val) {
	    this.totalShippingCost = val;
	    this.displayCosts();
	};
	
	
	

	

	
	

	this.displayCosts = function (message) {
	
	
	    var shipping_cost =  (this.totalShippingCost === null) ? 0 : this.totalShippingCost;  
	
	    if (message === undefined) {
		  $('#current_shipping_cost').text(this.returnFormattedPrice(this.totalShippingCost));		
		  $('#current_total_cost').text(this.returnFormattedPrice(this.totalShippingCost + this.totalPrice));
		  
		  this.turnProceedOn();		  

	    } else {
		  $('#current_shipping_cost').text(message);
		  
		  var total_cost = this.returnFormattedPrice(this.totalPrice);
		  total_cost += " plus shipping";
		  $('#current_total_cost').text(total_cost);
		  
		  this.turnProceedOff();		  
		  
	    }

	
	};
	
	
	
	
	this.turnProceedOn = function () {
	
		$('.simpleCart_checkout').text("» Proceed to paypal");
		$('.simpleCart_checkout').bind('click', function() { simpleCart.checkOut(); });
	    $('.simpleCart_checkout').colorbox({width:"500px", height:"220px", inline:true, href:"#paypal"});
	
	}
	
	this.turnProceedOff = function () {
	
		$('.simpleCart_checkout').text("");
		$('.simpleCart_checkout').unbind();
	
	}
	
	
	
	
	
	// returns 1 if valide postcode
	// -1 if it is a part of a valid postcode
	// 0 if invalid postcode and not a part of a postcode
	// valid postcode is 4 integers, no more, no less
	this.validatePostcode = function (pc) {
	
	  if (/^\d*$/.test((pc))) {
	  
	    if (pc.length > 4) {  
	      return 0;
	    } else if (pc.length == 4) {
	      return 1;
	    } else {
	      return -1;
	    }
	    
	  } else {
	      return 0;	  
	  }
	
	};
	
	
	
	this.hideShoppingCart = function() {
	    if ($.support.opacity) {
	      an = { height: "0px",	opacity: '0' }
	    } else {
	      an = { height: "0px" }
	    }
	
		$("#shopping_cart").animate(an, 600 );
	};
	
	this.showShoppingCart = function() {
	    if ($.support.opacity) {
	      an = { height: "90px",	opacity: '0.9' }
	    } else {
	      an = { height: "90px" }
	    }
	
		$("#shopping_cart").animate(an, 1000 );
	};
	
	
	this.qtyLess = function(item_index) {
	    return this.changeQuantity(item_index, -1);
	};
	
	this.qtyMore = function(item_index) {
	    return this.changeQuantity(item_index, 1);
	};
	
	this.changeQuantity = function (item_index, change_amount) {
	
	    var old_qty = parseFloat(this.items[item_index].getValue('quantity'));
	    var new_qty = old_qty + parseFloat(change_amount);
	    
	    if (new_qty < 0) {
	      new_qty = 0;
	      change_amount = new_qty - old_qty;
	    }
	    
	    this.totalItems = this.totalItems + change_amount;
	    
	    
		this.items[item_index].setValue('quantity', new_qty);
		$('input#qty_field_'+item_index).val(new_qty);
		var pricechange = this.items[item_index].getValue('price') * change_amount;
	    this.totalPrice += pricechange;
		this.updateTotals();
	    
		
		if (new_qty <= 0) {
          this.removeEmptyProducts ();
	      this.updatePageElements();
		}
		
	    this.updateCookie();
		return new_qty;
	}
	
	
	
	this.preCheckout = function() {
		this.calcCustomShippingCost();
		document.getElementById('destination_postcode').onkeyup = function(that) {
		   return function () {
		     that.calcCustomShippingCost();
		   };
		}(this);
		
		this.displayCosts('Please enter your postcode'); 
	};
	

	
	// send user to paypal checkout with all the items in the cart
	this.checkOut = function() { 
	
      
		if( this.totalItems === 0 ){
			alert("Your cart is empty!");
			return false;
		}
		
		// check shipping cost has been calculated.
		if (this.totalShippingCost === null) {
			alert("There was a problem calculating shipping cost for this order.\n\nPlease try again.");
			$.fn.colorbox.close();
			return false;
		}
		

		
		var winpar = "scrollbars,location,resizable,status";
		var i,j=0,des,counter;
		
        
        if (this.testing) { 
	  	  var strn = "https://www.sandbox.paypal.com/webscr?cmd=_cart";
        } else {
		  var strn  = "https://www.paypal.com/cgi-bin/webscr?cmd=_cart";
        }
		
        strn += "&upload=1";
        strn += "&return=http://"+this.siteroot;
        strn += "&bn=Bonsaimedia_Cart_WPS_AU";
        strn += "&business=" + this.userEmail;
        strn += "&currency_code=" + this.currency;
        strn += "&lc=" + this.country_code;
        strn += "&shipping_1="+this.returnFormattedPrice(this.totalShippingCost);
        if (this.testing) { 
          strn += "&notify_url=http://beta.primefocusconsulting.com.au/shop/orders/ipnListener/";
        } else {
          strn += "&notify_url=http://www.primefocusconsulting.com.au/shop/orders/ipnListener/";
        }
		
		counter = 0;
		for (counter = 0; counter < this.items.length; counter++) { 
			tempItem = this.items[counter];
			j = counter + 1; 
            strn +=  "&item_name_"   + j + "=" + tempItem.getValue('name');
            strn +=  "&item_number_" + j + "=" + tempItem.getValue('code');
		    strn +=  "&quantity_"    + j + "=" + tempItem.getValue('quantity');
		    strn +=  "&amount_"      + j + "=" + this.returnFormattedPrice(tempItem.getValue('price') );
		    strn +=  "&no_shipping_"  + j + "=" + "2";
            strn +=  "&no_note_"  + j + "=" + "0";
            if( tempItem.optionList() ) {
				strn +=  "&on0_" + j + "=" + "Options" + "&os0_" + j + "=" + tempItem.optionList();
			}
			
				
		}
		

		
		strn = encodeURI(strn);
		
		// ----------------------------------------------------				
		
		// display the "transferring to paypal" window...
		//$.fn.colorbox({href:"#paypal", inline: true, open: true, width:"250px", height:"200px", resize: true, speed: 100});
		
		// clear the cart and redirect to paypal using our constructed URL string.
		setTimeout(function() { simpleCart.empty(); }, 250);
		setTimeout(function() { window.location=strn;}, 750);

		return false;
	};
	
	
	
	
}
/*************************************************************************************************
         This is the item class.  It will contain an array of name-value pairs.
 *************************************************************************************************/

function item () {

    this.standard_properties = ['code', 'name', 'image', 'price', 'weight', 'length', 'width', 'height']

	this.names	= [];
	this.values	= [];
	
	
	/* add a name-value pair to the item,
	 * return false and alert if the names 
	 * and values don't match.
	 */
	this.addValue = function(name,value) {
	
	   
		  if( this.names.length != this.values.length ) {
			alert("name and value array lengths do not match for this item!");
			return false;
		  }
		  found = false;
		  var a=0;
		  for(a=0;a<this.names.length;a++) {
			if( this.names[a] == name ) {
				this.values[a] = value;
				return;
			}
		  }
		  if( !found ) {
			this.names[this.names.length]	= name;
			this.values[this.values.length]	= value;
		  }
		  return;	
		     

	};
	
	
	// checks if a string is the name of a standard property
	this.isStandardProperty = function (p_name) {
		for(a=0;a<this.standard_properties.length;a++) {
			if( this.standard_properties[a] == p_name ) {
				return true;
			}
		}
		return false;
	}
	
	

	
	/* return the value associated with the
	 * name key, return null if the name is not
	 * found
	 */
	this.getValue = function(name) {
		var g=0;
		for(g=0;g<this.names.length;g++) {
			if(name==this.names[g]) {
				return this.values[g];
			}
		}
		return null;
	};
	/* return the value associated with the
	 * name key, return null if the name is not
	 * found
	 */
	this.setValue = function(name, val) {
		var g=0, success=false;
		for(g=0;g<this.names.length;g++) {
			if(name==this.names[g]) {
				this.values[g] = val;
				success=true;
			}
		}
		return success;
	};
	
	/* return true if the item is equal to 
	 * the item passed in, false otherwise 
	 */
	this.equalTo = function(item) {
		if(this.getSize() != item.getSize() ) {
			return false;
		} 
		var q=0;
		for(q=0;q<this.names.length;q++) {
			if( this.names[q] != 'quantity' && (item.getValue(this.names[q]) != this.values[q]) ) {
				return false;
			}
		}
		return true;
	};

	this.getSize = function() {
		return this.names.length;
	};
	
	this.cookieString = function() {
		returnString = '';
		var i=0;
		returnString = this.names[i] + "=" + this.values[i];
		i=1;
		for(i=1;i<this.names.length;i++) {
			returnString = returnString + "," + this.names[i] + "=" + this.values[i];
		}
		return returnString;
	};
	

	
	this.optionList = function() {
		returnString = '';
		if( this.getSize() < 8 ) {
			return null;
		}
		var o=0;
		for(o=0;o<this.names.length;o++) {
			if(!this.isStandardProperty(this.names[o])) {
				returnString = returnString + this.names[o] + ':' + this.values[o] + ', ';
			}
		}
		while(returnString.charAt(returnString.length-1)==',' || returnString.charAt(returnString.length-1)==' ' || returnString.charAt(returnString.length)==':'){
			returnString = returnString.substring(0,returnString.length-1);
		}
		return returnString;
	};
	
} // end item class




//*************************************************************************************************
// Thanks to Peter-Paul Koch for these cookie functions! (http://www.quirksmode.org/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 === xhtmlNamespace)? 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, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};
//*************************************************************************************************



$(document).ready(function(){
	simpleCart = new cart(); 
	
	// set inline in html page
	simpleCart.userEmail = sc_userEmail;
	simpleCart.siteroot = sc_siteroot;
	simpleCart.testing = sc_testing;
	
	simpleCart.initialize();
	$('#pre_checkout').bind('click', function() { simpleCart.preCheckout(); });
	$('#pre_checkout').colorbox({width:"500px", height:"300px", inline:true, href:"#shipping_details"});
});



