/* This file is only used when on a product page */

var thread_pend  = 0; // Current pending process
var thread_curr  = 0; // Process just started (that follows until the process death)
var optloop_need = 0; // Ajax calls that need to return
var optloop_curr = 0; // Ajax current call number
var curr_price   = 0; // Current threads pricing -- this should be updated if thread_pend != thread_curr
//var debug        = true; // Enables the debug console
var debug        = false; // Enables the debug console
var newPriceThread;   // Current price thread timeout, clear if something fails
var informationwin = null;
var imageLoaded    = null;

document.observe('dom:loaded', function() {
	if(debug) debug = new Product.Debug();

	new Product.ImageZoom();

	checkConditions();
	rebuildStars();
});

// Product class
var Product = {};

Product.Discount = Class.create({
	initialize: function(disc) {
		if(typeof(disc) == 'undefined') disc = null;
		this.discountHash = disc;
	},

	/**
	 * Determine the volume discount for this product
	 *
	 * @param int quant Quantity desired
	 */
	getVolumeDiscount: function(quant) {
		if(this.discountHash == null) return 1.00;

		var returndiscount = 1.00;
		disc = this.discountHash;
		disc.keys().each(function(volDiscount) {
			if(quant >= disc.get(volDiscount).get('qty')) {
				returndiscount = 1 - (disc.get(volDiscount).get('discount') / 100);
				throw $break;
			}
		});

		return returndiscount;
	}
});

Product.Debug = Class.create({
	initialize: function() {
		if($('debug')) {
			$('debug').show();
			return true;
		}

		divarea = new Element('div', {id: 'debug'}).setStyle({
			position       : 'fixed',
			bottom         : 0,
			right          : 0,
			left           : 0,
			zIndex         : 999,
			borderTop      : '1px solid #ccc',
			backgroundColor: '#efefef',
			padding        : '10px'
		});

		divarea.innerHTML = 'Debug Console';

		prearea = new Element('pre').setStyle({height: '100px', overflow: 'auto'});
		
		divarea.appendChild(prearea);
		document.body.appendChild(divarea);
	},

	append: function(text, color) {
		$('debug').down('pre').innerHTML += '<br />' + '<span style="' + (color != '' ? 'color: ' + color : '') + '">' + text + '</span>';
		$('debug').down('pre').scrollTop = 190000;
	}
});

