// v2.9 11-01-10 
// Latest Changes: Broke Billing name field into first and last
// v2.8 8-16-10 // Broke name field into first and last
// v2.7 8-15-10 // Reduced max cards to 10
// v2.6 8-08-10 // Added support for displaying shipping address 2 & company fields in carts
// v2.5 6-20-10 // removed charlength parsing of outputted form data
// v2.4 12-10-09 // added check for double click on checkout
// v2.34 11-09-09  // added missing P.O. box check
var shippingCost=0;
var shippingTime=0;
var NextId=1,USDollar="USD", USD="USD", test="test";
var POBoxWarningHit = false;
var submitFlag = false;

function Cart(){
 
/ Set the shipping rates */
	
	var DefaultshippingTime = "Shipping Not Set";
	var DefaultshippingCost = 0;
	
	var UPSshippingTime = "Next Day";
	var UPSshippingCost = 17.95;
	
	var PriorityshippingTime = "3-4 Business Days";
	var PriorityshippingCost = 5.95;
	
	var USPSshippingTime = "7-10 Business Days";
	var USPSshippingCost = 0;
	
	var InternationalshippingTime = "5-10 Business days";
	var InternationalshippingCost = 10.95;
	
	/* member variables */
	this.items = {};
	this.isLoaded = false;
	this.pageIsReady = false;
	this.quantity = 0;
	this.total = 0;
	this.shippingFlatRate = 0;
	this.shippingTotalRate = 0;
	this.shippingQuantityRate = 0;
	this.shippingRate = 0;
	this.shippingCost = 0;
	this.currency = USD;
 
	this.checkoutTo = test;
	this.cartHeaders = ['Price','Quantity', 'ShipToCountry','ShipToNameFirst','ShipToNameLast','ShipToCompany','ShipToStreet','ShipToStreet2', 'ShipToCity', 'ShipToState','ShipToZip', 'ShipToPhone', 'ChangeTheAddress', 'messageTo','messageFrom','messageBody','ChangeTheMessage','ShippingMethod', "Remove"];
	
	/******************************************************
			add/remove items to cart  
 	 ******************************************************/
 
	this.add = function () {
		/* load cart values if not already loaded */
		if( !this.pageIsReady 	) { 
			this.initializeView(); 
			this.update();	
		}
		if( !this.isLoaded 		) { 
			this.load(); 
			this.update();	
			this.updateTotals();
		}
		
		
		
		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;
		if( arguments[0] && typeof( arguments[0] ) != 'string' && typeof( arguments[0] ) != 'number'  ){ 
			argumentArray = arguments[0]; 
		} 
 
		newItem.parseValuesFromArray( argumentArray );
		newItem.checkQuantityAndPrice();
				
			this.items[newItem.id] = newItem;
		
		
		this.items[newItem.id].shippingcost = 0;
		
		this.update();
		
		
			
		
	};
	
	
	this.remove = function( id ){
		var tempArray = {};
		for( var item in this.items ){
			if( item != id ){ 
				tempArray[item] = this.items[item]; 
			}
		}
		this.items = tempArray;
	
	};
	
	
	this.empty = function () {
		RCCart.items = {};
		RCCart.update();
	};
 
 
		
/********************************************************************************************************
 * checkout
 ********************************************************************************************************/
 
 this.checkForPromo = function () {
	total = 0;
	for(i in this.items) {
			total += this.items[i].price * this.items[i].quantity; 
	}
	if (total > 250) {
	return true;
	}else{
	return false;}
};
 
 
this.checkout = function() {

if (submitFlag == false ){  // check if checkout has been clicked to prevent double orders
				RCCart.testCheckout();
				}
};
	
	
this.testCheckout = function() {
		
		submitFlag = true;   // to prevent double orders
		
		var form = document.createElement("form"),
			counter = 0;
		form.acceptCharset = "utf-8";
		form.id = "resultsDump";
		
		for( var current in this.items ){
			var item 				= this.items[current];
						
			counter++;
			form.appendChild( this.createHiddenElement( "Quantity_" 	+ counter, item.quantity 	) );
			form.appendChild( this.createHiddenElement( "Price_" 		+ counter, item.price		) );
			form.appendChild( this.createHiddenElement( "MessageTo_" 	+ counter, item.messageto 	) );
			form.appendChild( this.createHiddenElement( "MessageFrom_" 	+ counter, item.messagefrom 	) );
			form.appendChild( this.createHiddenElement( "SpecialMessage_" 	+ counter, item.messagebody 	) );
			
			form.appendChild( this.createHiddenElement( "ShipToCompany_" 	+ counter, item.shiptocompany 	) );
			form.appendChild( this.createHiddenElement( "ShipToCountry_" 	+ counter, item.shiptocountry 	) );
			form.appendChild( this.createHiddenElement( "ShipToNameFirst_" 	+ counter, item.shiptonamefirst 	) );
			form.appendChild( this.createHiddenElement( "ShipToNameLast_" 	+ counter, item.shiptonamelast 	) );
			form.appendChild( this.createHiddenElement( "ShipToStreet_" 	+ counter, item.shiptostreet 	) );
			form.appendChild( this.createHiddenElement( "ShipToStreet2_" 	+ counter, item.shiptostreet2 	) );
			form.appendChild( this.createHiddenElement( "ShipToPhone_" 	+ counter, item.shiptophone 	) );
			
			form.appendChild( this.createHiddenElement( "ShipToState_" 	+ counter, item.shiptostate 	) );
			form.appendChild( this.createHiddenElement( "ShipToProvince_" 	+ counter, item.shiptoprovince 	) );
			
			form.appendChild( this.createHiddenElement( "ShipToCity_" 	+ counter, item.shiptocity 	) );
 
			form.appendChild( this.createHiddenElement( "ShipToZip_" 	+ counter, item.shiptozip 	) );
			form.appendChild( this.createHiddenElement( "ShippingMethod_" 	+ counter, item.shippingmethod	) );
				
		
			
		
		};
		
		
		
		document.body.appendChild( form );
		var str = $("#resultsDump").serialize();
		var str2 = $("#billingForm").serialize();
		
 
		//$("#results").empty();
		//$("#results").text(str2 +"&"+ str);
		if(RCCart.checkForPromo()){
		var output = str+ "\&" + str2+"\&Over250Promo=true";} else {
		var output = str+ "\&" + str2;
		}		
		document.body.removeChild( form ); 
			//$.post("FormProcessor.aspx", output);
		
 
		if (version == "corporate") {
		output = output + "\&corporateDiscount=" + $("#corporateDiscount").val() + "\&corporateComment=" + $("#corporateComment").val();
		}
		if (version == "callcenter") {
		output = output + "\&callcenterOperator=" + $("#callcenterOperator").val();
		}
				
		// Dump the Cookies
		//alert(document.cookie);
		RCCart.dumpCookies();
		//alert(document.cookie);
		
		$.ajax({
   type: "POST",
   url: "FormProcessor.aspx",
   data: output,
   success: function(msg){
     if(msg == "CCError") {
     window.location = "ThankYou.aspx?Status=Error";
     } else {
     window.location = "ThankYou.aspx";
     }
   }
 });
 
		
		
	};
 
	/******************************************************
				data storage and retrival 
	 ******************************************************/
	
	/* load cart from cookie */
	this.load = function () {
		/* initialize variables and items array */
		this.items = {};
		this.total = 0.00;
		this.quantity = 0;
		
		/* retrieve item data from cookie */
		if( readCookie('RCCart') ){
			var data = unescape(readCookie('RCCart')).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 */
					this.items[newItem.id] = newItem;
				}
 			}
		};
 
		/* read the billing info */
		  $("#billingAddress :input").each(
    	function(){ // if cookied, restore
    		var name = $(this).attr('name');
    		if( $.cookie( name ) ){
    			$(this).val( $.cookie(name) );
    		}
    	}
    );
		
		
		this.isLoaded = true;
	};
	
	
	
	/* save cart to cookie */
	this.save = function () {
 
		var dataString = "";
		for( var item in this.items ){
			dataString = dataString + "++" + this.items[item].print();
		}
	createCookie('RCCart', dataString.substring( 2 ),0);
		
		
	// create the billing cookies
		 		$("#billingAddress :input").each(
    			function(){
				//alert($(this).attr('name'));
    				$.cookie($(this).attr('name'), $(this).val(), { path: '/' });
    			}
    		);
		
	};
	
	
	//Dump the cookies
	this.dumpCookies = function () {
	$("#billingAddress :input").each(
    			function(){
				eraseCookie($(this).attr('name'));
				});
	eraseCookie('RCCart');
	};
 
	
		
	/******************************************************
				 view management 
	 ******************************************************/
	
	this.initializeView = function() {
		this.totalOutlets 			= getElementsByClassName('RCCart_total');
		this.quantityOutlets 		= getElementsByClassName('RCCart_quantity');
		this.cartDivs 				= getElementsByClassName('RCCart_items');
		this.shippingCostOutlets	= getElementsByClassName('RCCart_shippingCost');
		this.finalTotalOutlets		= getElementsByClassName('RCCart_finalTotal');
		
		
 
		this.addEventToArray( getElementsByClassName('RCCart_checkout') , RCCart.checkout , "click");
		
		
			
		this.pageIsReady = true;
		
	};
	
	
	
	this.updateView = function() {
		this.updateViewTotals();
		if( this.cartDivs && this.cartDivs.length > 0 ){ 
			this.updateCartView(); 
		
		} 
	};
	
	this.updateViewTotals = function() {
	
	
	
		var outlets = [ ["quantity"		, "none"		] , 
						["total"		, "currency"	] , 
						["shippingCost"	, "currency"	] ,
						["finalTotal"	, "totalcurrency"	] ];
						
		for( var x=0,xlen=outlets.length; x<xlen;x++){
			
			var arrayName = outlets[x][0] + "Outlets",
				outputString;
				
			for( var element in this[ arrayName ] ){
				switch( outlets[x][1] ){
					case "none":
						outputString = "" + this[outlets[x][0]];
						break;
					case "currency":
						outputString = this.valueToCurrencyString( this[outlets[x][0]] );
						break;
					case "percentage":
						outputString = this.valueToPercentageString( this[outlets[x][0]] );
						break;
				    case "totalcurrency":
						outputString = this.valueToLongCurrencyString( this[outlets[x][0]] );
						break; 
					default:
						outputString = "" + this[outlets[x][0]];
						break;
				}
				this[arrayName][element].innerHTML = "" + outputString;
			}
		}
	};
	
	this.updateCartView = function() {
 
		var newRows = [],
			x,newRow,item,current,header,newCell,info,outputValue,option,headerInfo;
		
		/* create headers row */
		newRow = document.createElement('div');
		for( header in this.cartHeaders ){
			newCell = document.createElement('div');
			headerInfo = this.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 this.items ){
		
			newRow = document.createElement('div');
			item = this.items[current];
			for( header in this.cartHeaders ){
			
			
			
				newCell = document.createElement('div');
				info = this.cartHeaders[header].split("_");
				
				switch( info[0].toLowerCase() ){
					case "total":
						outputValue = this.valueToCurrencyString(item.price*item.quantity) ;
						break;
					case "remove":
						outputValue = this.valueToLink( "Remove" , "javascript:;" , "onclick=\"RCCart.items[\'" + item.id + "\'].remove();\"" );
						break;
					case "price":
						outputValue = this.valueToCurrencyString( item[ info[0].toLowerCase() ] ? item[info[0].toLowerCase()] : " " );
						break;
					case "shippingmethod":
					
						outputValue = this.valueToSelect( item.id, info[0] , "name=\"" +item.id+ "\" onchange=\"RCCart.items[\'" + item.id + "\'].set(\'" + info[0].toLowerCase()  + "\', RCCart.getSelectedItem(this)); RCCart.setShipping(\'" +item.id + "\', RCCart.items[\'" + item.id + "\']."+ info[0].toLowerCase()+ "); RCCart.updateTotals(); RCCart.updateView();\"");
						$("[name=" + item.id + "]").val(RCCart.items[item.id].shippingmethod);
						
						break;
					case "changetheaddress":
						outputValue = this.valuesToAddress( item.id ) + "<br /><br />";
						break;
					case "changethemessage":
						outputValue = this.valuesToMessage( item.id ) + "<br /><br />";
						break;
					case "messagebody":
						if (item[ info[0].toLowerCase() ].length <=1) {
						outputValue=item[ info[0].toLowerCase() ]; } else {
						outputValue = "<b>Message:</b> " +item[ info[0].toLowerCase() ].substr(0,80) + "<br /><br />";
						}
						break;
						case "messageto":
						if (item[ info[0].toLowerCase() ].length <=1) {
						outputValue = "<div class='messageHeader'></div><br /><b>(None set)</b>"; } else {
						outputValue = "<div class='messageHeader'></div><br /><b>To:</b> " +item[ info[0].toLowerCase() ].substr(0,50) + "<br /><br />";
						} 
						break;
						case "messagefrom":
						if (item[ info[0].toLowerCase() ].length <=1) {
						outputValue=item[ info[0].toLowerCase() ]; } else {
						outputValue = "<b>From:</b> " +item[ info[0].toLowerCase() ].substr(0,50) + "<br /><br />";
						}
						break;
						case "shiptocompany":
						if (item[ info[0].toLowerCase() ].length <=1 || item[ info[0].toLowerCase() ] == "UseBilling") {
						outputValue="" } else {
						outputValue = "<b>Company:</b> " + item[ info[0].toLowerCase() ].substr(0,50);
						}
						break;
						case "shiptonamefirst":
						if (item[ info[0].toLowerCase() ].length <=1 || item[ info[0].toLowerCase() ] == "UseBilling") {
						outputValue = "<div class='shippingHeader'></div><br /><b>(Ship to the same address as billing)</b>"; } else {
						outputValue = "<div class='shippingHeader'></div><br /><b>To:</b> " + item[ info[0].toLowerCase() ].substr(0,65) + "<br />";
						} 
						break;
						case "shiptonamelast":
						if (item[ info[0].toLowerCase() ].length <=1 || item[ info[0].toLowerCase() ] == "UseBilling") {
						outputValue = ""; } else {
						outputValue = item[ info[0].toLowerCase() ].substr(0,65) + "<br />";
						} 
						break;
						case "shiptostreet":
						if (item[ info[0].toLowerCase() ].length <=1 || item[ info[0].toLowerCase() ] == "UseBilling") {
						outputValue="" } else {
						outputValue = "<b>Address:</b> " + item[ info[0].toLowerCase() ].substr(0,50);
						}
						break;
						case "shiptostreet2":
						if (item[ info[0].toLowerCase() ].length <=1 || item[ info[0].toLowerCase() ] == "UseBilling") {
						outputValue="" } else {
						outputValue = item[ info[0].toLowerCase() ].substr(0,50);
						}
						break;
						case "shiptocity":
						if (item[ info[0].toLowerCase() ].length <=1 || item[ info[0].toLowerCase() ] == "UseBilling") {
						outputValue="" } else {
						outputValue = "<b>City:</b> "+ item[ info[0].toLowerCase() ].substr(0,20);
						}
						break;
						case "shiptostate":
						if (item[ info[0].toLowerCase() ].length <=1 || item[ info[0].toLowerCase() ] == "UseBilling") {
						outputValue="" } else {
						if (item.shiptocountry == "CA") {
						outputValue = "<b>Province:</b> "+item.shiptoprovince; } else {
						outputValue = "<b>State:</b> "+ item.shiptostate;
						}
						}
						break;
						case "shiptozip":
						if (item[ info[0].toLowerCase() ].length <=1 || item[ info[0].toLowerCase() ] == "UseBilling") {
						outputValue="" } else {
						outputValue = "<b>ZIP/ Post Code:</b> "+ item.shiptozip + "<br /><br />";
						}
						break;
						case "shiptophone":
						if (item[ info[0].toLowerCase() ].length <=1 || item[ info[0].toLowerCase() ] == "UseBilling") {
						outputValue="" } else {
						outputValue = "<b>Phone:</b> "+ item.shiptophone + "<br /><br />";
						}
						break;
					default: 
						outputValue = item[ info[0].toLowerCase() ] ? item[info[0].toLowerCase()] : " ";
						break;
				}	
				
				for( var y=1,ylen=info.length;y<ylen;y++){
					option = info[y].toLowerCase();
					switch( option ){
						case "image":
						
						case "img":
							outputValue = this.valueToImageString( outputValue );		
							break;
						case "input":
							outputValue = this.valueToTextInput( outputValue , "onChange=\"RCCart.items[\'" + item.id + "\'].set(\'" + outputValue + "\' , this.value);\""  );
							break;
						case "div":
						case "span":
						case "h1":
						case "h2":
						case "h3":
						case "h4":
						case "p":
							outputValue = this.valueToElement( option , outputValue , "" );
							break;
						case "noheader":
							break;
						default:
							error( "unkown header option: " + option );
							break;
					}
				
				}		  
				newCell.innerHTML = outputValue;
				newCell.className = "item" + info[0];
				newRow.appendChild( newCell );
				
			}			
			newRow.className = "itemContainer " + item.id;
			newRows[x] = newRow;
			x++;
			
		}
					
		
		
		for( current in this.cartDivs ){
			
			/* delete current rows in div */
			var div = this.cartDivs[current];
			while( div.childNodes[0] ){
				div.removeChild( div.childNodes[0] );
			}
			
			for(var j=0, jLen = newRows.length; j<jLen; j++){
				div.appendChild( newRows[j] );
			}
			
	
		}
		
		
		
	tb_init("a.thickbox, area.thickbox, input.thickbox"); //update thickbox			
	this.useBillingReplace(); //replace "useBilling" Items
	

	
	};
 
	this.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 );
			}
		}
	};
	
	
	this.createHiddenElement = function ( name , value ){
		var element = document.createElement("input");
		element.type = "hidden";
		element.name = name;
		element.value = value;
		return element;
	};
	
	
	
	/******************************************************
				Currency management
	 ******************************************************/
	
	this.currencySymbol = function() {		
		switch(this.currency){
			
			case USD:
		
				return "";
		}
	};
	
	
 
	
	/******************************************************
				Formatting
	 ******************************************************/
	
	
	this.valueToCurrencyString = function( value ) {
		return parseFloat( value ).toCurrency( this.currencySymbol() );
	};
	
	this.valueToLongCurrencyString = function( value ) {
		
		return "$" + addCommas(roundNumber( value, 2 ));
	};
	
	this.valueToPercentageString = function( value ){
		return parseFloat( 100*value ) + "%";
	};
	
	this.valueToImageString = function( value ){
		if( value.match(/<\s*img.*src\=/) ){
			return value;
		} else {
			return "<img src=\"" + value + "\" />";
		}
	};
	
	this.valueToSelect = function( id, value, html ){
		
		us= " /> <OPTION VALUE=\"Please Select\" selected=\"true\">Please Select</option><OPTION VALUE=\"USPS\" >First Class Mail</option><OPTION VALUE=\"USPS Priority\">USPS Priority</option><OPTION VALUE=\"UPS Next Day\">UPS Next Day</option>";
		ca = " /><OPTION VALUE=\"Please Select\" selected=\"true\">Please Select</option><OPTION VALUE=\"USPS International Standard Mail\" >USPS International Standard Mail</option></select>"; 
		//alert(RCCart.items[id].shiptocountry);
		if ($('#BillToCountry').val() == 'CA' && RCCart.items[id].shiptocountry == "UseBilling"){
			
			return "<select class=\"" + value + "\" "  + html +  ca;
			
		};
		if ($('#BillToCountry').val() == 'US' && RCCart.items[id].shiptocountry == "UseBilling" ){
			
			return "<select class=\"" + value + "\" "  + html +  us; 
		};
		if (RCCart.items[id].shiptocountry == 'US' ){
		
			return "<select class=\"" + value + "\" "  + html +  us; 
		};
		if (RCCart.items[id].shiptocountry == 'CA' ){
		
			return "<select class=\"" + value + "\" "  + html +  ca; 
		};
		this.updateShipping();
		RCCart.update();
	};
	this.valueToTextInput = function( value , html ){
		return "<input type=\"text\" value=\"" + value + "\" " + html + " />";
	};
	
	this.valueToLink = function( value, link, html){
		return "<a href=\"" + link + "\" " + html + " >" + value + "</a>";
	};
	
	this.valueToElement = function( type , value , html ){
		return "<" + type + " " + html + " > " + value + "</" + type + ">";
	};
	
	this.getSelectedItem = function( target ) {
	var theIndex = target.selectedIndex;
	var theOutput = target[theIndex].text;
		return theOutput;
	};
	
	this.getSelectedItemIndex = function( form , target ){
	var aSel = form;
	
		for(var i=0; i<aSel.length; i++) {
		
			if(aSel[i]==target) {
			alert(aSel.selectedIndex);
			break;
			}
		}
	};
	
	// function to create link to update submit button call in modal box
	this.setItem = function ( itemID ) {
	$("#addressModalSubmit").before("<A href=\"javascript: RCCart.addressModalSubmit(\'" + itemID + "\');\" id=\"addressModalSubmit\"> Submit Changes </a>").remove();
	};
	this.setItem2 = function ( itemID ) {
	$("#messageModalSubmit").before("<A href=\"javascript: RCCart.messageModalSubmit(\'" + itemID + "\');\" id=\"messageModalSubmit\"> Submit Changes </a>").remove();
	};
	
	// generate 'change this' links in cart
	this.valuesToAddress = function ( itemID ) {
	return '<a href="#TB_inline?height=460&amp;width=330&inlineId=addressModal" class="thickbox" onclick="RCCart.setItem(\''+ itemID +'\');RCCart.addressModalDefaults(\''+ itemID + '\');\" >Change This</a>';
	};
	this.valuesToMessage = function ( itemID ) {
	return '<a href="#TB_inline?height=190&amp;width=400&inlineId=specialMessageModal" class="thickbox" onclick="RCCart.setItem2(\''+ itemID +'\'); RCCart.messageModalDefaults(\'' + itemID + "\');\" >Change This</a>";
	};
	
	// populate the message modal default values
	this.messageModalDefaults = function ( itemID ) {
	$('#messageToModal').val(RCCart.items[itemID].messageto);
	$('#messageFromModal').val(RCCart.items[itemID].messagefrom);
	$('#messageBodyModal').val(RCCart.items[itemID].messagebody);
	};
	
	this.addressModalDefaults = function ( itemID ) {
	$('#addressModalShipToNameFirst').val(RCCart.items[itemID].shiptonamefirst);
	$('#addressModalShipToNameLast').val(RCCart.items[itemID].shiptonamelast);
	$('#addressModalShipToCompany').val(RCCart.items[itemID].shiptocompany);
	$('#addressModalShipToPhone').val(RCCart.items[itemID].shiptophone);
	
	$('#addressModalShipToStreet').val(RCCart.items[itemID].shiptostreet);
	$('#addressModalShipToStreet2').val(RCCart.items[itemID].shiptostreet2);
	$('#addressModalShipToCity').val(RCCart.items[itemID].shiptocity);
	
	$('#addressModalShipToState').val(RCCart.items[itemID].shiptostate);
	$('#addressModalShipToProvince').val(RCCart.items[itemID].shiptoprovince);
	$('#addressModalShipToZip').val(RCCart.items[itemID].shiptozip);
	
	$('#addressModalShipToCountry').val(RCCart.items[itemID].shiptocountry);
	
	var fieldArray =  $('#addressModalForm :input')
			for( i=0; i<fieldArray.length; i++) {
				if (fieldArray[i].value == 'UseBilling' || fieldArray[i].value == 'undefined') {
				fieldArray[i].value = "";
				} 
			};
	
	};
	
	// update the item variables with the values entered into modal box
	this.addressModalSubmit = function (itemID) {
	if (validateAddressModalForm() == true){
	RCCart.items[itemID].set('shiptocountry', $("#addressModalShipToCountry").val());
	RCCart.items[itemID].set('shiptonamefirst', $("#addressModalShipToNameFirst").val());
	RCCart.items[itemID].set('shiptonamelast', $("#addressModalShipToNameLast").val());
	RCCart.items[itemID].set('shiptophone', $("#addressModalShipToPhone").val());
	RCCart.items[itemID].set('shiptocompany', $("#addressModalShipToCompany").val());
	
	RCCart.items[itemID].set('shiptostreet', $("#addressModalShipToStreet").val());
	RCCart.items[itemID].set('shiptostreet2', $("#addressModalShipToStreet2").val());
	
	RCCart.items[itemID].set('shiptocity', $("#addressModalShipToCity").val());
	RCCart.items[itemID].set('shiptozip', $("#addressModalShipToZip").val());
	RCCart.items[itemID].set('shiptostate', $("#addressModalShipToState").val());
	tb_remove();
	this.update();
	}
	};
	
	this.messageModalSubmit = function (itemID) {
	if (specialMessageModalValid == true){
	RCCart.items[itemID].set('messageto', $("#messageToModal").val());
	RCCart.items[itemID].set('messagefrom', $("#messageFromModal").val());
	RCCart.items[itemID].set('messagebody', $("#messageBodyModal").val());
	tb_remove();
	this.update();
	} 
	};
	
		
	
	// Set the shipping
	this.setShipping = function(targetID, value) {
 
	var address = RCCart.items[targetID].shiptostreet;	
	if (address.search(/po box/i) != -1 || address.search(/p o box/i) != -1 || address.search(/p.o. box/i) != -1) { // check for PO Box
	RCCart.items[targetID].set('shippingTime', USPSshippingTime);
	RCCart.items[targetID].set('shippingCost', USPSshippingCost);
	$(".ShippingMethod[name="+targetID+"] option[value='UPS Next Day']").remove();
	if (POBoxWarningHit == false){
	alert("Sorry, UPS does not deliver to P.O. Boxes");
	POBoxWarningHit = true;
	};
	} else {
 
	//set the shipping time and cost
	if (value == "Please Select") {
	shippingTime = DefaultshippingTime;
	shippingCost = DefaultshippingCost;
	};
	if (value == "First Class Mail") {
	shippingTime = USPSshippingTime;
	shippingCost = USPSshippingCost;
	};
	if (value == "USPS Priority") {
	shippingTime = PriorityshippingTime;
	shippingCost = PriorityshippingCost;
	};
	if (value == "UPS Next Day") {
	shippingTime = UPSshippingTime;
	shippingCost = UPSshippingCost;
	};
	if (value == "USPS International Standard Mail") {
	shippingTime = InternationalshippingTime;
	shippingCost = InternationalshippingCost;
	};
 
// Check for duplicate cards and bill accordingly
this.checkDuplicates = function() {
 
	for( var current in RCCart.items){
	if (current != "promo_card" && targetID != "promo_card") {
	var thisItemID = parseFloat(current.substring(1,2));
	//alert("target:"+targetID +"  current:"+ current);
	
			if (RCCart.items[targetID].shiptocountry == "CA" || $("#BillToCountry").val() == "CA"){ // check for international shipping
			RCCart.items[targetID].set('shippingTime', shippingTime);
			RCCart.items[targetID].set('shippingCost', shippingCost);
			//RCCart.items[targetID].set('shippingmethod', "Please Select");
			//$('.ShippingMethod[name='+targetID+']').val("Please Select");
			//alert(RCCart.items[targetID].shippingcost);
			};
			
			if (RCCart.items[targetID].shiptocountry == "US" || $("#BillToCountry").val() == "US"){ // check for us shipping
			RCCart.items[targetID].set('shippingTime', shippingTime);
			RCCart.items[targetID].set('shippingCost', shippingCost);
			//RCCart.items[targetID].set('shippingmethod', value);
			//$('.ShippingMethod[name='+targetID+']').val("First Class Mail");
			//alert(RCCart.items[targetID].shippingcost);
			};	
	
		if (current != targetID || current == appliedToAll && current != "undefined"){ // if the items have the same shipping...
 
				if (RCCart.items[current].shippingmethod == RCCart.items[targetID].shippingmethod && RCCart.items[current].shiptostreet == RCCart.items[targetID].shiptostreet) {
					RCCart.items[current].set('shippingCost', 0);
					RCCart.items[current].set('shippingTime', RCCart.items[targetID].shippingtime);
				};
		} else { // if the shipping is not the same, set the shipping vars
		
	
			if (typeof(shippingCost) != "undefined" && typeof(shippingTime) != "undefined") {
			RCCart.items[targetID].set('shippingCost', shippingCost);
			RCCart.items[targetID].set('shippingTime', shippingTime);
			};
			
				if (RCCart.items[targetID].shiptocountry == "CA" || $("#BillToCountry").val() == "CA"){ // check for international shipping
			RCCart.items[targetID].set('shippingTime', InternationalshippingTime);
			RCCart.items[targetID].set('shippingCost', InternationalshippingCost);
		};
 
		
				if (shippingdefault == true){ // check for international shipping
			
			RCCart.items[targetID].set('shippingTime', USPSshippingTime);
			RCCart.items[targetID].set('shippingCost', USPSshippingCost);
			shippingdefault = false;
		};
		
		
		};
	
	
		// and finally append the set values
	$(".ShippingMethod[name="+current+"]").nextAll().remove();
	$('.ShippingMethod[name='+current+']').parent().append('<br /><div class=\"shippingTime\">'+RCCart.items[current].shippingtime+'</div><div class=\"shippingCost\">Shipping: $'+RCCart.items[current].shippingcost+'</div>');
	$('.ShippingMethod[name='+current+']').parent().append('<div id=\"moreInfo\"><a href=\"#TB_inline?height=300&amp;width=330&amp;inlineId=shippingDetails\" class=\"thickbox\" >(More Info)</a></div>');
 
	}
	};
	};
 
	this.checkDuplicates();
	};
	tb_init("a.thickbox, area.thickbox, input.thickbox"); //update thickbox	
 
	};
	
	
	
	// Hide items listed as UseBilling and replace with "(Use Same as Billing Address)"
	
	this.useBillingReplace = function() {
	/*
	$("#step1_cart .itemContainer div:contains('UseBilling'):nth-child(5n-1)").text("(Same as Billing)"); 
	$("#step1_cart .itemContainer div:contains('UseBilling')").css('opacity', 0); 
	*/
	};
	
	// get info from forms and add to confirm page
	this.getFinalBilling = function() {
 
	// HIde 'Not Set' City, State, ZIP
	this.billingExtra = function() {
	
	if (RCCart.getValue("#BillToStreet2") == "\"Not Set\""){
	street2 = " ";}else{
	street2 = '<br />' + RCCart.getValue("#BillToStreet2") + '<br />';
	};
	
	if (RCCart.getValue("#BillToState") == "UseBilling" || RCCart.getValue("#BillToCountry") == "CA") {
	state = " ";}else{
	state = RCCart.getValue("#BillToState");
	};
	
	if (RCCart.getValue("#BillToProvince") == "UseBilling" || RCCart.getValue("#BillToCountry") == "US") {
	province = " ";}else{
	province = RCCart.getValue("#BillToProvince");
	};
	
	if (RCCart.getValue("#BillToCity") == "Not Set") {
	return " ";
	} else {
	return street2 +RCCart.getValue("#BillToCity")+ " " + state + province + " " +RCCart.getValue("#BillToZip") + "<br />";
 
	};
	};
	
	
 
	
	// retrieve the values and append to 3rd step
	$('#finalBilling').empty();
	$('#finalBilling').html( '<div id="finalBillingLeft"><p><b> Cardholder: </b> ' + RCCart.getValue("#NameOnCard") 
	+ '<br /><b> Card Number: </b> XXXX'+ RCCart.getValue("#CardNumber").substring(RCCart.getValue("#CardNumber").length-4,RCCart.getValue("#CardNumber").length)
	+ '<br /><b> Card Type: </b> '+RCCart.getValue("#CardType")
	+ '</p></div><div id="finalBillingRight"><p><b> Billing Name: </b> '+RCCart.getValue("#BillToNameFirst") +' '+RCCart.getValue("#BillToNameLast")+ '<br /><b> Billing Company: </b>' + RCCart.getValue("#BillToCompany")
	+ '<br /><b> Billing Address: </b> '+RCCart.getValue("#BillToStreet")
	+ this.billingExtra()
	+ '<b> Phone: </b> '+RCCart.getValue("#BillToPhone")
	+ '<br /><b> Email: </b> '+RCCart.getValue("#BillToEmail")
	+ '</p></div>'
	)
	};
	
	
	
	
	this.getValue = function(target) {
	testvalue = $(target).val();
	if(testvalue !== null && testvalue != "undefined" ) {
	return $(target).val();
	} else {
	return "Not Set";
	}
	};
	/******************************************************
				Duplicate management
	 ******************************************************/
	
	
	this.hasItem = function ( item ) {
		for( var current in this.items ) {
			var testItem = this.items[current];
			var matches = true;
			for( var field in item ){
				if( typeof( item[field] ) != "function"	&& 
					field != "quantity"  				&& 
					field != "id" 						){
					if( item[field] != testItem[field] ){
						matches = false;
					}
				}	
			}
			if( matches ){ 
				return current; 
			}
		}
		return false;
	};
		
	
	
	/******************************************************
				Cart Update managment
	 ******************************************************/
	
	this.update = function() {
	//alert("update");
		if( !RCCart.isLoaded ){
			RCCart.load();
		} 
		if( !RCCart.pageIsReady ){
			RCCart.initializeView();
		}
		
		
		this.updateTotals();
		this.updateView();
		
		// Update the second cart by cloning the first
		$('.RCCart_items_Step2').empty();
		$('#step1_cart .RCCart_items').clone(true).appendTo('.RCCart_items_Step2');
		
		tb_init("a.thickbox, area.thickbox, input.thickbox"); //update thickbox		
		
	
		
		// update the already selected shipping option in the just-cloned second cart
		
		this.updateShipping = function() {
		for( var current in this.items ){
		
		var shippingStr = RCCart.items[current].shippingmethod;
		$(".ShippingMethod[name="+current+"]").val(shippingStr);
		RCCart.setShipping(current, shippingStr);	
		}};
		
		this.updateShipping();
		
		
		// Update the third cart by cloning the first
		$('#RCCart_items_Step3').empty();
		$('#step1_cart .RCCart_items').clone().appendTo('#RCCart_items_Step3');
		$('#finalBilling').empty();
		RCCart.getFinalBilling();
		
		//$('#finalBilling').empty();
			
		// Add the Checkbox
		$(".applyToAll").remove();
		$(".RCCart_items_Step2 .itemRemove :first").parent().parent().append("<div class='applyToAll'><input type='checkbox' id='applyToAllCheckbox' name='applyToAllCheckbox' onchange='applyToAllShipping();'><label for='applyToAllCheckbox'>Use this shipping method for all</label></div>");
 
		$(".itemContainer").after("<div class='itemFooter'></div>");
		
		if ($('#step1_cart .RCCart_quantity').html() === '0') {
		//console.log("empy!");
		$("#step1_cart .RCCart_items").html('<img src="img/cartEmpty.gif" id="cartEmpty" alt="Add cards using the form to the left!" />');
		}
				
		this.save();
		};
	
	//this.setAllShipping= function(shippingmethod) {
	//alert(shippingmethod.toString());
	//$('.itemShippingMethod').find(':input').val(shippingmethod.toString());
	
	//for( var current in this.items ){
	//RCCart.setShipping(current, shippingmethod);
	//RCCart.items[current].set('shippingmethod', shippingmethod); 
	//RCCart.updateTotals;
	//}
	//}		
	
	
	this.updateTotals = function() {
		this.total = 0 ;
		this.subTotal = 0;
		this.quantity  = 0;
		this.discountTotal = 0;
		for( var current in this.items ){
	
	
 
		var item = this.items[current];
		
		//RCCart.setShipping(current, item.shippingmethod);
		
			if( item.quantity < 1 || item.quantity + this.quantity >21 && version != "corporate"){ 
			alert("Sorry, please order no more than 20 cards");
				item.remove();
				return;
			} else if( item.quantity !== null && item.quantity != "undefined" ){
				this.quantity = parseInt(this.quantity,10) + parseInt(item.quantity,10); 
			}
			if( item.price ){
				this.total = parseInt(item.quantity,10)*item.price + item.shippingcost; 
				
				// vars for corporate discount
				this.discountTotal = ((parseInt(item.quantity,10)*item.price)- ((parseInt(item.quantity,10)*item.price)*($("#corporateDiscount").val()/100))) + item.shippingcost; 
				
				
		if(item != undefined) {
		
		if(version == "corporate" && this.discountTotal != "") {
		this.subTotal =  this.discountTotal + this.subTotal;
		} else {
		this.subTotal =  this.total + this.subTotal;
		}
		}	
		
			//this.itemTotal =  this.total;
			
			$("#step3_cart .ShippingMethod[name="+current+"]").nextAll().remove();
			$("#step3_cart .ShippingMethod[name="+current+"]").parent().append("<br /><div class='ShippingMethodText'>"+item.shippingmethod+"</div>");
			$("#step3_cart .ShippingMethod[name="+current+"]").parent().append("<br /><div class='itemTotal'>$"+roundNumber(this.total,2)+"</div>");
			
		
			}
	
	
		
		}
		this.finalTotal =  this.subTotal;
		
	};
	
	
	
	/*
	this.shipping = function(){
		if( parseInt(this.quantity,10)===0 )
			return 0;
		var shipping = 	parseFloat(this.shippingFlatRate) + 
					  	parseFloat(this.shippingTotalRate)*parseFloat(this.total) +
						parseFloat(this.shippingQuantityRate)*parseInt(this.quantity,10),
			nextItem,
			next;
		for(next in this.items){
			nextItem = this.items[next];
			if( nextItem.shipping ){
				if( typeof nextItem.shipping == 'function' ){
					shipping += parseFloat(nextItem.shipping());
				} else {
					shipping += parseFloat(nextItem.shipping);
				}
			}
		}
		
		return shipping;
	}
	*/
	
	this.initialize = function() {
		RCCart.initializeView();
		RCCart.load();
		RCCart.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 );
			}
							
			if( typeof(value) == "number" && isNaN( value ) ){
				error( "Improperly formatted input.");
				
			} else { 
				this[field] = value;
				this.checkQuantityAndPrice();
			}			
		} else {
			error( "Cannot change " + field + ", this is a reserved field.");
		}
		
		
		
		//RCCart.update();
	};
	
	
	CartItem.prototype.print = function () {
		var returnString = '';
		for( var field in this ) {
			if( typeof( this[field] ) != "function" ) {
				returnString+= escape(field) + "=" + escape(this[field]) + "||";
			}
		}
		return returnString.substring(0,returnString.length-2);
	};
	
	
	CartItem.prototype.checkQuantityAndPrice = function() {
		if( !this.price || this.quantity == null || this.quantity == 'undefined' ){ 
			alert('No quantity for item.');
		} else {
			this.quantity = ("" + this.quantity).replace(/,*/gi, "" );
			this.quantity = parseInt( ("" + this.quantity).replace( /[^(\d|\.)]*/gi, "") , 10); 
			if( isNaN(this.quantity) ){
				error('Quantity is not a number.');
				//alert("Please enter a quantity");
				this.quantity = 1;
				
			};
		}
				
		if( !this.price || this.price == null || this.price == 'undefined'){
			this.price=0.00;
			error('No price for item or price not properly formatted.');
		} else {
			this.price = ("" + this.price).replace(/,*/gi, "" );
			this.price =  ("" + this.price).replace( /[^(\d|\.)]*/gi, "") ; 
			if( isNaN(this.price) ){
				error('Price is not a number.');
				this.price = 0.00;
			}
		}
	};
	
	
	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() {
		RCCart.remove(this.id);
		RCCart.update();
	};
	
 
 
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);
}
 
 
 
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);
};
 
 
/********************************************************************************************************
 *  Helpers
 ********************************************************************************************************/
 
