
var thing, cnt = 0, ps = -1, gt = 0, swap = false;
d.write('<div id="sc"></div>');

String.prototype.Trim = new Function("return this.replace(/^\\s+|\\s+$/g, '')");

function sc(i) {
	//**** initialize shopping cart
	var ua = navigator.userAgent;
	
	//**** weed out the old and yucky
	if (ua.indexOf('MSIE 5.') != -1 && ua.indexOf('Mac') != -1) { 
		var bwsr = confirm('We apologise for the inconvenience, but your browser is too old (sorry!), and it cannot use our shopping cart. Please install Firefox (at mozilla.com)! You won\'t be sorry, and it\'s easy to do!\n\nClick OK to go to mozilla.com, or click Cancel to stay on this site.\n\nThank you!!!'); 
		
		if (bwsr) self.location = 'http://mozilla.com';
		
		return; 
	}
	else if ( !el('sc') ) return;
		
	//**** create the shopping cart object
	if (!d.cart) d.cart = new Shopcart();
	
	if (i instanceof Array) d.cart.showList(i, arguments[1]);
	else if (i != '' && i != undefined) d.cart.add(el(document.ID));
	else d.cart.makeCart(false);

} // end sc


function Shopcart(_el) {
	
	if (_el == '') return;
	
	//**** init basics
	this.total = 0;
	this.grand_total = 0;
	this.count = 0;
	this.shipping = 0;
	this.pst_val = 0.07;
	this.gst_val = 0.05;
	this.gst = 0;
	this.pst = 0;
	this.items = [];
	this.newitem = [];
	
	//**** init object vars
	this.str = '';
	this.showTotal = true;
	this.swap = 0;
	this.choice = 0;
	this.ps = -1;
	this.wholesale = false;
	this.haspst = '';
	
	//**** form options
	this.formoptions = {shipto:0};
	
	//**** load cookie values (from other page(s))
	this.getCookie();
	
} // end object shopcart

Shopcart.prototype.getCookie = function () {
	//**** grab cookie info
	var tmp = d.cookie, m;
	var edsc = (top.sesspool.cart);
	var ops = (top.sesspool.ops);
	
	if (edsc == 'empty cart' || edsc == '') this.items = [];
	else this.items = edsc;//eval( edsc );
	
	if (ops == 'no ops') this.formoptions = {};
	else this.formoptions = ops;//makeObj( ops, 1 );
	
	if (top.sesspool.merch != 'retail') {
		this.wholesale = true;
		x = eval(top.sesspool.merch);
		this.merchant = x[0].replace(/\+/g, ' ');
		this.haspst = top.sesspool.pst;
		if (x[1]) this.cartlist = x.slice(1);
		else this.cartlist = '';
	}
	
}; // end proto getCookie

function parseCookie(_str) {
	var i, sc, ops, m, mc;
	
	if (_str.search(/evendesign/i) != -1) {
		_str = _str.split(';');
		alert(_str)
		//**** find the even stuff
		for (i = 0; i < _str.length; i++) {
			if (_str[i].search(/evendesignshopcart=/) != -1) sc = _str[i];
			else if (_str[i].search(/evendesignshopcartops=/) != -1) ops = _str[i];
			else if (_str[i].search(/evendesignmerchant=/) != -1) m = _str[i];
		}
		
		return [sc, ops, m];
	}
	
	return 0;
	
}; // end parseCookie