Product.ShipQuote = Class.create({
	initialize: function(prodid, tehelement, noshipping, zipinfo) {
		this.prodid     = prodid;
		this.zipcode    = zipinfo.zip;
		this.country    = zipinfo.country;
		this.shippingel = tehelement;
		this.noshipping = noshipping;

		this.getShipEstimate();
	},

	getShipEstimate: function() {
		if(this.noshipping) return false;
		if(this.countries && this.countries.getValue()) this.country = this.countries.getValue();
		if(!this.zipcode && !this.country) {
			this.changeShipping();
			return false;
		}

		new Ajax.Request('/include/ajax.shipping.php?prodid=' + this.prodid + (this.zipcode ? '&zip=' + this.zipcode : (this.country != '' ? '&international&type=quote&country=' + escape(this.country) + '&url=' + escape(window.location.protocol + '://' + window.location.host + window.location.pathname) : '')), {
			method: 'post',
			onCreate: function() {
				this.shippingel.update('Calculating shipping, please wait ...');
			}.bind(this),
			onSuccess: function(transport) {
				if(!transport.responseText.isJSON()) {
					this.shippingel.innerHTML = 'There was a problem calculating shipping.';
					return false;
				}

				shippingJSON = transport.responseText.evalJSON();
				if(shippingJSON.errorsList) {
					if(!shippingJSON.zip) {
						this.changeShipping();
						return true;
					} else this.shippingel.innerHTML = 'There was an error calculating shipping to ' + (shippingJSON.zip ? shippingJSON.zip : shippingJSON.country) + '.';
				} else {
					this.shippingel.innerHTML = '';
					if(shippingJSON.country) {
						this.shippingel.innerHTML += '$' + addCommas(shippingJSON.to_bongo) + ' to ship to <span style="font-weight: bold">Bongo USA</span>, paid at checkout.<br />';
						this.shippingel.innerHTML += '$' + addCommas(shippingJSON.cost) + ' to <span style="font-weight: bold">' + (shippingJSON.zip ? shippingJSON.zip : shippingJSON.country) + '</span>, estimated shipping from Bongo to you.<br />';
						this.shippingel.insert(new Element('button').setStyle({ fontSize: '10px', marginTop: '2px' }).insert(new Element('img', {'src': 'http://icons.onlinecommercegroup.com/information.png', 'alt': 'About Bongo Shipping'})).insert(' About International Bongo Shipping').observe('click', function(evt) {
							Event.stop(evt);
							location = '/info/bongo-international-shipping';
						})).insert(' ');
					} else {
						this.shippingel.innerHTML += '$' + addCommas(shippingJSON.cost) + ' to zip code ' + (shippingJSON.zip ? shippingJSON.zip : shippingJSON.country) + '<br />';
					}
				}

				anchlink = new Element('button').setStyle({fontSize: '10px', marginTop: '2px'});
				anchlink.observe('click', this.changeShipping.bind(this));

				changeImage = new Element('img', {'src': 'http://images.onlinecommercegroup.com/images/icons/textfield_rename.png', 'alt': 'Change destination'});
				this.shippingel.insert(anchlink.insert(changeImage).insert(' Change destination'));
			}.bind(this)
		});

		return true;
	},

	changeShipping: function() {
		this.country = null;
		this.countries = null;

		this.shippingel.innerHTML = 'USA zip code: ';
		shippinginput = new Element('input', { type: 'text', size: 5, id: 'zip' }).setStyle({ fontSize: '11px' });

		this.shippingel.insert(shippinginput);
		this.shippingel.insert(' ').insert(new Element('button', {id: 'changeZipcode' }).setStyle({ fontSize: '11px' }).update('Estimate').observe('click', this.updateShipping.bind(this)));
		this.shippingel.insert('<br />').insert(new Element('a', {href: '#'}).update('<small style="display: block; margin-top: 2px;">Need to ship <span style="font-weight: bold">outside</span> the USA?</small>').observe('click', this.shipInternational.bind(this)));

		Event.observe('shipping', 'keypress', function(eventWatch) {
			if(eventWatch.keyCode == Event.KEY_RETURN) {
				Event.stop(eventWatch);
				this.updateShipping();
			}
		}.bind(this));
	},

	shipInternational: function(evt) {
		if(evt) Event.stop(evt);
		this.zipcode = null;

		new Ajax.Request('/include/ajax.shipping.php?international&type=countries', {
			onCreate: function() {
				this.shippingel.update('Please wait...');
			}.bind(this),
			onComplete: function(transport) {
				this.shippingel.update('');
				this.countries = new Element('select').setStyle({width: '150px', fontSize: '11px'}).update(transport.responseText);

				this.shippingel.insert(this.countries).insert(' ').insert(new Element('button', {id: 'changeZipcode' }).setStyle({ fontSize: '11px' }).update('Estimate').observe('click', this.getShipEstimate.bind(this)));
				this.shippingel.insert('<br />').insert(new Element('a', {href: '#'}).update('<small style="display: block; margin-top: 2px;">Need to ship <span style="font-weight: bold">to</span> the USA?</small>').observe('click', this.changeShipping.bind(this)));
			}.bind(this)
		});
	},

	updateShipping: function(evt) {
		if(evt) Event.stop(evt);

		if(!$('zip')) return false;
		else if(!$('zip').getValue()) alert('Please enter your zipcode.');
			else {
				this.zipcode = $('zip').getValue();
				this.getShipEstimate();
			}
	}
});

function blowUp() {
	img = $('product-image').getAttribute('src').replace('/medium', '/xlarge');

	w = window.open('about:blank','IMG','titlebar,scrollbars,resizable=1,width=700,height=550')

	if(w) {
		w.document.write('<html><body><div align="center"><a href="#" onclick="window.close(); return false"><img src="' + img + '" style="border: 0"></a></div></body></html>');
		w.document.close();
	}
}