Number.prototype.withCommas=function(){var x=6,y=parseFloat(this).toFixed(2).toString().reverse();while(x<y.length){y=y.substring(0,x)+","+y.substring(x);x+=4;}return y.reverse();};
Number.prototype.toCurrency=function(){return(arguments[0]?arguments[0]:"$")+this.withCommas();};
 
String.prototype.reverse=function(){return this.split("").reverse().join("");};
//Number.prototype.withCommas=function(){var x=6,y=this.toFixed(2).toString().reverse();while(x<y.length){y=y.substring(0,x)+","+y.substring(x);x+=4;}return y.reverse();};
 
//Number.prototype.toCurrency=function(){return(arguments[0]?arguments[0]:"$")+this.withCommas();};
 
Number.prototype.toFixed = function(fractionDigits)
{
   var m = Math.pow(10,fractionDigits);
   return Math.round(this*m,0)/m;
}
 
function roundNumber(number,decimal_points) {
	if(!decimal_points) return Math.round(number);
	if(number == 0) {
		var decimals = "";
		for(var i=0;i<decimal_points;i++) decimals += "0";
		return "0."+decimals;
	}
 
	var exponent = Math.pow(10,decimal_points);
	var num = Math.round((number * exponent)).toString();
	return num.slice(0,-1*decimal_points) + "." + num.slice(-1*decimal_points)
}
 
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;
}
 
/********************************************************************************************************
 * error management 
 ********************************************************************************************************/
 
function error( message ){
	try{ 
		console.log( message ); 
	}catch(err){ 
	//	alert( message );
	}
}
 
 
var RCCart = new Cart();
 
window.onload = RCCart.initialize;
 
