(function($) {
 
	jQuery.fn.DreamCart = function(stock, submit_callback, options ) {
		
		var opts = jQuery.extend({}, $.fn.DreamCart.defaults, options);
		
		// iterate through each matched element
		return this.each(function() {
			$this = $(this);
			// build main options before element iteration
			o = jQuery.meta ? jQuery.extend({}, opts, $(this).data()) : opts; // build element specific options
			if ( stock == null) { 
				var optns = o; 
				DrawDonate("#"+$(this).attr('id'), optns);
				var cartid = "#"+$(this).attr('id');
				var id = cartid+" form"; 
				jQuery(id).submit(function() { 
					if (jQuery(id+' #amount').val() > null) {
						if (jQuery(id+' #amount').val() < o.minimum_value) {
							jQuery(id+' #message').html("PayPal takes &euro;0.36 commission for a &euro;1 donation. Please enter at least &euro;1.35, thank you!").fadeIn();
							return false; // prevent the form from submitting
						} else {
							jQuery(id+' #message').html("<img src='css/images/loader.gif' align='absmiddle' /> Transferring to PayPal, please wait...").fadeIn();
							$(id+" input[disabled]").removeAttr("disabled"); //enable all disabled fields
				  			return true; // submit the form
						}
					} else {
						jQuery(id+' #message').html("Please enter the amount you wish to donate and try again.").fadeIn();
						return false; // prevent the form from submitting
					}
				});

			} else {
				var cartid = "#"+$(this).attr('id');
				var optns = o; var addButton = false;
				if (stock.substr(0,1) == "#") { 
					$(stock+" .addtocart").click(function() { 
						var itemid = $(this).parent().attr('id');
						jQuery.fn.DreamCart.AddItem(cartid, itemid, optns);
					}); 
					if ($(stock).children().size() == 1) addButton = $(stock+" :first-child").attr('id');
				} else StockShop(cartid, stock, optns); 
				CreateCart(cartid, optns, addButton);
				
				$(cartid+" .addtocart").click(function() { jQuery.fn.DreamCart.AddItem(cartid, addButton, optns); });
				$(".product .weight, .product .itemid, .product .quantity").hide();
				
				var id = cartid+" form";
				if (typeof submit_callback == 'function') {
					jQuery(id).submit(function() { 
						passval = submit_callback(this, optns); 
						if (passval) {
							jQuery(id+' #message').html("<img src='css/images/loader.gif' align='absmiddle' /> Transferring to PayPal, please wait...").fadeIn();
							$(id+" input[disabled]").removeAttr("disabled"); 
						}
						return passval; //enable all disabled fields
					});
				} else {
					jQuery(id).submit(function() {
						if (jQuery(id+' #input_amount').val() > null) {
							if (jQuery(id+' #input_amount').val() < o.minimum_value) {
								jQuery(id+' :submit').next().html("PayPal takes &euro;0.35 commission for a &euro;1 donation. Please purchase at least &euro;1.35 from the shop, thank you!").fadeIn();
								return false; // prevent the form from submitting
							} else {
								jQuery(id+' :submit').next().html("<img src='css/images/loader.gif' align='absmiddle' />Transferring to PayPal, please wait...").fadeIn();
								$(id+" input[disabled]").removeAttr("disabled"); //enable all disabled fields
								return true; // submit the form
							}
						} else {
							jQuery(id+' :submit').next().html("You have not added anything to you shopping cart yet. Please use the add to cart buttons to make a purchase.").fadeIn();
							return false; // prevent the form from submitting
						}
					});
				}
			};
		});
			
	};
 
	//Public Functions
	StockShop = function(cartid, stock, optns) {
		
		var markup = "";
		for(shopitem in stock) { 
			
			markup = "<div id='"+stock[shopitem].itemid+"' class='product'><img src='"+stock[shopitem].image+"' /><div class='name' id='"+stock[shopitem].url+"'>"+stock[shopitem].name+"</div><div class='description'>"+stock[shopitem].description+"</div><div class='quantity'>"+stock[shopitem].quantity+"</div><div class='weight'>"+stock[shopitem].weight.toFixed(2)+"</div><div class='currency'>&euro; </div><div class='price'>"+stock[shopitem].price+"</div><input class='addtocart' value='' type='submit' title='Add this item to the basket'/></div>";
			$(stock[shopitem].shelfid).append(markup);
			AddtoCartButton(cartid, stock[shopitem].shelfid+" #"+stock[shopitem].itemid, optns);
		}
	};

	CommonForm = function(SubmitLabel, cmd, optns) {

		if (SubmitLabel == undefined) SubmitLabel = "Donate";
		if (cmd == undefined) cmd = "_donations";  
		
		var servermod = ""; if (optns.business == undefined) servermod = "sandbox.";
		var action = "https://www."+servermod+"paypal.com/cgi-bin/webscr"; 
		if (optns.business == "de_testpage") 
			action = "http://www.dreamsedge.ie/DreamAnywhere/modules/paypal/test.php";
		var business = "philip@dreamsedge.ie"; if (optns.business != undefined) business = optns.business;  
		var shipping = 1; if (optns.shipping != undefined) shipping = optns.shipping;  
		var note = 1; if (optns.note != undefined) note = optns.note;  
		var currency = "EUR"; if (optns.currency != undefined) currency = optns.currency;  
		var language = "IE"; if (optns.language != undefined) language = optns.language;  
		var bn = "DreamsedgeStudios_Donate_WPS_IE"; if (optns.bn != undefined) bn = optns.bn;  
		var tax = 0; if (optns.tax != undefined) tax = optns.tax;  
		var informed = 'Please keep me informed.'; if (optns.informed != undefined) informed = optns.informed;  
				
		var responseText = "<form id='form_paypal' action='"+action+"' method='post' target='_parent'>"+
		  "<input type='hidden' name='cmd' id='cmd' value='"+cmd+"'>"+
		  "<input type='hidden' name='business' id='business' value='"+business+"'>"+
		  "<input type='hidden' name='no_shipping' id='no_shipping' value='"+shipping+"'>"+
		  "<input type='hidden' name='no_note' id='no_note' value='"+note+"'>"+
		  "<input type='hidden' name='currency_code' id='currency_code' value='"+currency+"'>"+
		  "<input type='hidden' name='lc' id='lc' value='"+language+"'>"+
		  "<input type='hidden' name='return' id='return' value='"+optns.successurl+"'>"+
		  "<input type='hidden' name='cancel_return' id='cancel_return' value='"+optns.cancelurl+"'>"+
		  "<input type='hidden' name='bn' id='bn' value='"+bn+"'>"+
		  "<input type='hidden' name='notify_url' id='notify_url' value='"+optns.notifyurl+"'>"+
		  "<input type='text' name='tax' id='tax' value='"+tax+"' disabled='disabled'>"+
		  "<input type='submit' name='submit' id='submit' value='' class='"+SubmitLabel+"' title='Continue to checkout contents of basket' />"+
		  "<br /><input type='checkbox' name='custom' id='custom' checked='checked'>&nbsp;"+informed+
		  "&nbsp;&nbsp;<div id='message'></div></form>";
		  
		  return responseText;
	};

	AddtoCartButton = function(cartid, itemid, optns) {
		$(itemid+" .addtocart").click(function() { jQuery.fn.DreamCart.AddItem(cartid, itemid, optns); });
	};

	//Private Functions
	DrawDonate = function(donateid, optns) {
		
		var name = "Donation"; if (optns.name != undefined) name = optns.name;  
		var tax = 0; if (optns.tax != undefined) tax = optns.tax;  
		
		var responseText = CommonForm(null, null, optns);
		responseText = responseText + 
			"<p><small>Once you click on 'Donate', you will be transferred to PayPal "+
			"where you can enter your payment information.</small></p>";
		$(donateid).html(responseText);

		responseText = "<input type='hidden' name='item_name' id='item_name' value='"+name+"'>"+
		  	"<label>Amount (&euro;) : </label><input type='text' name='amount' id='amount' width='10' class='text' />";
		$(donateid+" :submit").prev().before(responseText); 
		
};
	
	DrawServices = function(cartid, optns) {
		responseText = ""; for (x in optns.postage_rates) {
			var checked = ""; if (x == optns.service) checked = " checked";
			responseText = responseText + "<input type='radio' name='SP_Using' id='SP_Using' value='"+x+
				"'"+checked+" />"+x+"<br />";
		}
		$(cartid+" #form_paypal #SP_UsingSet").html(responseText);
		if ($(cartid+" #SP_UsingSet > input").length == 1) $("#Services").hide();
		$(cartid+" #form_paypal #SP_UsingSet input").click(function() { 
			DrawZones(cartid, optns); DrawSizes(cartid, optns); CalculateTotal(cartid, optns); });
		$(cartid+" #form_paypal #ServiceToggle").click(function() { 
			$(cartid+" #form_paypal #SP_UsingSet").toggle("slow"); 
			var h = $(this).html(); 
			if (h == "Show Delivery Services") { $(this).html("Hide Delivery Services"); $(this).css("background-image", "url(css/images/Collapse.png)"); }
			else { $(this).html("Show Delivery Services"); $(this).css("background-image", "url(css/images/Expand.png)"); }
		});
	}
	
	DrawZones = function(cartid, optns) {
		var selservice = $(cartid+" #SP_UsingSet > input:checked").val();
		
		responseText = ""; for (x in optns.postage_rates[selservice]) {
			var msg = ""; for (y in optns.postage_rates[selservice][x]["Countries"]) { 
				msg = msg + optns.postage_rates[selservice][x]["Countries"][y] + ", "; }
			msg = msg.substr(0, msg.length-2);
			if (msg == "") msg = "The rest of the world";
			var checked = ""; if (x == optns.zone) checked = " checked";
			responseText = responseText + "<input type='radio' name='SP_To' id='SP_To' value='"+x+"'"+checked+" />"+msg+"<br />";
		}
		$(cartid+" #form_paypal #SP_ToSet").html(responseText);
		if (optns.hide_zones) $(cartid+" #Zones").hide();
		if ($(cartid+" #SP_ToSet > input").length == 1) $("#Zones").hide();
		$(cartid+" #form_paypal #SP_ToSet input").click(function() { DrawSizes(cartid, optns); CalculateTotal(cartid, optns); });
		$(cartid+" #form_paypal #ZoneToggle").click(function() { 
			$(cartid+" #form_paypal #SP_ToSet").toggle("slow"); 
			var h = $(this).html(); 
			if (h == "Show Delivery Zones") { $(this).html("Hide Delivery Zones"); $(this).css("background-image", "url(css/images/Collapse.png)"); }
			else { $(this).html("Show Delivery Zones"); $(this).css("background-image", "url(css/images/Expand.png)"); }
		});
	}
	
	DrawSizes = function(cartid, optns) {
		var selservice = $(cartid+" #SP_UsingSet > input:checked").val();
		if (typeof selservice == "undefined") selservice = optns.service;
		var selzone = $(cartid+" #SP_ToSet > input:checked").val();
		if (typeof selzone == "undefined") selzone = optns.zone;
		
		responseText = ""; 
		for (x in optns.postage_rates[selservice][selzone]["Sizes"]) {
			var checked = ""; if (x == optns.size) checked = " checked";
			responseText = responseText + "<input type='radio' name='SP_Size' id='SP_Size' value='"+x+"'"+checked+" />"+
				optns.postage_rates[selservice][selzone]["Sizes"][x]["Description"]+"<br />";
		} 
		$(cartid+" #form_paypal #SP_SizeSet").html(responseText);
		if (optns.hide_sizes) $(cartid+" #Sizes").hide();
		if ($(cartid+" #SP_SizeSet > input").length == 1) $("#Sizes").hide();
		$(cartid+" #form_paypal #SP_SizeSet input").click(function() { CalculateTotal(cartid, optns); });
		$(cartid+" #form_paypal #SizesToggle").click(function() { 
			$(cartid+" #form_paypal #SP_SizeSet").toggle("slow"); 
			var h = $(this).html(); 
			if (h == "Show Delivery Sizes") { $(this).html("Hide Delivery Sizes"); $(this).css("background-image", "url(css/images/Collapse.png)"); }
			else { $(this).html("Show Delivery Sizes"); $(this).css("background-image", "url(css/images/Expand.png)"); }
		});
	}
	
	CreateCart = function(cartid, optns, addButton) {

		var weight_unit = "kgs"; if (optns.weight_unit != undefined) weight_unit = optns.weight_unit;  
		var handling = 0; if (optns.handling != undefined) handling = optns.handling;  
		var shipping = 0; if (optns.shipping != undefined) shipping = optns.shipping;  
		var tax = 0; if (optns.tax != undefined) tax = optns.tax;  

		var responseText = "<h1></h1>"; 
		var addButtonCode = ""; if (addButton)
			addButtonCode = "<input id='addbutton' name='addbutton' type='button' value='' class='addtocart' title='Add another item to the cart' />";	
		
		responseText = responseText + CommonForm("BuyNow", "_cart", optns);
		responseText = responseText + 
			"<p><small>Once you click on 'Buy Now', you will be transferred to PayPal "+
			"where you can enter your payment information.</small></p><div class='footer'></div>";
		$(cartid).html(responseText);
		$("#form_paypal #tax").remove();
		responseText = "<input type='hidden' name='upload' value=1>"+
		  "<input type='hidden' name='weight_unit' value='"+weight_unit+"'>"+
		  "<div id='Title'>"+
			"<div id='description' class='itemname'>Description</div><div id='id' class='itemnumber'>ID</div>"+
			"<div id='quantity' class='itemquantity'>Qty.</div><div id='price' class='itemprice'>&euro;</div>"+
		  "</div>"+
		  "<div id='items'></div>"+
		  addButtonCode+
		  "<div style='clear: both;'></div>"+
		  "<label for='tax' class='TotalLabel'>Tax on items</label>"+
		  "<input type='text' id='tax' name='tax' value='"+tax+"' disabled='disabled' class='fees'>";
			if (optns.include_handling) {
				responseText = responseText +
		  "<label for='handling' class='TotalLabel'>Handling (inc. Tax)</label>"+
		  "<input type='text' id='handling' name='handling' value='"+handling+"' disabled='disabled' class='fees'>";
			}
			if (optns.include_shipping) {
				responseText = responseText +
		  "<label for='shipping' class='TotalLabel'>Shipping (inc. Tax)</label>"+
		  "<input type='text' id='shipping' name='shipping' value='"+shipping+"' disabled='disabled' class='fees'>";
			}
		responseText = responseText +
		  "<div style='clear: both;'></div>"+
		  "<label class='TotalLabel'>Total: &euro;</label><div class='CartTotal'>0</div>"+
		  "<div style='clear: both; height: 0;'></div>"+
		  "<div id='Services'><div id='ServiceToggle'>Hide Delivery Services</div><div id='SP_UsingSet'></div></div>"+
		  "<div id='Zones'><div id='ZoneToggle'>Hide Delivery Zones</div><div id='SP_ToSet'></div></div>"+
		  "<div id='Sizes'><div id='SizesToggle'>Hide Delivery Sizes</div><div id='SP_SizeSet'></div></div>";
		$(cartid+" :submit").before(responseText);
		
		if (($.cookie('DreamPay') !== undefined) && ($.cookie('DreamPay') != "") && ($.cookie('DreamPay') !== null)) {
			var data = $.cookie('DreamPay').split("&");
			if (data.length > 2) {
				for(x=0;x < (data.length);x++) { 
					pair = data[x].split('=');
					if (pair[0] == 'itemid') itemid = pair[1];
					x++; qty = data[x].split('=');
					x++; os0 = data[x].split('=');
					x++; os1 = data[x].split('=');
					if ( $("#"+itemid).length > 0 ) jQuery.fn.DreamCart.AddItem(cartid, itemid, optns, qty[1], os0[1], os1[1]);
				}
			}
		} else {
			$(cartid+" .itemnumber").hide();
		}

		DrawServices(cartid, optns); DrawZones(cartid, optns); DrawSizes(cartid, optns);
//		$(cartid+" #quantity").live("change", CalculateTotal(cartid, optns));

	};
	
	UpdateCookies = function(cartid) {

		var v = "";
		$(cartid+" #items .cartrow").each(function () {
			var qtyid = $('.itemquantity', this).attr('id');
			var os0id = $('.option_value_0', this).attr('id');
			var os1id = $('.option_value_1', this).attr('id');
			v = v + "itemid=" + $('.itemid', this).html() + "&";
			v = v + qtyid + "=" + $('.itemquantity', this).val() + "&";
			v = v + os0id + "=" + $('.option_value_0', this).val() + "&";
			v = v + os1id + "=" + $('.option_value_1', this).val() + "&";
		});
		v = v.substr(0,v.length-1);
		
		$.cookie('DreamPay',v, { expires: 7, path: '/', domain: document.domain });
	};

	jQuery.fn.DreamCart.AddItem = function(cartid, itemid, optns, qty, _os0, _os1) { 
		
		var name = $("#"+itemid+" .name").html().replace("\'","");
		var quantity = $("#"+itemid+" .quantity").html();
		if (qty != null) quantity = qty;
		var price = $("#"+itemid+" .price").html();
		var weight = $("#"+itemid+" .weight").html();
		var on0 = $("#"+itemid+" .option_name_0").html();
		var os0 = $("#"+itemid+" .option_value_0").html();
		if (_os0 != null) os0 = _os0;
		var on1 = $("#"+itemid+" .option_name_1").html();
		var os1 = $("#"+itemid+" .option_value_1").html();
		if (_os1 != null) os1 = _os1;
		var tax = 0;

		var responseText = "<input type='text' id='item_name_"+optns.current_item+"' name='item_name_"+optns.current_item+"'"+
		  "value='"+name+"' class='itemname'>"+
		  "<input type='text' id='item_number_"+optns.current_item+"' name='item_number_"+optns.current_item+"'"+
		  "value='"+itemid+"' class='itemnumber'>"+
		  "<input type='text' id='quantity_"+optns.current_item+"' name='quantity_"+optns.current_item+"'"+
		  " value='"+quantity+"' class='itemquantity'>"+
		  "<input type='text' id='amount_"+optns.current_item+"' name='amount_"+optns.current_item+"'"+
		  " value='"+price+"' class='itemprice'>"+
		  "<input type='text' id='weight_"+optns.current_item+"' name='weight_"+optns.current_item+"'"+
		  " value='"+weight+"' class='itemweight'>";
		if (optns.current_item == 1) {
			if (optns.include_shipping) {
		  responseText = responseText +
		  "<input type='hidden' id='shipping_"+optns.current_item+"' name='shipping_"+optns.current_item+"'"+
		  " value=1 class='itemshipping'>";
			}
			if (optns.include_handling) {
		  responseText = responseText +
		  "<input type='hidden' id='handling_"+optns.current_item+"' name='handling_"+optns.current_item+"'"+
		  " value=1 class='itemhandling'>";
			}
		}
		  responseText = responseText +
		  "<input type='hidden' id='tax_"+optns.current_item+"' name='tax_"+optns.current_item+"'"+
		  " value='"+tax+"' class='itemtax'>";
		if (on0 !== null) { 
		  responseText = responseText +
		  "<input type='hidden' id='on0_"+optns.current_item+"' name='on0_"+optns.current_item+"' value='"+on0+"' class='option_name_0'>"+
		  "<input type='text' id='os0_"+optns.current_item+"' name='os0_"+optns.current_item+"' value='"+os0+"' class='option_value_0'>";
		}
		if (on1 !== null) {
		  responseText = responseText +
		  "<input type='hidden' id='on1_"+optns.current_item+"' name='on1_"+optns.current_item+"' value='"+on1+"' class='option_name_1'>"+
		  "<input type='text' id='os1_"+optns.current_item+"' name='os1_"+optns.current_item+"' value='"+os1+"' class='option_value_1'>";
		}
		  responseText = responseText +
		  "<input type='button' id='remove_"+optns.current_item+"' name='remove_"+optns.current_item+"'"+
		  " value='' class='itemremove' title='Remove this item from basket'>";
		
		var add_item = false; if (name != null) add_item = true; // For products removed form shop
		if (optns.accumulate) {
			
			$(cartid+" #items .cartrow").each(function () {
				var thisitemid = $(' .itemid', this).html();
				var cart_os0 = $(' .option_value_0', this).val();
				var cart_os1 = $(' .option_value_1', this).val();
				
				if ((itemid == thisitemid) && (os0 == cart_os0) && (os1 == cart_os1)) { 
					var v = Number($(' .itemquantity', this).val())+Number(quantity);
					$(' .itemquantity', this).val(v);
					add_item = false;
				}
			});
		}
		if (add_item) { 
			var markup = "<div id='item_"+optns.current_item+"' class='cartrow' style='visibility: hidden;'></div>";
			$(cartid+" #items").append(markup); 
			var thisitem = " #item_"+optns.current_item;
			responseText = "<div class='itemid'>"+itemid+"</div>" + responseText;
			$(cartid+thisitem).html(responseText);
			$(cartid+thisitem).show("slow");
			$(cartid+thisitem).css("visibility","visible");
			var thisquantity = " #item_"+optns.current_item+" .itemquantity";
			$(cartid+thisquantity).change(function() { CalculateTotal(cartid, optns); });
			var thisremove = " #item_"+optns.current_item+" .itemremove";
			$(cartid+thisremove).click(function() { RemoveItem(cartid, $(this).parent().attr('id'), optns); });
			optns.current_item++;
			for (cl in optns.hide_classes) { $(optns.hide_classes[cl]).hide(); };
			for (cl in optns.disable_classes) { $(optns.disable_classes[cl]).attr("disabled","'disabled'"); };
		}

		CalculateTotal(cartid, optns);
				
	};

	RemoveItem = function(cartid, itemid, optns) {

		if (optns.accumulate) { 
			
			var shopitemid = $("#"+itemid+" .itemid", cartid).html();
			var price = $("#"+shopitemid+" .price").html();
			
			var thisquantity = " #"+itemid+" .itemquantity";
			var q = parseInt($(thisquantity, cartid).val())-1;
			$(thisquantity, cartid).val(q);		

			CalculateTotal(cartid, optns);
			
		} else { q = 0; }
		
		if (q == 0) {
			$(cartid+" #"+itemid).hide("slow", function() { 
				$(this).remove(); CalculateTotal(cartid, optns); 
				var id = cartid+" #items";
				var item_count = 1;
				$(id).children().each(function() {
					$(this).attr('id', "item_"+item_count).attr('name', "item_"+item_count);
					$(".itemname", this).attr('id', "item_name_"+item_count).attr('name', "item_name_"+item_count);
					$(".itemnumber", this).attr('id', "item_number_"+item_count).attr('name', "item_number_"+item_count);
					$(".itemquantity", this).attr('id', "quantity_"+item_count).attr('name', "quantity_"+item_count);
					$(".itemprice", this).attr('id', "amount_"+item_count).attr('name', "amount_"+item_count);
					$(".itemremove", this).attr('id', "remove_"+item_count).attr('name', "remove_"+item_count);
					$(".itemweight", this).attr('id', "weight_"+item_count).attr('name', "weight_"+item_count);
					$(".itemtax", this).attr('id', "tax_"+item_count).attr('name', "tax_"+item_count);
					$(".option_name_0", this).attr('id', "on0_"+item_count).attr('name', "on0_"+item_count);
					$(".option_value_0", this).attr('id', "os0_"+item_count).attr('name', "os0_"+item_count);
					$(".option_name_1", this).attr('id', "on1_"+item_count).attr('name', "on1_"+item_count);
					$(".option_value_1", this).attr('id', "os1_"+item_count).attr('name', "os1_"+item_count);
					item_count++;
				});
				optns.current_item = item_count;
			});
		}
		
	};

	CalculateTotal = function(cartid, optns) {
		var tot = 0.00; var weight = 0.00; var tot_tax = 0.00;

		$(cartid+" #items .cartrow").each(function() { 

			var thisqty = parseInt($(" .itemquantity", this).val());
			var thisweight = parseFloat($(" .itemweight", this).val())*thisqty;

			var thisprice = parseFloat($(" .itemprice", this).val());
			var shopitemid = $(" .itemid", this).html();
			var thisprice = parseFloat($("#"+shopitemid+" .price").html());

			var dis_str = $("#"+shopitemid+" .discounts").html(); eval("var dis = {"+dis_str+"}");
			for (var key in dis) { var ky=parseInt(key); if (thisqty < ky) { break; }; k = ky; };
			thisprice = thisprice*(1-dis[k]);

			var rt = optns.tax_rate/100;
			if (optns.tax_included) { thisprice = (thisprice/(1+rt)); thisprice = Math.round(thisprice*100)/100; }
			$(" .itemprice", this).val(thisprice);
			
			var tax = (thisprice * rt); tax = Math.round(tax*100)/100;
			$(" .itemtax", this).val(tax);

			tot_tax = tot_tax + (tax * thisqty);
			tot = tot + (thisqty * thisprice); 
			weight = parseFloat(weight) + thisweight;
		});
		
		var ser = $(cartid+" #SP_UsingSet > input:checked").val(); 
		if (typeof ser === "undefined") ser = optns.service;
		var reg = $(cartid+" #SP_ToSet > input:checked").val();
		if (typeof reg === "undefined") reg = optns.zone;
		var sze = $(cartid+" #SP_SizeSet > input:checked").val();
		if (typeof sze === "undefined") sze = optns.size;

		var items = optns.postage_rates[ser][reg]["Sizes"][sze]["Weights"]; 
		
		var rt = optns.tax_rate/100;
		if (optns.include_shipping) {
			var sp = items["0.00"];
			for(w in items) if ((weight-w) >= 0) sp = items[w]; else break;
			if (tot == 0) sp = "0.00"; // if cart is emptied shipping should return to zero
			if (!optns.tax_included) sp=sp*(1+rt); 
			sp = Math.round(sp*100)/100;
			$(cartid+" #shipping").val(sp.toFixed(2));
			$(cartid+" #shipping_1").val(sp.toFixed(2));
		} else sp = "0.00";
		if (optns.include_handling) {
			var hd = optns.handling_charge;
			if (tot == 0) hd = "0.00"; // if cart is emptied handling should return to zero
			if (!optns.tax_included) hd=hd*(1+rt); 
			hd = Math.round(hd*100)/100;
			$(cartid+" #handling").val(hd.toFixed(2));
			$(cartid+" #handling_1").val(hd.toFixed(2));
		} else hd = "0.00";
		tot = tot + parseFloat(tot_tax) + parseFloat(sp) + parseFloat(hd);
		$(cartid+" #tax").val(tot_tax.toFixed(2));
		$(cartid+" .CartTotal").html(tot.toFixed(2)); 

		UpdateCookies(cartid);
		
		
	};

	jQuery.fn.DreamCart.thispath = window.location.href.substring(0, window.location.href.lastIndexOf("/")+1);
	jQuery.fn.DreamCart.defaults = { accumulate: true, current_item: 1, tax_included : true, tax_rate : 21.5, include_handling: true, include_shipping : true, handling_charge : 1.5, hide_classes: [ ".itemnumber", ".itemweight", ".itemid", ".itemshipping", ".itemhandling" ], disable_classes: [".itemname",  ".itemprice"], cancelurl : jQuery.fn.DreamCart.thispath + "paypalcancel.php", notifyurl : jQuery.fn.DreamCart.thispath + "paypal-ipn.php", successurl : jQuery.fn.DreamCart.thispath + "paypalsuccess.php", minimum_value: 1.35, service : "Standard (An Post)", zone : "Z0", size : "S3", hide_sizes : true, hide_zones : true,
	
	postage_rates: { 
		"Standard (An Post)" : {
			"Z0" : { "Countries" : { "IE" : "Ireland", "NI" : "Northern Ireland" }, 
			         "Sizes" : {
						"SO" : { "Description" : "Letter", 
							   "Weights" : {"0.05" : "0.55"} },
						"S1" : { "Description" : "Envelope",
							   "Weights" : {"0.05" : "0.95", "0.25": "1.35", "0.5": "1.9", "1.0" : "3.0"} },
						"S2" : { "Description" : "Packet",
							   "Weights" : {"0.05" : "2.20", "0.25": "2.7", "0.5" : "3.85", "1.0" : "6.0", "1.5" : "7.5"} }
						,"S3" : { "Description" : "Parcel",
							   "Weights" : {"0.05" : "6.5", "1.5" : "7.50", "2.5" : "8.7", "3.0" : "9.8", "3.5" : "11.00", "4.0" : "12.00", "4.5" : "13.00", "5.0" : "14.00", "6.0" : "15.00", "7.0" : "16.00", "8.0" : "17.00", "9.0" : "18.00", "10.0" : "19.00", "11.0" : "20.00", "12.0" : "21.00", "13.0" : "22.00", "14.0" : "23.00", "15.0" : "24.00", "16.0" : "25.00", "17.0" : "26.00", "18.0" : "27.00", "19.0" : "28.00"} }
					} },
			"Z1" : { "Countries" : {"UK" : "Great Britain"},
			         "Sizes" : {
						"SO" : { "Description" : "Letter", 
							   "Weights" : {"0.05" : "0.82"} },
						"S1" : { "Description" : "Envelope",
							   "Weights" : {"0.05" : "1.5", "0.25": "3.0", "0.5": "4.25"} },
						"S2" : { "Description" : "Packet",
							   "Weights" : {"0.05" : "2.70", "0.25": "3.5", "0.5" : "4.85", "1.0" : "7.5", "1.5" : "10.75"} }
						,"S3" : { "Description" : "Parcel",
							   "Weights" : {"0.05" : "18.25", "1.5" : "22.0", "2.0" : "25.0", "2.5" : "27.50", "3.0" : "31.0", "3.5" : "33.0", "4.0" : "35.0", "4.5" : "37.50", "5.0" : "40.00", "6.0" : "41.00", "7.0" : "42.00", "8.0" : "43.00", "9.0" : "44.00", "10.0" : "45.00", "11.0" : "46.00", "12.0" : "47.00", "13.0" : "48.00", "14.0" : "49.00", "15.0" : "50.00", "16.0" : "51.00", "17.0" : "52.00", "18.0" : "53.00", "19.0" : "54.00"} }
					} },
			"Z2" : { "Countries" : {"AT" : "Austria","BE" : "Belgium","BG" : "Bulgaria","CY" : "Cyprus","CZ" : "Czech Republic","DK" : "Denmark","EE" : "Estonia","FI" : "Finland","FR" : "France","DE" : "Germany","GR" : "Greece","HU" : "Hungary","IT" : "Italy","LV" : "Latvia","LT" : "Lithuania","LU" : "Luxembourg","MT" : "Malta","NL" : "Netherlands","PL" : "Poland","PT" : "Portugal","RO" : "Romania","SK" : "Slovakia","SI" : "Slovenia","ES" : "Spain","SE" : "Sweden"},
			         "Sizes" : {
						"SO" : { "Description" : "Letter", 
							   "Weights" : {"0.05" : "0.82"} },
						"S1" : { "Description" : "Envelope",
							   "Weights" : {"0.05" : "1.5", "0.25": "3.0", "0.5": "4.25"} },
						"S2" : { "Description" : "Packet",
							   "Weights" : {"0.05" : "2.70", "0.25": "3.5", "0.5" : "4.85", "1.0" : "7.5", "1.5" : "10.75"} }
						,"S3" : { "Description" : "Parcel",
							   "Weights" : {"0.05" : "22.0", "1.5" : "28.0", "2.0" : "30.0", "2.5" : "34.0", "3.0" : "38.0", "3.5" : "44.0", "4.0" : "48.5", "4.5" : "52.50", "5.0" : "55.00", "6.0" : "58.00", "7.0" : "61.00", "8.0" : "64.00", "9.0" : "67.00", "10.0" : "70.00", "11.0" : "73.00", "12.0" : "76.00", "13.0" : "79.00", "14.0" : "82.00", "15.0" : "85.00", "16.0" : "88.00", "17.0" : "91.00", "18.0" : "94.00", "19.0" : "97.00"} }
					} },
			"Z3" : { "Countries" : { }, 
			         "Sizes" : {
						"SO" : { "Description" : "Letter", 
							   "Weights" : {"0.05" : "0.82"} },
						"S1" : { "Description" : "Envelope",
							   "Weights" : {"0.05" : "1.5", "0.25": "3.0", "0.5": "4.25"} },
						"S2" : { "Description" : "Packet",
							   "Weights" : {"0.05" : "2.70", "0.25": "3.5", "0.5" : "4.85", "1.0" : "10.4", "1.5" : "16.6"} }
						,"S3" : { "Description" : "Parcel",
							   "Weights" : {"0.05" : "22.0", "1.5" : "28.0", "2.0" : "30.0", "2.5" : "34.0", "3.0" : "38.0", "3.5" : "44.0", "4.0" : "48.5", "4.5" : "52.50", "5.0" : "55.00", "6.0" : "60.00", "7.0" : "65.00", "8.0" : "70.00", "9.0" : "75.00", "10.0" : "80.00", "11.0" : "85.00", "12.0" : "90.00", "13.0" : "95.00", "14.0" : "100.00", "15.0" : "105.00", "16.0" : "110.00", "17.0" : "115.00", "18.0" : "120.00", "19.0" : "125.00"} }
					} }
		}
//		,"Other" : { }
	}
};

})(jQuery);

function AddX(cartid, itemid, optns) {
	jQuery.fn.DreamCart.AddItem(cartid, itemid, optns); 
	tb_remove();
}

/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tb_pathToImage = "css/images/loader.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			
			$("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TB_overlay").unbind();
						$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
					}
				}else{
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