Product.ImageZoom = Class.create({
	initialize: function() {
		this.boxWidth  = 324;
		this.boxHeight = 227;

		// Find the correct location to place box
		var offset = $('product-image').cumulativeOffset();

		var that = this;
		zoomImg = new Element('div', {id: 'zoomPicture'}).setStyle({
			display : 'none',
			position: 'absolute',
			top     : offset.top + 'px',
			left    : (offset.left + $('image-container').getWidth()) + 'px',
			width   : that.boxWidth + 'px',
			height  : that.boxHeight + 'px',
			overflow: 'hidden',
			border  : '1px solid #ccc',
			background: '#fff'
		});
		zoomImg.insert(new Element('img', {src: ''}).setStyle({'position':'absolute'}));
		document.body.appendChild(zoomImg);
		//document.body.insert(new Element('div', {id: 'zoomBug'}).setStyle({'position': 'absolute', 'top': 0, 'left': 0}));

		//$('main-image').insert(new Element('div', {id: 'zoomLocation'}).setStyle({'position': 'absolute', 'top': 0, 'left': 0}));

		$('product-image').observe('mouseover', this.showHide.bind(this, true));
		$('product-image').observe('mouseout', this.showHide.bind(this, false));
	},

	zoomer: function(evt) {
		if(typeof(this.dims) != 'object') return;

		imgview = Element.cumulativeOffset($('product-image'));
		xPos = ((Event.pointerX(evt) - imgview.left) * this.dims.xRatio) - this.dims.centerX;
		yPos = ((Event.pointerY(evt) - imgview.top) * this.dims.yRatio) - this.dims.centerY;

		if((xPos + (this.dims.centerX * 2)) > this.dims.largeWidth) xPos = this.dims.largeWidth - (this.dims.centerX * 2);
			else if(xPos < 0) xPos = 0;
		if((yPos + (this.dims.centerY * 2)) > this.dims.largeHeight) yPos = this.dims.largeHeight - (this.dims.centerY * 2);
			else if(yPos < 0) yPos = 0;

		//$('zoomBug').update(xPos + '/' + this.dims.largeWidth + ' \\\\ ' + this.dims.centerX + "<br />" + (xPos + (this.dims.centerX * 2)));

		$('zoomPicture').down('img').setStyle({
			'top'  : (yPos * -1) + 'px',
			'left' : (xPos * -1) + 'px'
		});

		//$('zoomLocation').setStyle({'width': '10px', 'height': '10px', 'top': (Event.pointerX(evt) - imgview.left) + 'px', 'left': (Event.pointerX(evt) - imgview.left) + 'px', 'background': '#ccc'});
	},

	showOnLoad: function(source) {
		$('zoomPicture').show();
		$('zoomPicture').down('img').writeAttribute('src', source);

		var centerX = ($('zoomPicture').down('img').getWidth() - $('product-image').getWidth()) / 2;
		var centerY = ($('zoomPicture').down('img').getHeight() - $('product-image').getHeight()) / 2;
		if(centerX > (this.boxWidth / 2)) centerX = (this.boxWidth / 2);
		if(centerY > (this.boxHeight / 2)) centerY = (this.boxHeight / 2);

		this.dims = Object.extend({
			smallHeight: $('product-image').getHeight(),
			smallWidth : $('product-image').getWidth(),
			largeHeight: $('zoomPicture').down('img').getHeight(),
			largeWidth : $('zoomPicture').down('img').getWidth(),
			centerX    : centerX,
			centerY    : centerY,
			xRatio     : $('zoomPicture').down('img').getWidth()  / $('product-image').getWidth(),
			yRatio     : $('zoomPicture').down('img').getHeight() / $('product-image').getHeight()
		});

		if(this.boxWidth >= this.dims.largeWidth || this.boxHeight >= this.dims.largeHeight) {
			$('zoomPicture').hide();
			return false;
		}

		$('product-image').observe('mousemove', this.zoomer.bind(this));
	},

	showHide: function(show) {
		if(show) {
			source = $('product-image').readAttribute('src').replace('/medium', '/xlarge');

			this.largeImage = new Image();

			var objThat = this;
			this.largeImage.onload = function() { objThat.showOnLoad(source); };

			this.largeImage.src = source;
		} else {
			$('product-image').stopObserving('mousemove');
			if(typeof(this.largeImage) != 'undefined') {
				this.largeImage.onload = function() {};
			}
			$('zoomPicture').hide();
		}
	}
});

function rebuildStars(tempstar) {
	var i = 1;

	$$('.stars').each(function(x) {
		if(tempstar && tempstar < i) x.setAttribute('src', sharedurl + '/img/star_off.png');
		else if(!tempstar && starcount < i) x.setAttribute('src', sharedurl + '/img/star_off.png');
			else x.setAttribute('src', sharedurl + '/img/star.png');
		++i;
	});
}