Shopcart.prototype.add = function (_el) {
	//**** get new item info
	var tmp, i, x = this.items.length;
	
	this.newitem = {};
	
	this.items[x] = {};
	this.items[x].title = fix(_el.title);
	this.items[x].name = fix(_el.id);
	this.items[x].price = fix(_el.getAttribute('price'));
	this.items[x].opts = fix(_el.getAttribute('options'));
	
	if (this.items[x].price.indexOf('[') != -1) {
		p = this.items[x].price.match(/'(\d+)'(,'(\d+)')?/);
		this.items[x].price = p[1];
	}
	if (this.wholesale) {
		this.items[x].price = this.items[x].price / 2;
		if ((cpos = this.items[x].opts.indexOf('colour')) != -1) {//alert(this.items[x].opts);
			tmp = this.items[x].opts;
			epos = tmp.indexOf(']', cpos);
			this.items[x].opts = tmp.substring(0, epos) + ",'all colours'" + tmp.substring(epos);
		}
	}
	this.items[x].qty = 1;
	//this.items[x].opts = {};
	
	this.items[x].src = _el.src.replace(/http:\/\/(evendesigninc.com|localhost)\/lines\/thumb\//, '');
	this.items[x].newitem = true;
	
	if ((tmp = _el.getAttribute('choice')) != null && tmp != "['Array']") {
		//**** load in arrays for the multiple choice
		this.items[x].title = eval(fix(tmp));
		this.items[x].price = eval(_el.getAttribute('price'));
	}
	
	this.newitem.title = this.items[x].title;
	this.newitem.name = this.items[x].name;
	this.newitem.price = this.items[x].price;
	this.newitem.opts = this.items[x].opts;
	this.newitem.qty = this.items[x].qty;
	this.newitem.src = this.items[x].src;
	
	this.makeCart(true);
	
}; // end proto add


Shopcart.prototype.copy = function (src, dest) {
	var i;
	
	for (i in src) dest[i] = src[i];
	
}; // end proto copy 

function viz(_el) {
	if (_el.parentNode.parentNode.style.overflow != 'visible') {
		_el.parentNode.parentNode.style.overflow = 'visible'; 
		_el.parentNode.parentNode.style.height = 'auto';
		_el.src = '/images/nav/minus.gif';
		}
	else {
		_el.parentNode.parentNode.style.overflow = 'hidden'; 
		_el.parentNode.parentNode.style.height = '1.6em';
		_el.src = '/images/nav/plus.gif';
	}
}

Shopcart.prototype.showList = function (_ary, _new) {

	//**** create boxes and buttons
	var but = '<div id="sc2"><input type="button" value="X" class="b" title="close merchant tools window" onclick="hideCart()">' +
				'<h3 id="shopping">{MSG1}' + unescape(this.merchant) + '!<\/h3><h3 id="merch">Merchant Tools<\/h3>' +
				'<div id="scwrapwholesale"><div id="thanks">{MSG2}</div><br><table cellpadding="0" cellspacing="0" border="0" width="100%" id="sctable">';
				
	var row = '<tr align="center"><td>{C1}<\/td><td>{C2}<\/td><td><input type="button" name="load" value="Load" onclick="loadCart(\'{C3}\', \'{C4}\', \'{N1}\')" title="load in the \'{N1}\' cart" />{DELBUTT}<\/td><\/tr>';
	
	var str = '<tr><th>Cart Name</th><th>Items</th><th>Options</th></tr>';
	
	var oldmsg1 = 'Welcome Back, ';
	var oldmsg2 = 'Here is a list of shopping carts, and their contents, you have previously saved. You can load in a cart to make a quick purchase, or you can close this window and shop for different items. You could load in a cart, then add or remove items as you require.';
	
	var newmsg1 = 'Welcome to <strong>even design</strong>, ';
	var newmsg2 = 	'<p>This window will appear each time you sign-in; but next time it will list any &quot;shopping carts&quot; you have saved.</p>' +
					'<p>For convenience, we have included in the &quot;even Sampler&quot; shopping cart our popular items, colours and sizes. If you load in this cart, you can alter the items, remove them, add to them, or otherwise customize what you want to order.</p>' +
					'<p>You see, after you have shopped and are checking out, you can save the contents of the shopping cart; you may save the contents as the &quot;Default&quot; cart, or choose another name. You may save as many different carts as you require.</p>' +
					'<p>Then, the next time you sign-in, you can load in one of these carts to make a quick order. If you do load in a cart, you can still add to it, or remove any items you don\'t want.</p>' +
					'<p>Alternatively, you can click the <strong>&quot;Start Fresh!&quot;</strong> button to begin with an empty cart. At this point, go ahead and click either the <strong>Start Fresh!</strong> button <em>(and visit each section of the web site to add items to the shopping cart)</em>, or the <strong>Load</strong> button for the &quot;even Sampler&quot; cart to get started!</p>' +
					'<p>Thanks for being a part of <strong>even design</strong>!</p> <p>Judi Patson</p>';
					
	var delbutt = ' / <input type="button" name="del" value="Delete" onclick="delCart(\'{N1}\')" title="delete the \'{N1}\' cart" />';
	var i, j, c1, c2, items, tmp, tot;
	
	
		
	//**** build the table rows
	if (_ary.length>=0) {
		tmp = but.replace(/{MSG1}/, _new ? oldmsg1 : newmsg1);
		str = tmp.replace(/{MSG2}/, _new ? oldmsg2 : newmsg2) + str;
		
		for (i = 0; i < _ary.length; i++) {
			tmp = _ary[i];
			
			items = [];
			str += row;
			
			if (tmp.name.toLowerCase() != 'even sampler') str = str.replace(/{DELBUTT}/, delbutt);
			else str = str.replace(/{DELBUTT}/, '');
			
			
			tot = 0;
			qty = 0;
			
			//**** make comma list of items in cart, plus popup image
			for (j in tmp.items) {
				items.push(tmp.items[j].title);
				items[j] = '<span id="popup' + i + '' + j +'" >' + items[j] + ' x' + tmp.items[j].qty + '</span><div class="imgpop" id="pop' + i + '' + j +'"><img src="' + (tmp.items[j].src.indexOf('http') == -1 ? 'http://evendesigninc.com/lines/thumb/' : '') + tmp.items[j].src + '" class="g" /></div>';
				tot += tmp.items[j].qty * tmp.items[j].price;
				qty += parseInt(tmp.items[j].qty);
			}
			items = '<div class="popcart"><span><strong>Shopping Cart contents:</strong> <img src="/images/nav/plus.gif" onclick="viz(this)" title="click to see the contents" /></span><br />' + items.join('<br />') + '</div>';
			
			str = str.replace(/{N1}/g, tmp.name);
			str = str.replace(/{C1}/g, tmp.name + '<br />($' + tot.toFixed(2) + ', ' + qty + ' items)');
			str = str.replace(/{C2}/, items);
			str = str.replace(/{C3}/, escape(objToStr(tmp.items)));
			str = str.replace(/{C4}/, escape(objToStr(tmp.ops)));
			 
		}
	}
	else {
		tmp = but.replace(/{MSG1}/, newmsg1);
		str = tmp.replace(/{MSG2}/, newmsg2) + str + '<tr><td>shopping cart names appear here...</td><td>the items in the cart appear here...</td><td>some buttons appear here...</td></tr>';
	}
	
	str += '</table></div><div id="buttons"><input type="button" id="rem" value="Start Fresh!" title="close this window and start with an empty cart" onclick="hideCart()"> <input type="button" id="close" value="Send Password" title="I forgot my merchant password; please email it me" onclick="emailPW(\'' + this.merchant + '\')"> <input type="button" id="change" value="Change Password" title="I\'d like to change my merchant password" onclick="changePW(\'' + this.merchant + '\')"></div></div>';
	
	el('sc').innerHTML = str;
	el('sc').style.display = 'block';
	initRollover();
	
}; // end showList



Shopcart.prototype.makeCart = function (add) {
	var str = '', j, k = -1, tmp, chkout = (arguments.length == 2 ? arguments[1] : false), chkstr = '';
	var buttons = ['Add" class="remind','Update','Submit to PayPal'];
	var titles = ['secretly add another little something for yourself','magically update your goodies','send to PayPal for online credit card transaction'];
	
	this.swap = 1; // set to "update" button
	this.showTotal = true;
	var pricediv = this.wholesale ? 2 : 1;
	
	//**** create rows of items
	this.getItems(add, chkout);
	
	//**** create boxes and buttons
	var but = '<div id="sc2"><input type="button" value="X" class="b" title="close shopping cart without updating" onclick="hideCart()">';
	var tab = '<div id="scwrap' + (this.wholesale ? 'wholesale' : '') + '"><table cellpadding="0" cellspacing="0" border="0" width="100%" id="sctable">';
	
	//**** what does the header say
	str = but + '<h3 id="shopping">';
	
	if (chkout) {
		str += 'Yay! Time to Checkout! Thanks again!<\/h3>';
		this.swap = 2;
	}
	else if (this.str != '') str += 'The shopping cart says ‘thanks!’<\/h3>';
	else {
		str += 'The shopping cart is sad and empty.<\/h3>';
		this.showTotal = false;
	}
	
	if (this.wholesale) str += '<h3 id="merch">' + this.merchant + '<\/h3>';
	
	str += tab + (str.indexOf('empty') == -1 ? this.str : '');
	
	if (add && this.newitem != null) {
		//**** new item to cart
		var choice = '', skip = false, choiceary, priceary, pos;
		
		if (typeof this.newitem.title == 'object' && this.newitem.title.length > this.choice) {
			choice = '';
			choiceary = this.newitem.title;
			priceary = this.newitem.price;
			pos = this.items.length - 1;
			
			for (j = 0; j < choiceary.length; j++) {
				if (j != this.ps) 
					choice += '<br><input type="' + (this.ps >= 0 && this.newitem.title.length == 2 ? 'checkbox' : 'radio') + '" name="choice' + pos + '" value="' +
							choiceary[j] + '" price="' + (priceary[j]/pricediv) + '"' + (j > 0 || this.ps >= 0 ? '' : ' checked="checked"') + '>' + choiceary[j] + 
							' ($ ' + (priceary[j]/pricediv).toFixed(2) + ') ';
			}
			
			this.newitem.title = (this.ps == -1 ? 'Choose from more than one:' : 'A similar piece ("' + this.newitem.title[this.ps] + 
											'") was added already; check below to add this version too');
		}
		else if (typeof this.newitem.title == 'object' && this.newitem.title.length == this.choice) skip = true;
		
		if (!skip) {
			var pos = this.items.length - 1;
			str += '<tr class="new"><td class="scimg"><img src="' + (this.newitem.src.indexOf('http') == -1 ? '/lines/thumb/' : '') + this.newitem.src + '" alt="' + this.newitem.title + '" title="' + this.newitem.title + '" class="g"><\/td>' +
					'<td class="scitem"><input type="text" name="qty' + pos + '" value="1" title="enter the quantity for ' + 
					this.newitem.title + '" size="3"> ' + this.newitem.title + choice + this.makeOpts(pos) + '<\/td><td class="price"><h4>' + 
					(typeof this.newitem.price == 'object' ? '' : '$ ' + Number(this.newitem.price).toFixed(2) + ' ea.') + '<\/h4><\/td>' +
					'<td class="rem"><h4>New Item!<\/h4>' + (!pos ? '(click Add to save me to the cart)' : '(click Add ;-)') + '<\/td><\/tr>';
		}
		this.swap = skip ? 1 : 0;
	}
	
	//**** finish off items table
	str += '<\/table>';
	
	//**** show the 'total'
	if (this.showTotal && !chkout) str += '<div id="total">Subtotal: <h4 id="cost">$ ' + this.total.toFixed(2) + '<\/h4><\/div>';
	
	//**** deal with all the checkout stuff ******************************
	if (chkout) {
		str += '<div id="thanks"><p>Thank you for purchasing ' + this.count + ' piece' + mkEss('', this.count) + ' of jewellery! To finish off, please <strong>select any options<\/strong> for each piece of jewellery, and your <strong>Shipping Destination<\/strong> (to calculate the shipping and taxes).<\/p><p>When you click the "Submit" button, this info gets passed to <strong>PayPal</strong>, where you enter your shipping and payment info and pay by credit card on a secure connection. If you are requesting any custom choices, or you have multiple items, I’ll email you to find out the details (PayPal collects your email address for me). Many thanks!<\/p><p>Judi Patson<\/p><\/div>';
		
		str += '<div id="total">Subtotal: <h4 id="cost">$ ' + this.total.toFixed(2) + '<\/h4><\/div>';
		str += '<div id="ship">Choose your Shipping Destination: <select onchange="document.cart.calc(this);" name="shipto" id="shipto" title="Please choose your shipping destination"><option value="0"><\/option>' +
			'<option value="11"' + (ms(this.formoptions,'shipto',1)) + '>in British Columbia, $ 11.00 <\/option>' +
			'<option value="13"' + (ms(this.formoptions,'shipto',2)) + '>in the rest of Canada, $ 13.00 <\/option>' +
			'<option value="26"' + (ms(this.formoptions,'shipto',3)) + '>in North America, $ 26.00 <\/option>' +
			'<option value="36"' + (ms(this.formoptions,'shipto',4)) + '>Overseas, $ 36.00 <\/option><\/select><\/div>';
		str += '<div id="tax"><\/div>';
		str += '<div id="gtotal">Grand Total: <h4 id="gt">$ ' + this.total.toFixed(2) + '<\/h4><\/div>';
		
		//**** wholesale gets a list of saved carts - as array/object in cookie?
		if (this.wholesale) {
			//**** make list of saved carts
			var c_opstr = '';
			for (c = 0; c < this.cartlist.length; c++) {
				cname = this.cartlist[c].split('*');
				if (cname.length > 1) {
					s = ' selected';
					cname = cname[0];
				}
				else {
					s = '';
					cname = this.cartlist[c];
				}
				c_opstr += '<option value="' + cname + '"' + s + '>the ' + cname + ' cart<\/option>';
			}
			str += '<div id="merchpw">Enter your Merchant Password: <input name="pw" id="pw" type="password" title="Please enter your Merchant Password"><\/div>';
			str += '<div id="carts"><input type="checkbox" name="savecart" id="savecart"> Save this shopping cart to: <select name="cartlist" id="cartlist" onchange="chkCart(this)"><option value="Default">the Default cart<\/option>' + c_opstr + '<option value="new">a New cart<\/option><\/select><\/div><div id="merchant"><\/div>';
		}
		
		//**** prepare for all the hidden fields
		chkstr = '<form name="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post"><div id="ppform"><\/div><\/form>';
		
	}
	
	//**** main shop cart buttons ***************************************
	str += '<\/div><div id="buttons">';
	
	if (this.wholesale) {
		str += '<input type="button" id="mtools" value="Merchant Tools" title="view your saved carts and stuff" onclick="self.location = \'/index.php?merchant=' + this.merchant + '\'"> ';
	}
	if ( (add && !chkout && this.items.length > 1) || (!add && !chkout && this.items.length > 0) ) {
			str += '<input type="button" id="rem" value="Remove All Items" title="dump the shopping cart into the aisle" ' +
					'onclick="d.cart.emptyCart()">  ' +					
					'<input type="button" id="chkout" value="Checkout" title="transport yourself into the shortest line at the cash" ' +
					'onclick="d.cart.updateCart(this, true)">  ';
	}
	else if (chkout) {
		str += '<input type="button" id="paypal" value="' + buttons[this.swap] + '" title="' + titles[this.swap] + '" onclick="d.cart.sendToPayPal(this)">  ';
		this.swap = 1;
	}
	
	if ( (add || chkout) || (!add && !chkout) && this.items.length > 0) 
		str += '<input type="button" id="add" value="' + buttons[this.swap] + '" title="' + titles[this.swap] + '" onclick="d.cart.updateCart(this, ' + chkout + ')">  '; //add/update button
	
	str += '<input type="button" id="close" value="Close" title="close the shopping cart window" onclick="hideCart()"><\/div>';
	
	str = '<form name="scf" method="post" action="">' + str + '<\/div>' + '<\/form>' + chkstr;//;
	
	//**** write the cart to the page ***********************************
	el('sc').innerHTML = str;
	el('sc').style.display = 'block';
	
	//**** need tax?
	if (chkout && this.formoptions['shipto']) this.calc(d.forms['scf'].elements['shipto']);
	
	//**** scroll to bottom?
	if (chkout && this.wholesale) el('scwrapwholesale').scrollTop = el('scwrapwholesale').scrollHeight;
	else if (chkout) el('scwrap').scrollTop = el('scwrap').scrollHeight;
	
}; // end mkCart



function ms(_val, _pos, _idx) {
	//**** match cookie value for shipping destination
	var str = '';
	
	if (_val[_pos] && _val[_pos] == _idx) str = ' selected';
	
	return str;	
}



Shopcart.prototype.getItems = function (add, chkout) {
	var i, j, k, ps, qty, cnt = 0, str = '', opstr = '', tmp, choice = false, tmpobj, price;
	
	this.total = 0;
	this.count = 0;
	
	//[{title:"ufo magnet ring: comes with extra ball bearings",name:"ufo magnet ring",price:"175",opts:"{size:['4','4.5','5','5.5','6','6.5','7','7.5','8','8.5','9','9.5','10','10.5','11','custom']}",qty:"1",src:"attraction/ufo_magnet_ring.jpg"}]
	for (j = 0; j < this.items.length; j++) {
		//**** load all items into cart - "this.items" is the shopping cart array of items
		
		if (!this.items[j] || this.items[j].newitem) continue; // skip new item in this part
		
		//---------------------------
		
		if (this.items[j].qty == 0) { 
			//**** remove item if 0 qty
			this.items.splice(j, 1); 
			continue; 
		}
		
		if (this.newitem && typeof this.newitem.title == 'object') choice = true;
		
		//**** create row for item
		str += '<tr><td class="scimg"><img src="' + (this.items[j].src.indexOf('http') == -1 ? 'http://evendesigninc.com/lines/thumb/' : '') + this.items[j].src + '" alt="' + this.items[j].title + '" title="' + this.items[j].title + '"><\/td>' +
				'<td class="scitem"><input type="text" name="qty' + j + '" value="' + this.items[j].qty + '" title="enter the quantity for ' + this.items[j].title + 
				'" size="3"> ' + this.items[j].title.replace(this.items[j].name, mkEss(this.items[j].name, this.items[j].qty));

		str += this.makeOpts(j);
		
		if (k == j) {
			//**** this item highlighted - add message
			str += '<br><em class="blk">(You already have <span class="scqty">' + qty + '<\/span> <span class="scitem">' + tmp + mkEss(tmp, qty) + 
					'<\/span>-<br>set how many you want, and click "Update".)<\/em>';
			this.swap = 1;
		}
		
		price = this.items[j].price;// this.wholesale ? (this.items[j].price / 2) : 
		
		//**** load in price and finish row
		str += '<\/td><td class="price" nowrap="nowrap"><h4>$ ' + Number(price).toFixed(2) + ' ea.<\/h4><p>(x' + this.items[j].qty + '=' + (price * this.items[j].qty).toFixed(2) + ')<\/p><\/td>' + '<td class="rem"><input type="button" value="Remove" title="remove the ' + this.items[j].title + ' from the shopping cart" onclick="document.cart.rmCartItem(' + j + ', ' + chkout + ')"><\/td><\/tr>';
		
		//**** add up price total
		this.total += price * this.items[j].qty;
		
		//**** add total items
		this.count += parseInt(this.items[j].qty);
		
	} // end for
	
	this.str = str;
	
}; // end getItems



Shopcart.prototype.updateCart = function (_el) {
	//**** makes array for cookie, adding all items with a quantity > 0 (and adds new item, if present)
	var cartVals = _el.form.elements, i, j, t = '', x, p = 0, chkout = (arguments.length == 2 ? arguments[1] : false), tmp;
	
	for (i in this.items) { //(i = 0; i < this.items.length; i++) {
		//**** go through all items - but remove a new item during checkout
		if (chkout && this.items[i].newitem) { 
			delete this.items[i];//this.items.splice(i, 1);
			this.newitem = null;
			continue;
		}
		
		//**** update the quantity
		if (!cartVals['qty'+i]) continue;
		tmp = parseInt(cartVals['qty'+i].value); 
		
		//**** if quantity is 0 delete item, or skip update if NaN
		if (!tmp && String(tmp) != 'NaN') { 
			this.items.splice(i, 1); 
			continue; 
		}
		else if (String(tmp) != 'NaN') this.items[i].qty = tmp;
		
		if ((x = cartVals['choice'+i])) {
			//**** check for pesky choices
			if (x.length) {
				//**** have radios
				for (j = 0; j < x.length; j++) { 
					if (x[j].checked) {
						t = x[j].value;		
						p = x[j].getAttribute('price');
					}
				}
			}
			else if (x.checked) {
				//**** just one is a checkbox
				t = x.value;
				p = x.getAttribute('price');
			}
			else {
				//**** no choice selected - delete
				this.items.splice(i, 1); 
				continue;
			}
			
			this.items[i].title = t;
			this.items[i].price = p;
			
		} // end choice
		
		//**** if this is a new item, remove flag
		if (this.items[i].newitem) {
			delete this.items[i].newitem;
			this.newitem = null;
		}
	} // end for
	
	//**** make cookie 
	mkCookie('evendesignshopcart', this.items);
	mkCookie('evendesignshopcartops', this.formoptions);
	
	top.sesspool.fSub();
	
	//**** recreate cart ("false" means no new item)
	this.makeCart(false, chkout);
	
}; // end updateCart


Shopcart.prototype.emptyCart = function () {
	mkCookie('evendesignshopcart', []);
	mkCookie('evendesignshopcartops', {});
	
	top.sesspool.fSub();
	
	this.items = [];
	this.formoptions = {shipto:0};
	this.makeCart(false);
	
}; // end emptyCart


Shopcart.prototype.makeOpts = function (j) {
	var i, tmpobj, opstr = '';
	tmpobj = makeObj(this.items[j].opts);
	
	for (i in tmpobj) { 
		if (typeof tmpobj[i] == 'function') continue;
		
		if (!this.formoptions || !this.formoptions[i+j]) this.formoptions[i+j] = 0;
		opstr += makeSelect(i, tmpobj[i], j, this.items[j].title);//, (this.wholesale && i == 'colour')
	}
	
	if (opstr != '') opstr = '<br><h4 class="ops">Options:<\/h4> ' + opstr;
	
	return opstr;
};


Shopcart.prototype.rmCartItem = function (_n, _chkout) {
	//**** remove item
	var i, label, pos, del = '';
	
	//**** go through pesky options and reset goddam name references
	for (i in this.formoptions) { 
		label = i.match(/[^\d]+/)[0];
		pos = i.match(/\d+/);
		
		if (this.formoptions[label+_n] && pos == _n && del.indexOf(i) == -1) {
			delete this.formoptions[i];
			del += i;
		}
		else if (_n < pos) {
			this.formoptions[label+(pos - 1)] = this.formoptions[label+pos];
			delete this.formoptions[label+pos];
		}
	}
	
	mkCookie('evendesignshopcartops', this.formoptions);
	
	try {
		this.items.splice(_n, 1);
	}
	catch(e) {
		delete this.items[_n];
	}
	
	mkCookie('evendesignshopcart', this.items);
	
	top.sesspool.fSub();
	
	this.makeCart(false, _chkout);
	
}; // end removeCartItem


Shopcart.prototype.calc = function (_el) {
	//**** calculate shipping and taxes
	this.ship = parseInt(_el.value);
	var taxstr = '';
	
	this.tax = 1;
	
	switch (_el.selectedIndex) {
		case 1:
			if (this.haspst == '') {
			this.pst = this.total * this.pst_val;
			taxstr = 'PST (' + (this.pst_val * 100).toFixed(0) + '%): <h4>$ ' + this.pst.toFixed(2) + '<\/h4>';
			this.tax += this.pst_val;
			}
			//**** pst also means gst!! continue to case 2
		case 2:
			this.gst = this.total * this.gst_val;
			taxstr += (taxstr != '' ? '<br>' : '') + '( GST# 87956 7105 RT0001 )&nbsp;&nbsp; GST (' + (this.gst_val * 100).toFixed(0) + '%): <h4>$ ' + this.gst.toFixed(2) + '<\/h4>';
			this.tax += this.gst_val;
			setHTML('tax', taxstr);
			break;
		default:
			setHTML('tax', '');
	}
	
	this.grand_total = (this.total + this.pst + this.gst + this.ship).toFixed(2);
	
	setHTML ('gt', '$ ' + this.grand_total);
	
	save(_el);
	
}; // end calc


Shopcart.prototype.sendToPayPal = function (_el) {
	//**** check all item choices and shipping has been selected - then create form and send to PayPal
	var i, j = 0, k, frm = _el.form.elements, msg = [], els = [], str = '', wstr = '', opstr = '', tmpobj, tx;
	
	for (i = 0; i < frm.length; i++) {
		with (frm[i]) {
			if (type.indexOf('select') != -1 && selectedIndex == 0 && options.length > 1 && name != 'cartlist') { msg.push(title); els.push(i); }
			if (this.wholesale && id == 'pw' && value == '') { msg.push(title); els.push(i); }
			if (type == 'text' && value != this.items[name.charAt(name.length-1)].qty) { alert('Please click the "Update" button and try again!'); return; }
		}
	}
	
	if (msg.length) {
		//**** doh! missed something
		for (i in msg) if (typeof msg[i] != 'function') str += '\n\n- ' + msg[i];
		alert('Please check your order! The following choices have not been selected:\n' + str + '\n\nThank you.');
		frm[els[0]].focus();
		return;
	}	
	
	else {		
		//**** update the settings
		
		 
		for (i in this.items) {
			if (typeof this.items[i] == 'function') continue;
			j++;
			opstr = '';
			//**** paypal crap
			str += '<input type="hidden" name="item_' + j + '" value="' + this.items[i].title + '">';
			
			//**** make list of options into a neat string
			tmpobj = makeObj(this.items[i].opts);
			for (k in tmpobj) {
				if (typeof tmpobj[k] != 'function' && frm[k+i]) opstr += ' (' + k + ': ' + frm[k+i].value.Trim() + ')';
				else if (console) console.log(k,i);
			}
			
			//**** item fields
			str += '<input type="hidden" name="item_name_' + j + '" value="\'' + this.items[i].title + '\'' + opstr + '">';
			str += '<input type="hidden" name="amount_' + j + '" value="' + (this.items[i].price * this.tax).toFixed(2) + '">'; 
			str += '<input type="hidden" name="quantity_' + j + '" value="' + this.items[i].qty + '">';
			
			if ((tx = this.items[i].title.indexOf(':')) > 0) tx = this.items[i].title.substring(0, tx);
			else tx = this.items[i].title;
			if (this.items[i].qty > 1) tx += ' x' + this.items[i].qty;
			wstr += tx + ', ';
		}
		
		//**** make big paypal form
		str = '<input type="hidden" name="cmd" value="_cart">' +
			'<input type="hidden" name="upload" value="1">' +
			'<input type="hidden" name="business" value="judi@evendesigninc.com">' +
			'<input type="hidden" name="cs" value="1">' +
			'<input type="hidden" name="currency_code" value="CAD">' +
			'<input type="hidden" name="cn" value="Comments">' +
			'<input type="hidden" name="return" value="http://www.evendesigninc.com/">' +
			'<input type="hidden" name="cancel_return" value="http://www.evendesigninc.com/">' +
			'<input type="hidden" name="shipping_1" value="' + this.ship + '">' +
			str; 
		
		
		if (this.wholesale) {
			//**** collect some info for php; form to palpal sent later
			mkCookie('evendesignshopcart', this.items);
			mkCookie('evendesignshopcartops', this.formoptions);
			
			top.sesspool.fSub();
			
			//this.updateCart(d.forms['scf'].elements[0], 1);
			d.forms['scf'].action = '/inc/saveWholesale.php';
			
			//**** values to save into db
			wstr = '<input type="hidden" name="items" value="' + wstr.substring(0, wstr.length-2) + '">';
			wstr += '<input type="hidden" name="merchant" value="' + this.merchant + '">';
			wstr += '<input type="hidden" name="total" value="' + this.total + '">';
			wstr += '<input type="hidden" name="pst" value="' + this.pst + '">';
			wstr += '<input type="hidden" name="gst" value="' + this.gst + '">';
			wstr += '<input type="hidden" name="ship" value="' + this.ship + '">';
			wstr += '<input type="hidden" name="tax" value="' + this.tax + '">';
			
			//**** save the paypal stuff for later
			wstr += '<textarea name="paypal" >' + php_serialize(str) + '"</textarea>';
			
			setHTML('merchant', wstr);
			
			d.forms['scf'].submit();
		}
		
		else {			
			//**** add paypal form to page and submit
			setHTML('ppform', str);
				
			//**** clear cookies
			mkCookie('evendesignshopcart', '');
			mkCookie('evendesignshopcartops', '');
			
			top.sesspool.fSub();
			
			//**** submit form
			d.forms['paypal'].submit();
		}
	}
	
	return;
	
}; // end sendtopaypal


function save(_el) {
	var fn = false;
	
	if (_el[_el.selectedIndex].value.toLowerCase().Trim() == 'custom') {
		ans = parseInt(prompt('Please enter your custom size/length:', ''));
		
		if (ans != '' && ans) {
			tmpstr = d.cart.items[parseInt(_el.name.charAt(_el.name.length-1))].opts;
			ans = ans + (tmpstr.indexOf('in\'') != -1 ? 'in' : '');
			
			newop = new Option(ans, ans, false, true);
			tmpop = _el.options[_el.selectedIndex];
			_el.options[_el.selectedIndex] = newop;
			_el.options[_el.options.length] = tmpop;
			
			
			d.cart.items[parseInt(_el.name.charAt(_el.name.length-1))].opts = tmpstr.replace(/custom/, ans + '\',\'custom');
			
			_el.selectedIndex--; 
		}
		else _el.selectedIndex = 0; 
	}
	else if (_el[_el.selectedIndex].value.toLowerCase().Trim() == 'all colours') {
		fn = 'qty' + _el.name.substring(6);
		d.cart.formoptions[fn] = _el.form[fn].value = _el.length - 2;
		
	}
	
	d.cart.formoptions[_el.name] = _el.selectedIndex; 
	
	if (fn) d.cart.updateCart(_el);
}


function makeSelect(_label, _ary, _pos, _title) {
	//**** make a select box
	var str = '', sel, op, i, j = 1, tmp;
	
	sel = '<select name="' + _label + _pos + '" title="Please select a ' + _label + ' for the &quot;' + _title + '&quot;" class="sel" onchange="save(this)">{X}<\/select>';
	op = '<option value="VAL">STR<\/option>';
	
	if (_ary.length > 1) {
		str = op.replace(/VAL/, '');
		str = str.replace(/STR/, 'Choose a ' + _label);
	}
	
	
	for (i = 0; i < _ary.length; i++) {
		//**** keep track of what has been selected
		if (d.cart.formoptions[_label+_pos] == j || _ary.length == 1) tmp = op.replace(/">/, '" selected>');
		else tmp = op;
		
		if (_ary.length == 1) d.cart.items; //what needs to happen here???? didn't finish the line....
		
		str += tmp.replace(/VAL/, _ary[i]);
		str = str.replace(/STR/, _ary[i] + (_ary[i] == 'all colours' ? ' (' + (j-1) + ' items)' : ''));		
		j++;
	}
	
	//if (arguments[4]) str += op.replace(/VAL/, 'all colours').replace(/STR/, 'all colours');
	
	return sel.replace(/{X}/, str);
	
} // end makeSelect


function hideCart() {
	el('sc').style.display = 'none';
	d.cart.newitem = null;
	return;
} // end hideCart


function chkCart(_el) {
	
	if (_el.value == 'new') {
		ans = prompt('Please enter the name for the new cart (use a-z and 0-9 characters only):','');
		
		if (ans != '' && ans) {
			
			ans = ans.replace(/[^a-z0-9]/g, '');
			
			newop = new Option(ans, ans, false, true);
			tmpop = _el.options[_el.selectedIndex];
			_el.options[_el.selectedIndex] = newop;
			_el.options[_el.options.length] = tmpop;
			el('savecart').checked = true;
			
			_el.selectedIndex--; 
		}
		else _el.selectedIndex = 0;
	}
	
} // end chkCart


function delCart(_cart) {
	//**** a merchant wants to remove a cart file from the db
	var ans = confirm('Click OK to permanently delete the "' + _cart + '" shopping cart!');
	
	if (ans) self.location += '&delcart=' + _cart;
	
} // end delCart


function emailPW(_m) {
	//**** a merchant wants to get their pw
	var ans = confirm('Click OK to have your password emailed to the email account we have on file.');
	
	if (ans) self.location += '&emailpw=' + _m;
	
} // end emailPW


function changePW(_m) {
	//**** a merchant wants to change their pw
	var pwstr = '<tr><td align="right">old password:<\/td><td><input type="password" name="oldpw" /><\/td><\/tr>' +
				'<tr><td align="right">new password:<\/td><td><input type="password" name="newpw" /><\/td><\/tr>' +
				'<tr><td align="right">confirm password:<\/td><td><input type="password" name="newpw2" /><\/td><\/tr>' +
				'<tr><td>&nbsp;<\/td><td><input type="hidden" name="action" value="changepw" /><input type="submit" name="changepw" value="Submit" /><\/td><\/tr>';
		
	el('sctable').innerHTML = pwstr;
	el('scwrapwholesale').innerHTML = '<form name="chngpw" method="post" action="index.php?merchant=' + _m + '" onsubmit="return chkPW(this)">' + el('scwrapwholesale').innerHTML + '<\/form>';
	
} // end changePW


function chkPW(_frm) {
	var oldp = _frm.oldpw.value, newp = _frm.newpw.value;
	
	if (oldp == '') {
		alert('Sorry! Please enter your old password.');
		_frm.oldpw.focus();
		return false;
	}
	else if (newp != _frm.newpw2.value && newp != '') {
		alert('Sorry! Your new password could not be confirmed...please try again.');
		//_frm.reset();
		_frm.newpw.value = ''; _frm.newpw2.value = '';
		_frm.newpw.focus();
		return false;
	}
	else if (newp.match(/^[a-z0-9]{4,}$/i) == null) {
		if (newp.length < 4) alert('Please enter a password at least 4 characters long');
		else alert('Please only use alphanumeric characters (a-z, 0-9) in your password');
		_frm.newpw.value = ''; _frm.newpw2.value = '';
		_frm.newpw.focus();
		return false;
	}
	else return true;
	
} // end chkPW


function mkCookie(_name, _ary) {
	var i, j, str = '', isAry;
	
	if (_ary == undefined) _ary = null;
	else isAry = _ary instanceof Array || _ary.length ? 1 : 0
	
	//console.log(isAry, _ary.length, _ary);
	for (i in _ary) { //**** recreate all properties into string - check if object of arrays or straight object
		if (typeof _ary[i] == 'function') continue;
		if (isAry) {
			str += '{';
			for (j in _ary[i]) if (typeof _ary[i][j] != 'function') str += j + ':"' + _ary[i][j] + '",';
			str = str.substring(0, str.length - 1) + '},';
		}
		else str += i + ':"' + _ary[i] + '",';		//alert(i + ' - ' + _ary[i]);	
	}
		
	if (str != '') {
		str = str.substring(0, str.length - 1);
		
		if (isAry) str = '[' + str + ']';
		else str = '{' + str + '}';
		//str = str.replace(/"/g, '\\"');
		if (arguments.length == 3 && arguments[2] == 1) {
			top.sesspool.shopcart(_name, str);
			return;// _name + '=' + php_serialize(str) + ';path=/';
		}
		if (arguments.length == 3 && arguments[2].match(/\D+/)) {
			var c = top.sesspool.merch; //d.cookie.toString();
			c = c.replace(_ary, _ary + arguments[2]);
			top.sesspool.shopcart(_name, c);
			return;
		}
		else {
			top.sesspool.shopcart(_name, str);
			//el('sess').submit();
			return;// _name + '=' + escape(str) + ';path=/';
		}
	}
	else top.sesspool.shopcart(_name, str);//return _name + '=;path=/';
	
	top.sesspool.fSub();
	
} // end mkCookie


function mkEss(t, n) {
	//**** make items plural
	var s = (n > 1 ? 's' : '');
	var isS = t.length ? t.charAt(t.length - 1) : '';
	
	if (isS == 's') s = ' (pair' + (n > 1 ? 's' : '') + ')';
	
	return t + s;
	
} // end mkEss


function setHTML (_el, _val) {
	
	el(_el).innerHTML = _val;
	
} // end sethtml



function fix(_str) {
	return unescape(_str).replace(/_|\+/g, ' ').replace(/\s\s*/, ' ');	
}


function makeObj(_str) {
	//**** turn a string "object" back into a real object
	var i, curr, rslt, pc = 0, prop, obj = {}; 
	
	_str = fix(_str);
	
	if (arguments.length == 1) prop = /(\w+)\:\s?(\[[^\]]*\])/g;
	else prop = /(\w+)\:\s?([^(\}\,)]*)/g;
	
	while ( (rslt = prop.exec(_str)) != null ) {
		//alert(rslt[1]+' - '+rslt[2]);
		try {
			obj[rslt[1]] = rslt[2].replace(/[\[\]']/g, '').split(',');
		}
		catch (e) {
			obj[rslt[1]] = '';
		}
	}
	
	return obj;
	
} // end makeObj


function loadCart(_cart, _ops, _name) {
	
	var cart = eval(unescape(_cart)), ops = eval(unescape('[' + _ops + ']'));
	
	mkCookie('evendesignshopcart', cart);
	mkCookie('evendesignshopcartops', ops[0]);
	mkCookie('evendesignmerchant', _name, '*');
	
	top.sesspool.fSub();
	
	self.location = self.location + '&loadcart=true';
	//d.cart.makeCart(false);
	
} // end loadCart


function include(_tag, _file) {

  var script  = d.createElement('script');
  script.src  = _file;
  script.type = 'text/javascript';
  script.defer = true;

  tags(_tag).item(0).appendChild(script);

}


function php_serialize(obj)
{
    var string = '', count;

    if (typeof(obj) == 'object') {
        if (obj instanceof Array) {
            string = 'a:';
            tmpstring = '';
            count = 0;
            for (var key in obj) {
                tmpstring += php_serialize(key);
                tmpstring += php_serialize(obj[key]);
                count++;
            }
            string += count + ':{';
            string += tmpstring;
            string += '}';
        } else if (obj instanceof Object) {
            classname = obj.toString();

            if (classname == '[object Object]') {
                classname = 'StdClass';
            }

            string = 'O:' + classname.length + ':"' + classname + '":';
            tmpstring = '';
            count = 0;
            for (var key in obj) {
                tmpstring += php_serialize(key);
                if (obj[key]) {
                    tmpstring += php_serialize(obj[key]);
                } else {
                    tmpstring += php_serialize('');
                }
                count++;
            }
            string += count + ':{' + tmpstring + '}';
        }
    } else {
        switch (typeof(obj)) {
            case 'number':
                if (obj - Math.floor(obj) != 0) {
                    string += 'd:' + obj + ';';
                } else {
                    string += 'i:' + obj + ';';
                }
                break;
            case 'string':
                string += 's:' + obj.length + ':"' + obj + '";';
                break;
            case 'boolean':
                if (obj) {
                    string += 'b:1;';
                } else {
                    string += 'b:0;';
                }
                break;
        }
    }

    return string;
}


function objToStr() {
	//**** recreates sections and pages array locally for javascript (used by dual combo-boxes for dynamic population)
	var i, a = arguments, str = '', ok, end = '', c = 0, y, tmp;

	for (i = 0; i < a.length; i++) {

		//------------------
		tmp = a[i];

		if (typeof tmp == 'object') {
			//**** check if array
			if (tmp instanceof Array) {
				str += '[';
				end = ']';
			}
			else {
				str += '{';
				end = '}';
			}

			for (y in tmp) { //alert(typeof tmp[y]);
				if (typeof tmp[y] == 'object') { //**** item is an object - check if array
					if (tmp[y] instanceof Array) {
						str += y + ': ';
						str += objToStr(tmp[y]);
						str += ',';
					}
					else if (typeof tmp[y] == 'string') {
						str += y + ':"' + tmp[y] + '"';
						str += ',';
					}
					else {
						str += objToStr(tmp[y]);
						str += ',';
					}
				}
				else { //**** check if array element - otherwise an object property
					if (tmp instanceof Array) str += '"' + tmp[y] + '",';
					else str += y + ': "' + tmp[y] + '",';
				}
			}

			if (str.substring(str.length - 1) == ',') str = str.substring(0, str.length - 1); //chop the ,
			str += end + ',';
		}
		else str += '"' + tmp + '"';

		//----------------------------------

		if (str.substring(str.length - 1) == ',') str = str.substring(0, str.length - 1); //chop the ,

	}

	return str;

} // end objToStr



function initRollover() {
	var dt = tags('SPAN'), i;
	
	for (i = 0; i < dt.length; i++) {
	
		if ( dt[i].id.match(/popup(\d\d)/) ) {
			
			dt[i].onmouseover = function (e) { 
				var posx = 0, posy = 0;
				var div = this.id.replace(/popup/, 'pop');
				
				if (!e) var e = window.event;
				
				if (e.pageX || e.pageY) {
					posx = e.pageX;
					posy = e.pageY + el('scwrapwholesale').scrollTop;
				}
				else if (e.clientX || e.clientY) {
					posx = e.clientX;
					posy = e.clientY + el('scwrapwholesale').scrollTop;
				}
				
				
				el(div).className = 'toolhover';
				el(div).style.left = (posx - 100) + 'px';
				el(div).style.top = (posy - 200) + 'px';
				this.val = div;
			};
			
			dt[i].onmouseout = function () { el(this.val).className = 'imgpop'; };
		}
	}
}

