/* 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;
var Product = {};

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

	checkConditions();
	rebuildStars();

	$('addProduct').observe('submit', cartSubmit.bind(this));
});

Product.Image = Class.create({
	initialize: function(options) {
		if(Product.Image.initialized) return false;
		Product.Image.initialized = this;

		Product.Image.Hooks = {
			FileName: [this.mainFilename.bind(this)],
			Failure : [],
			Loading : []
		};

		this.options = Object.extend({
			currentImage: -1,
			imageZoom   : function(evt) {},
			imageSelect : this.imageSelect.bind(this)
		}, options || {});

		this.main_image = $('main-image');
		this.product_image = $('product-image');
		this.image_selector = $$('div.image-selector a');
		this.image_title_text = $('image_title_text') || new Element('div');

		this.main_image.observe('click', this.options.imageZoom.bind(this));
		this.product_image.observe('error', this.imageFailure.bind(this, this.product_image, 'medium'));
		this.product_image.observe('load', this.imageLoaded.bind(this));

		counter = 0;
		this.image_selector.each(function(x) {
			var imageId = x.readAttribute('id');
			if(imageId === null) { // For legacy templates (v. 1, 2, 3)
				imageId = counter++;
				x.setAttribute('id', 'selectImage' + imageId);
			} else {
				imageId = imageId.replace('selectImage', '');
			}

			x.observe('click', function(evt) {
				Event.stop(evt);
				this.changeImage(imageId);
			}.bind(this));

			thumb = x.down('img.thumb-image');
			if(thumb) {
				thumb.store('image_id', imageId)
					.observe('error', this.imageFailure.bind(this, thumb, 'thumb'));
			}
		}.bind(this));

		return this;
	},

	displayVideo: function(imageId) {
		var image = Product.Image.List[imageId];

		var videoURL = image.video;
		var preview  = image.image_directory + '/medium/' + image.image_filename;

		var vidWidth = 324;
		var vidHeight = 227;
		var stretching = true;
		var showLargeVideo = false;
		var videoLogo = 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=' + preview + '&plugins=googlytics-1&autostart=true' + (stretching ? '&stretching=exactfit' : '') + (!showLargeVideo ? '' : '&bufferlength=15') + (typeof(videoLogo) == 'undefined' ? '' : '&logo=' + videoLogo));
		s1.write('main-video');

		return this;
	},

	mainFilename: function(image_info) {
		if(!image_info.filenames) {
			image_info.filenames = {};
			image_info.filenames.thumb  = image_info.image_directory + '/thumb/' + image_info.image_filename;
			image_info.filenames.medium = image_info.image_directory + '/medium/' + image_info.image_filename;
			image_info.filenames.large  = image_info.image_directory + '/large/' + image_info.image_filename;
		}
	},

	showVideo: function(hide) {
		if(!hide) {
			$('main-video').update('').hide();
			this.main_image.show();
		} else {
			$('main-video').show();
			this.main_image.hide();
		}

		return this;
	},

	imageFailure: function(element, size) {
		if(element.hasClassName('load-fail')) return false;
		element.addClassName('load-fail');
		var newImageName = null;

		Product.Image.Hooks.Failure.each(function(x) {
			newImageName = x(element, size);
		});

		if(newImageName === null) {
			var image_id = element.retrieve('image_id');

			var image_info = Product.Image.List[image_id];
			if(!image_info) return false;

			var image_url = image_info[size + '_image'];
			if(!image_url) image_url = null;
		}

		element.writeAttribute('src', image_url);

		return true;
	},

	imageLoading: function() {
		if(this.loading_div) return;
		this.loading_div = new Element('div').addClassName('loading-img').update('<img src="' + sharedurl + '/img/loading.gif" alt="Loading..." />');
		this.main_image.insert({
			top: this.loading_div
		});
	},

	imageLoaded: function() {
		if(this.loading_div) {
			this.loading_div.remove();
			delete this.loading_div;
		}
	},

	changeImage: function(imageId) {
		if(!Product.Image.List[imageId] || !Product.Image.List[imageId]) return false;

		this.imageLoading();

		this.options.currentImage = imageId;
		var image = Product.Image.List[imageId];

		Product.Image.Hooks.FileName.each(function(x) {
			x(image);
		});

		this.product_image.store('image_id', imageId)
			.removeClassName('load-fail')
			.writeAttribute('src', image.filenames.medium)
			.writeAttribute('alt', image.alt_text);
		this.image_title_text.update(image.alt_title);

		this.main_image.down('a').writeAttribute('href', image.filenames.large).
			writeAttribute('title', image.alt_title.unescapeHTML().replace(/(\&quot\;|\&#8221\;)/g, '"').replace(/(\&#8217;|\&#039;)/g, '\''));

		if(image.video) this.displayVideo(imageId).showVideo(true);
			else this.showVideo(false);

		this.options.imageSelect(imageId);

		return this;
	},

	imageDeselect: function() {
		this.image_selector.each(function(x) {
			x.removeClassName('selected');
		});

		return this;
	},

	redrawImages: function(initialize) {
		if(initialize) this.options.currentImage = 0;
		if(this.options.currentImage === -1) return;

		images = $$('img.thumb-image');
		if(images.size()) {
			images.each(function(image){
				var image_id = image.retrieve('image_id');
				if(!image_id) return false;
				Product.Image.Hooks.FileName.each(function(x) {
					x(Product.Image.List[image_id]);
				});

				image.writeAttribute('src', Product.Image.List[image_id].filenames.thumb);
			});
		}

		this.changeImage(this.options.currentImage);
	},

	imageSelect: function(imageId) {
		this.imageDeselect();
		var select_image = $('selectImage' + imageId);
		if(select_image) select_image.addClassName('selected');

		return this;
	}
});

checkOptionImage = (function() {});

Product.Image.initialized = false;
Product.Image.Hooks = {};

Product.Image.Zoomy = Class.create(Product.Image, {
	initialize: function($super) {
		if(!$super({imageSelect: this.imageSelect.bind(this)})) return false;

		new Zoomy($('main-image').down('a.image-link'));
		return true;
	}
});

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

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

		var returndiscount = 1.00;
		var 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;
		}

		var 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';

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

		divarea.appendChild(prearea);
		document.body.appendChild(divarea);
		return true;
	},

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

Product.Calculator = Class.create({
	getValue: function(param_name) {
		if(!calc_parameters || !calc_parameters[param_name]) return false;

		var value_id = null;

		calc_parameters[param_name].each(function(value_id_test) {
			option_value = $('Option' + value_id_test);

			if(option_value && !option_value.disabled) {
				value_id = value_id_test;
				throw $break;
			}
		});

		return value_id;
	}
});

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

				var 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 = '';
					this.shippingel.innerHTML += '$' + addCommas(shippingJSON.cost) + ' to zip code ' + (shippingJSON.zip ? shippingJSON.zip : shippingJSON.country) + '<br />';
				}

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

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

		return true;
	},

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

		this.shippingel.innerHTML = 'USA zip code: ';
		var 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();
		}
		return true;
	}
});

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

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

	if(w) {
		w.document.write('<html><body><div align="center"><img src="' + img + '" style="cursor:pointer" onclick="window.close();"></div></body></html>');
		w.document.close();
	}
}

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) {
			var response = transport.responseText.evalJSON();
			if(!response.rating) alert(response.message);
				else {
					var 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);
	return true;
}

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

var changeHiddenStatus = (function(option_id, value) { // value = true then hide
	var option_item = $('OptionItem' + option_id);
	if(!option_item) throw 'Option not found on page.';

	$('OptionH0_' + option_id).disabled =
	$('OptionH2_' + option_id).disabled =
	$('OptionH3_' + option_id).disabled = value;

	if(document['addproduct']['OptionList[' + option_id + '][1]'].type != 'undefined') {
		document['addproduct']['OptionList[' + option_id + '][1]'].disabled = value;
	} else {
		for (i = 0; i < document['addproduct']['OptionList[' + option_id + '][1]'].length; i++) {
			document['addproduct']['OptionList[' + option_id + '][1]'][i].disabled = value;
		}
	}

	var visible = option_item.visible();

	if(value) option_item.hide();
		else option_item.show();

	return !(value && !visible || !value && visible);
});

function checkConditions(recursecount) {
	var current_options = $('addProduct').serialize(true);

	if(typeof(recursecount) == 'undefined') recursecount = 0;
	var changed = false;

	conditions.keys().each(function(condition_id) {
		conditions.get(condition_id).keys().each(function(product_id) {
			var opt_changed = false;

			if(typeof(value = current_options['OptionList[' + condition_id + '][1]']) == 'undefined'
			   || value != conditions.get(condition_id).get(product_id)) {
				opt_changed = changeHiddenStatus(product_id, true);
			} else {
				opt_changed = changeHiddenStatus(product_id, false);
			}

			if(opt_changed && changed == false) changed = true;
		});
	});

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

function updatePrice(initialize) {
	var form = $('addProduct');
	if(form == null) return false;

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

	optloop_need = optloop_curr = 0;
	curr_price = baseprice;
	opt_prices = 0.00;
	var use_function = false;

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

	var current_options = form.serialize(true);

	if(!current_options.Quant) return false;

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

	// Options
	poption.keys().each(function(optname) {
		if(poption.get(optname).get('ajax')) {
			ajaxinfo = poption.get(optname).get('ajax');

			if(!ajaxinfo.get('func') || usedajax == ajaxinfo.get('func')) return;
			usedajax = ajaxinfo.get('func');

			var fn = window[ajaxinfo.get('func')];
			if(typeof fn === 'function') {
				use_function = fn.bind(document.window, thread_curr, ajaxinfo.get('file'), ajaxinfo.get('upcharge'));
			} else {
				// Invalid calculator
				return;
			}

			++optloop_need;
		} else if(poption.get(optname).get(current_options['OptionList[' + optname + '][1]']) && poption.get(optname).get(current_options['OptionList[' + optname + '][1]']).get('percentage')) {
			if (typeof current_options['OptionList[' + optname + '][1]'] == 'undefined') return true;

			opt_prices += (baseprice * (poption.get(optname).get(current_options['OptionList[' + optname + '][1]']).get('percentage') / 100));
		} else if(poption.get(optname).get(current_options['OptionList[' + optname + '][1]']) && poption.get(optname).get(current_options['OptionList[' + optname + '][1]']).get('price')) {
			if (typeof current_options['OptionList[' + optname + '][1]'] == 'undefined') return true;

			opt_prices += poption.get(optname).get(current_options['OptionList[' + optname + '][1]']).get('price');
		}

		return true;
	});

	if(use_function !== false) use_function();

	curr_price += opt_prices;
	ready = true;

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

	// Change images if neccessary
	if(!initialize && Product.Image.initialized) {
		Product.Image.initialized.redrawImages();
	}

	return true;
}

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) {
		clearTimeout(newPriceThread);

		// Quantities
		var 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);

		if(!isNaN(curr_price)) {
			yourDiscount = discount.getVolumeDiscount(qty) || 1;

			if($('price-before-discount')) $('price-before-discount').update(curr_price);
			if($('discount-amount')) $('discount-amount').update(yourDiscount);

			if(yourDiscount != 1.0) {
				curr_price *= yourDiscount;
				curr_price = ceiling(curr_price, 2);
			}

			if($('price-no-qty')) $('price-no-qty').update(ceiling(curr_price, 2));

			curr_price *= qty || 1;

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

		if(1 == 2) drawOptions();
	}

	return true;
}

function drawOptions() {
	var optlist = new Element('div');
	var form = $('addProduct');
	var val;
	if(optlist != null) {
		optlist.update();
		var list = [];
		var ele = form.getElements();
		ele.each(function(s) {
			if(s.disabled == true) return false;
			var ids = s.name.match(/^OptionList\[(\d{1,})\]\[(\d{1})\]$/);
			if(ids == null) return false;
			if(Object.isUndefined(list[ids[1]])) list[ids[1]] = [];
			if(ids[2] == 0) list[ids[1]][0] = s.getValue();
			else if(ids[2] == 1) {
				if(s.tagName == 'SELECT') {
					list[ids[1]][1] = s.options[s.selectedIndex].text;
				} else {
					if(s.tagName == 'INPUT') {
						if(s.type == 'text') list[ids[1]][1] = s.getValue();
						else if(s.type == 'radio') {
							val = form.getInputs('radio', s.name).find(function(n){return n.checked});
							list[ids[1]][1] = val.up().next('span').innerHTML;
						} else if(s.type == 'hidden') {
							val = s.up('div');
							if(val.hasClassName('fabsamples')) {
								list[ids[1]][1] = val.down('div.ppOptionGroupCap').innerHTML;
							}
						}
					}
				}
				if(Object.isUndefined(list[ids[1]][2])) {
					var el = s.up('.stepContentGroupCell');
					if(el && el.id) el = el.id;
						else return false;
					var match = el.match(/stepContent(\d{1,})/);
					list[ids[1]][2] = match[1];
				}
			}

			return true;
		});
		var newgrp, group, newlist;
		var disableNewHead = false;
		group = 0;
		newHead = new Element('tr').addClassName('optlistHead').update('<td colspan="2">Current Product Configuration:</td>');

		list.each(function(s) {
			var grpName = '';
			if(s[1] == undefined) return false;
			if(s[2] != group) {
				var step_indicator = $('stepIndicator' + s[2]);
				if(!step_indicator) {
					disableNewHead = true;
					return false;
				}
				if(newgrp) optlist.insert(newgrp);
				newgrp = new Element('tr').addClassName('optlistGroup');
				grpName = $('stepIndicator' + s[2]).down('.stepLabels').innerHTML + ':';
				newgrp.insert(new Element('td').addClassName('optlistTitle').update(grpName));
				newlist = new Element('td').addClassName('optlist');
				group = s[2];
			}

			newgrp.insert(newlist.insert(new Element('div').addClassName('optlistItem').update(s[0] + ': <span class="optPrint">' + s[1] + '</span>')));
			return true;
		});

		if(!disableNewHead) {
			$('optionlist').update(newHead);
			$('optionlist').insert(optlist.innerHTML);
		}
	}
}

function ceiling(value, precision) {
	if(!precision) precision = 2;
	precision = Math.pow(10, parseInt(precision));

	value = parseFloat(value) * precision;
	value = Math.ceil(value);

	return (value / precision);
}

var changeCartStatus = (function(status) {
	Product.cartable = !status;
});

var cartSubmit = (function(evt) {
	if(!Product.cartable) {
		alert('There are errors that need correcting before this product can be carted.');
		Event.stop(evt);
	}
});

Product.Options = Class.create({
	initialize: function() {
		this.form = $('addProduct');
		this.get_fabric = false;
		this.show_actual = false;
	},

	getExtraPricing: function(params) {
		var additional_pricing = [];

		Object.keys(params).each(function(key) {
			key_input = this.form[key];
			key_post  = key.replace(/^OptionList\[(\d{1,})\]\[(\d{1})\]$/, '$1');

			if(typeof(key_input.type) == 'undefined' && key_input[0].type == 'radio') {
				for(i = 0; key_input.length > i; i++) {
					if(!key_input[i].checked) additional_pricing.push(escape('add[' + key_post + '][]') + '=' + key_input[i].value);
				}
			} else if(key_input.tagName == 'SELECT') {
				if(!key_input.name.match(/^OptionList/)) return;

				for(i = 0; key_input.length > i; i++) {
					if(!key_input[i].selected) additional_pricing.push(escape('add[' + key_post + '][]') + '=' + key_input[i].value);
				}
			}
		}.bind(this));

		if(this.get_fabric) {
			// Get the selected fabrics from disabled fields to get better pricing info
			$$('.selected_fabrics').each(function(x) {
				key_post  = x.name.replace(/^OptionList\[(\d{1,})\]\[(\d{1})\]$/, '$1');
				additional_pricing.push(escape('fabric[' + key_post + '][]') + '=' + $('OptionH0_' + key_post).value);
				additional_pricing.push(escape('fabric[' + key_post + '][]') + '=' + x.value);
				additional_pricing.push(escape('fabric[' + key_post + '][]') + '=' + $('OptionH2_' + key_post).value);
				additional_pricing.push(escape('fabric[' + key_post + '][]') + '=' + $('OptionH3_' + key_post).value);
			}.bind(this));
		}

		return additional_pricing;
	},

	setExtraPrice: function(option_id, value_id, price) {
		// Feature NOT READY!!!!
		return;

		if(this.show_actual) {
			if(price < 0) price = '-$' + Math.abs(price).toString();
				else price = '$' + price;
		} else {
			if(price < 0) price = 'Decreases Price';
				else price = 'Increases Price';
		}

		option_element = $('OptionPrice' + option_id + '_' + value_id);
		if(option_element) {
			option_element.update(price);
		} else {
			option_element = $('Option' + option_id);
			option_value = option_element.down('option[value=' + value_id + ']');
			option_value.innerHTML = option_value.innerHTML + ' (' + price + ')';
		}
	},

	clearExtraPricing: function() {
		$$('.option_prices').invoke('update');

		this.form.select('select').each(function(element) {
			for(i = 0; element.length > i; i++) {
				element[i].innerHTML = element[i].innerHTML.replace(/ \(([0-9\.\$\-]+|Increases Price|Decreases Price)\)/, '');
			}
		});

		return this;
	}
});

/**
 * @param {String} ajaxCall The URL to call
 * @param
 */