function submitStar(count) {
	new Ajax.Request('/content/rating-new.php?product_id=' + product_id + '&rate=' + count, {
		onSuccess: function(transport) {
			response = transport.responseText.evalJSON();
			if(!response.rating) alert(response.message);
				else {
					starcount = response.rating;
					rebuildStars(starcount);
					alert('Your vote has been counted.');
				}
		}
	});
}

function debugAdd(text, color) {
	if(typeof(debug) != 'object') return false;
	debug.append(text, color);
}

function imageScroller(count) {
	$('scroll-images').scrollLeft = $('scroll-images').scrollLeft + count;
	timeout = setTimeout('imageScroller(' + count + ');', 100);
}

function checkConditions(recursecount) {
	if(typeof(recursecount) == 'undefined') recursecount = 0;
	changed = false;

	conditions.keys().each(function(condition_id) {
		conditions.get(condition_id).keys().each(function(product_id) {
			//debugAdd('Getting product id value' + product_id);
			if(($('Option' + condition_id).value != conditions.get(condition_id).get(product_id)) || $('Option' + condition_id).disabled == true) {
				debugAdd('Disabling option name ' + product_id + ' because cond ' + condition_id + ' value ' + $('Option' + condition_id).value + ' != ' + conditions.get(condition_id).get(product_id), 'red');
				if($('OptionItem' + product_id).visible()) changed = true;
				$('OptionItem' + product_id).hide();
				$('OptionH0_' + product_id).disabled = $('OptionH2_' + product_id).disabled = $('OptionH3_' + product_id).disabled = $('Option' + product_id).disabled = true;
			} else {
				debugAdd('Enabling option name ' + product_id + ' because cond ' + condition_id + ' value ' + $('Option' + condition_id).value + ' != ' + conditions.get(condition_id).get(product_id), 'green');
				if(!$('OptionItem' + product_id).visible()) changed = true;
				$('OptionItem' + product_id).show();
				$('OptionH0_' + product_id).disabled = $('OptionH2_' + product_id).disabled = $('OptionH3_' + product_id).disabled = $('Option' + product_id).disabled = false;
			}
		})
	});

	// If there were any changes we need to cycle back through a max of five times ...
	if(changed && recursecount < 5) checkConditions(++recursecount);
}

function updatePrice() {
	if(!$F('quantity')) return false;

	++thread_pend;
	thread_curr = thread_pend;
	usedajax = null;
	ready = false;

	optloop_need = optloop_curr = 0;
	curr_price = baseprice;
	opt_prices = 0.00;

	// Make sure no new conditions have been met and need to be activated
	checkConditions();

	$('price').innerHTML += ' ';
	loadingImg = new Element('img', {'src': sharedurl + '/img/loading.gif'});
	$('price').appendChild(loadingImg);
/*
	curprice = baseprice;


		  "fabric": $H({
						"ajax": $H({
									 "js"      : "am_bolster_pillow",
									 "upcharge": .25
									 "func"    : "am_bolster_pillow",
									 "file"    : ".../content/func.php",
								   })
					   })
		  });


*/

	// Options
	debugAdd('Initiating thread ' + thread_curr);
	poption.keys().each(function(optname) {
		if(poption.get(optname).get('ajax')) {
			ajaxinfo = poption.get(optname).get('ajax');
			debugAdd('Adding Ajax for option ' + optname);
			debugAdd('-- function: ' + ajaxinfo.get('func'));
			debugAdd('-- file: ' + ajaxinfo.get('file'));
			debugAdd('-- upcharge: ' + ajaxinfo.get('upcharge'));

			if(!ajaxinfo.get('func') || usedajax == ajaxinfo.get('func')) return false;
			usedajax = ajaxinfo.get('func');
			setTimeout(ajaxinfo.get('func') + '(' + thread_curr + ',\'' + ajaxinfo.get('file') + '\',' + ajaxinfo.get('upcharge') + ')', 1);
			++optloop_need;
		} else if(poption.get(optname).get($F('Option' + optname)) && poption.get(optname).get($F('Option' + optname)).get('percentage')) {
			if($('Option' + optname).disabled) return;
			debugAdd('Calculating percentage for option ' + optname);

			opt_prices += (baseprice * (poption.get(optname).get($F('Option' + optname)).get('percentage') / 100));
		} else if(poption.get(optname).get($F('Option' + optname)) && poption.get(optname).get($F('Option' + optname)).get('price')) {
			if($('Option' + optname).disabled) return;
			debugAdd('Calculating price for option ' + optname);

			opt_prices += poption.get(optname).get($F('Option' + optname)).get('price');
		}
	});

	curr_price += opt_prices;
	ready = true;

	// Shipping
	//if($('shipping')) curprice += parseFloat($('shipping').innerHTML * qty);

	newPriceThread = setTimeout('postPrice(' + thread_curr + ');', 10);
}

function postPrice(thread) {
	// Is this "thread" the current one?
	if(thread_curr == thread) newPriceThread = setTimeout('postPrice(' + thread_curr + ');', 75);
		else {
			clearTimeout(newPriceThread);
			return false;
		}

	// If the Ajax calls are complete, we can finally update the price ...
	if(optloop_need == optloop_curr) {
		// Quantities

		qty = parseInt($F('quantity')) || 1; // Change to 1 if NaN

		if(typeof(quantity) != 'undefined' && qty > quantity) {
			qty = quantity;
			alert('There are only ' + quantity + ' of these items in stock, your quantity has been set to ' + quantity + '.');
		}

		if(qty >= 100000 || qty <= 0) qty = 1;

		$('quantity').setValue(qty);

		yourDiscount = discount.getVolumeDiscount(qty) || 1;
		curr_price *= qty || 1;
		curr_price *= yourDiscount;

		// Show the price
		$('price').update(addCommas(curr_price));
		if($('discounts')) {
			if(yourDiscount < 1) $('discounts').update(parseInt((100 - yourDiscount * 100)) + '% discount');
				else $('discounts').update('');
		}
		clearTimeout(newPriceThread);
	}
}

function checkOptionImage(id) {
	//optiselect = $('Option' + id).down('option[value="' + $F('Option' + id) + '"]');
	//img = $('OptionDescription' + id).down('div[class="' + optiselect.innerHTML + '"]>img');

	//if($('optImgPreview' + id)) $('optImgPreview' + id).remove();
	//$('Option' + id).insert({ after: new Element('div', {id: 'optImgPreview' + id}).setStyle({textAlign: 'left'}).insert('<img src="' + img.readAttribute('src') + '" style="width: 150px" />') });
}

function doAjaxCall(ajaxCall, thread) {
	debugAdd('* Getting page ' + sPage, 'orange');

	new Ajax.Request(ajaxCall, {
		method: 'get',
		onSuccess: function(transport) {
			// Check to see if this thread is still running ...
			if(thread != thread_curr) {
				clearTimeout(newPriceThread);
				return false;
			}

			debugAdd('Received this from Ajax: ' + transport.responseText);
			curr_price = transport.responseText;

			++optloop_curr;
		}
	});

	if($('internal')) {
		new Ajax.Updater('internal', ajaxCall + '&debug');
		debugAdd('* Getting debug info ' + sPage, 'pink');
	}
}

function addCommas(nStr) {
	if(!nStr) return '0.00';
	nStr = parseFloat(nStr);
	// Round it ...
	nStr = Math.round(nStr * 100) / 100;
	// Now fix it ...
	nStr = nStr.toFixed(2);
	nStr = nStr.toString();

	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;
}

function openWindow(title, text) {
	if(typeof(jsPopup) == 'undefined') jsPopup = template + '/jstemplate.html';

	var informationwin = window.open(jsPopup, 'infowin', 'width=700,height=400,scrollbars=yes,status=no');

	setTimeout(function() {
		informationwin.document.getElementById('placer').innerHTML = $(text).innerHTML;
		informationwin.document.getElementById('title').innerHTML = title;
		informationwin.document.title = title;
	}, 400);
}

function jsReturn(inputid, rootid, old, id, name, image) {
	debugAdd('+ jsReturn variables (' + inputid + ', ' + rootid + ', ' + old + ', ' + id + ', ' + name + ', ' + image + '),', 'orange');
	$('Option' + inputid).setValue(id);
	$('prettyview' + inputid).down('img').setAttribute('src', image);
	$('prettyview' + inputid).down('div').innerHTML = name.replace(/(<([^>]+)>)/ig, '');

	updatePrice();
}