function doAjaxCall(ajaxCall, thread, postParams, callback) {
	if(!postParams) postParams = {};

	product_options = new Product.Options().clearExtraPricing();
	additional_pricing = product_options.getExtraPricing(postParams);

	postParams = Object.toQueryString(postParams);

	if(additional_pricing.size()) postParams += '&' + additional_pricing.join('&');

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

			if(transport.responseText.isJSON() && isNaN(transport.responseText)) {
				var jreturn = transport.responseText.evalJSON();
				if(!jreturn.success) {
					curr_price = '--.-- (Price Unavailable)';
					changeCartStatus(true);
				} else {
					curr_price = jreturn.price;
					changeCartStatus(false);
				}

				if (typeof callback != 'undefined' && typeof window[callback] != 'undefined') window[callback](jreturn, product_options);

				var messages = [];
				if(jreturn.messages && jreturn.messages.size && jreturn.messages.size() > 0) {
					jreturn.messages.each(function(x) {
						messages.push(x.message);
					});

					alert(messages.join("\n"), false);
				}
			} else curr_price = transport.responseText;

			++optloop_curr;

			return true;
		}
	});

	if($('internal')) {
		new Ajax.Updater('internal', ajaxCall + '&debug', {method: 'post', parameters: postParams});
	}
}

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();

	var x = nStr.split('.');
	var x1 = x[0];
	var 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';

	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, fabric_sku, id, name, image, junker, fabObj) {
	$('Option' + inputid).setValue(id);
	$('prettyview' + inputid).down('img').setAttribute('src', image);
	$('prettyview' + inputid).down('div').innerHTML = name.replace(/(<([^>]+)>)/ig, '') + ' (' + fabric_sku + ')';

	// Show/hide directional and let user know about the new option
	$H({'fabric': 'direction', 'fabric_2': 'direction_2'}).each(function(pair) {
		if(typeof(fabObj) == 'object' && inputid == calcparam.get(pair.key)) {
			if(calcparam.get(pair.value)) {
				changeHiddenStatus(calcparam.get(pair.value), !fabObj.stripe);
				checkConditions();
			}
		}
	});

	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);
	return true;
}

function viewProductVideo(videoURL, imageURL, videoLargeURL, showLargeVideo) {
	var stretching, vidWidth, vidHeight, vidContainer;
	if(!showLargeVideo) {
		vidWidth = 324;
		vidHeight = 227;
		vidContainer = 'main-video';
		if(videoLargeURL) {
			var anchLink = new Element('a', {'href': '#'});
			anchLink.onclick = function() {
				viewProductVideo(videoLargeURL, imageURL, null, true);
				return false;
			}
			var 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() {
	var 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'
	});

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

	var 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);

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

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

	var 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) {
			var response = transport.responseText.evalJSON();
			if(!response.passed) alert('Fabric sample not available.');
				else alert('Fabric sample has been carted.');
		}
	});
}

Product.cartable = true;