function changeMainImage(imageURL, alt_text, alt_title, videoURL, videoLargeURL) {
	// If we're trying to get the same image, let's not run this function (could cause issues with video)
	if(imageLoaded == imageURL) return false;
	if(!videoLargeURL) videoLargeURL = null;
	imageLoaded = imageURL;

	$('product-image').setAttribute('src', imageURL);
	$('product-image').setAttribute('alt', alt_text);
	$('product-image').setAttribute('title', alt_title);
	$('image_title_text').update(alt_title);
	$('main-video').hide();
	$('main-video').update();
	$('main-image').show();
	if(typeof(videoURL) != 'undefined' && videoURL != '') viewProductVideo(videoURL, imageURL, videoLargeURL);
}

function viewProductVideo(videoURL, imageURL, videoLargeURL, showLargeVideo) {
	if(!showLargeVideo) {
		vidWidth = 324;
		vidHeight = 227;
		vidContainer = 'main-video';
		if(videoLargeURL) {
			anchLink = new Element('a', {'href': '#'});
			anchLink.onclick = function() {
				viewProductVideo(videoLargeURL, imageURL, null, true);
				return false;
			}
			imgLink = new Element('img', {
				'src': iconsURL + '/color_swatch.png',
				'alt': 'Watch in high quality'
			});
			anchLink.appendChild(imgLink);
			anchLink.innerHTML += ' View High Quality';
			
			$('image_title_text').update(anchLink);
		}
		stretching = true;
	} else {
		vidWidth = 720;
		vidHeight = 480;
		vidContainer = 'largeVideoContainer';
		$('main-video').hide();
		$('main-video').update();
		$('main-image').show();
		openLargeVideo();
		stretching = false;
	}

	var s1 = new SWFObject('/template/shared/swf/player.swf', 'player', vidWidth, vidHeight, '9');
	s1.addParam('allowfullscreen', 'true');
	s1.addParam('allowscriptaccess', 'always');
	s1.addParam('flashvars', 'file=' + videoBaseURL + '/' + videoURL + '&image=' + imageURL + '&plugins=googlytics-1&autostart=true' + (stretching ? '&stretching=exactfit' : '') + (!showLargeVideo ? '' : '&bufferlength=15') + (typeof(videoLogo) == 'undefined' ? '' : '&logo=' + videoLogo));
	s1.write(vidContainer);

	if(!showLargeVideo) {
		$('main-image').hide();
		$('main-video').show();
	}
}

function closeLargeVideo() {
	$('videoOverlay').update();
	$('videoOverlay').remove();
}

function openLargeVideo() {
	div = new Element('div', {'id': 'videoOverlay'}).setStyle({
		background: 'url(/template/shared/img/overlay.png)',
		position  : 'fixed',
		top       : '0px',
		bottom    : '0px',
		right     : '0px',
		left      : '0px',
		zIndex    : '9998'
	});

	divContainer = new Element('div').setStyle({
		background: '#EFEFEF',
		margin    : '0 auto',
		width     : '720px',
		marginTop : '50px',
		padding   : '0px',
		border    : '1px solid #fff'
	});

	titleh4 = new Element('h4').setStyle({
		background     : 'url(/template/shared/img/section-title-background.png)',
		backgroundColor: 'red',
		padding        : '4px',
		fontSize       : '12px',
		fontWeight     : 'bold',
		color          : '#fff'
	});
	titleh4.update('High Quality Video');
	divContainer.appendChild(titleh4);

	divVideo = new Element('div', {'id': 'largeVideoContainer'});
	divContainer.appendChild(divVideo);
	divClose = new Element('div').setStyle({ padding: '5px' });

	aClose = new Element('a', {'href'   : '#'}).setStyle({
		marginTop: '8px',
		fontSize : '12px'
	});
	aClose.onclick = function() { closeLargeVideo(); return false; };

	closeImg = new Element('img', {
		'src': iconsURL + '/cancel.png',
		'alt': 'Cancel'
	});
	aClose.appendChild(closeImg);
	aClose.innerHTML += ' Close';

	divClose.appendChild(aClose);
	divContainer.appendChild(divClose);
	div.appendChild(divContainer);

	document.body.appendChild(div);
}

function cartSample(sid) {
	new Ajax.Request('/content/new_cart_sample.php?sid=' + sid, {
		onSuccess: function(transport) {
			response = transport.responseText.evalJSON();
			if(!response.passed) alert('Fabric sample not available.');
				else alert('Fabric sample has been carted.');
		}
	});
}