// product properties in order of refinement
var a_keys = ['tw','s', 'b','fn','cl', 'lb'];

// text for select boxes
var a_labels = {
	'tw' : {'l':'Select Type'},
	's' : {'l':'Select Size','a':'Show all Sizes', 'm':'sizes'},
//	'f' : {'l':'Select Format', 'a':'Show all Formats', 'm':'formats'},
	'b' : {'l':'Refine by Brand','a':'Show all Brands', 'm':'brands'},
	'fn' : {'l':'Refine by Finish','a':'Show all Finishes', 'm':'finishes'},
	'cl' : {'l':'Select Color'},
	'lb' : {'l':'Select Weight'}
};
 // list of the properties that are URL encoded for transport
var a_decodeKeys = ['n','b','w','p','d'];

// decode encoded properties
var a_urlReplace = [
	{'f':/\%27/g, 't':"'"},
	{'f':/\%28/g, 't':"("},
	{'f':/\%29/g, 't':")"},
	{'f':/\%2A/g, 't':"*"},
	{'f':/\%7E/g, 't':"~"},
	{'f':/\%21/g, 't':"!"},
	{'f':/\+/g, 't':'%20'}
];
function f_urlDecode(s_string) {
	if (!s_string) return '';
  	for(var i = 0; i < a_urlReplace.length; i++)
		s_string = s_string.replace(a_urlReplace[i]['f'], a_urlReplace[i]['t']);
    return decodeURIComponent(s_string);
}
for (var i = 0; i < a_prodList.length; i++) {
	for (var p = 0; p < a_decodeKeys.length; p++) {
		s_prop = a_decodeKeys[p];
		a_prodList[i][s_prop] = f_urlDecode(a_prodList[i][s_prop]);
	}
	if (!a_prodList[i]['w']) continue;
	if (a_prodList[i]['w'].match(/^(\d+)lb\s+([\w\s]+)$/, '')) {
		a_prodList[i]['lb'] = Number(RegExp.$1) + ' lb';
		a_prodList[i]['tw'] = RegExp.$2;
	}
	else
		alert('Incorrect format of weight: ' + a_prodList[i]['w']);
}

var a_sortFunctions = {
	's': function (a, b) { return f_getArea(a) - f_getArea(b); },
	'lb': function (a, b) { return parseInt(a) - parseInt(b); }
}
function f_getArea (s_size) {
	var a_tokens = s_size.split(/x/i);
	if (a_tokens.length < 2) return 0;
	
	// cleanup tokens
	var s_width  = a_tokens[0].replace(/^\D+/,'');
	var s_height = a_tokens[1].replace(/^\D+/,'');
	
	var n_width = s_width.match(/^\s*(\d+)\s+(\d+)\/(\d+)/)
		? Number(RegExp.$1) + Number(RegExp.$2) / Number(RegExp.$3)
		: parseFloat(s_width);
	var n_height = s_height.match(/^\s*(\d+)\s+(\d+)\/(\d+)/)
		? Number(RegExp.$1) + Number(RegExp.$2) / Number(RegExp.$3)
		: parseFloat(s_height);
	return n_width * n_height;
}

// this function returns the list of unique values in product list for specified property
function f_getPropList (a_localProdList, s_prop, b_index) {
	var a_list = [], a_index = [], s_value;
	for (var i = 0; i < a_localProdList.length; i++) {
		s_value = a_prodList[a_localProdList[i]][s_prop];
		if (!a_index[s_value]) {
			a_index[s_value] = true;
			a_list[a_list.length] = s_value
		}
	}
	if (b_index)
		return a_index;
	if (a_sortFunctions[s_prop])
		a_list.sort(a_sortFunctions[s_prop]);
	else
		a_list.sort();

	return a_list;
}

function f_getFilteredProducts (a_filters, a_skipKeys, b_noEmpty) {
	var a_list;
	for (var p = 0; p < window.a_keys.length; p++) {
		var s_prop = window.a_keys[p];
		// don't use color or weight for filtering
		if (a_filters[s_prop] == null) continue;
		if (a_skipKeys && a_skipKeys[s_prop]) continue;
		var s_value = a_filters[s_prop];
		if (a_list) {
			var a_newList = [];
			for (var i = 0; i < a_list.length; i++)
				if (a_prodList[a_list[i]][s_prop] == s_value)
					a_newList[a_newList.length] = a_list[i];
			if (a_newList.length || !b_noEmpty)
				a_list = a_newList;
		}
		else
			a_list = a_propIndex[s_prop][s_value];
		
		if (a_list.length == 1)
			return a_list;
	}
	// no filters applied - return full list
	if (!a_list) {
		a_list = [];
		for (var i = 0; i < a_prodList.length; i++)
			a_list[i] = i;
	}
	return a_list;
}

function f_getInDifferentColor (s_color, s_weight) {
	var i, n_id, a_product, n_first;
	for (i = 0; i < window.a_displayedProdList.length; i++) {
		n_id = a_displayedProdList[i];
		a_product = a_prodList[n_id];
		if (a_product['cl'] == s_color) {
			if (!s_weight || a_product['lb'] == s_weight)
				return n_id;
			if (n_first == null)
				n_first = n_id;
		}
	}
	return n_first;
}

function f_moutColor () {
	window.e_colorTimer = setTimeout('f_updateColor(s_selectedColor)', 300);
}
function f_moverColor (s_color) {
	f_updateColor(s_color)
}
function f_mdownColor (s_color) {
	f_filterSelection('cl', s_color);
}

function f_updateColor (s_color) {
	if (window.e_colorTimer) {
		clearTimeout(window.e_colorTimer);
		window.e_colorTimer = null;
	}
	var a_product = a_prodList[f_getInDifferentColor(s_color, window.s_selectedWeight)];
	var e_elem = document.getElementById('prodName');
	e_elem.innerHTML = a_product['n'].replace(a_product['cl'], '');
	e_elem = document.getElementById('colorName');
	e_elem.innerHTML = a_product['cl'];
	e_elem = document.getElementById('prodAttr');
	e_elem.innerHTML = a_keys[1] ? a_product[a_keys[1] != 'cl' ? a_keys[1] : 'fn'] : '&nbsp;';
}

function f_updateProduct (n_id) {
	var a_product = a_prodList[n_id];
	
	// update product info
	e_elem = document.getElementById('att_pcode');
	e_elem.innerHTML = a_product['c'];
	e_elem = document.getElementById('att_weight');
	e_elem.innerHTML = a_product['w'];
	e_elem = document.getElementById('att_printing');
	e_elem.innerHTML = a_product['p'];
	e_elem = document.getElementById('prodName');
	e_elem.innerHTML = a_product['n'].replace(a_product['cl'], '');
	e_elem = document.getElementById('price');
	e_elem.innerHTML =  a_product ? a_product['r'] + '<span>per ' + a_product['u'] + '</span>' : '-';
	e_elem = document.getElementById('colorName');
	e_elem.innerHTML = a_product['cl'];
	e_elem = document.getElementById('prodAttr');
	e_elem.innerHTML = a_keys[1] ? a_product[a_keys[1] != 'cl' ? a_keys[1] : 'fn'] : '&nbsp;';

	// update weight and color boxes
	e_elem = document.getElementById('select-lb');
	if (e_elem) {
		for (var i = 0; i < e_elem.options.length; i++) {
			if (e_elem.options[i].value == a_product['lb']) {
				e_elem.selectedIndex = i;
				break;
			}
		}
	}
	e_elem = document.getElementById('select-cl');
	if (e_elem) {
		for (i = 0; i < e_elem.options.length; i++) {
			if (e_elem.options[i].value == a_product['cl']) {
				e_elem.selectedIndex = i;
				break;
			}
		}
	}

	// update volume price
	e_elem = document.getElementById('volpriceSide');
	if (a_product['vp']) {
		var s_html = '<table id="volPriceTable"><tr><th>Packs</th><th>Price / Pack</th></tr>';
		for (var i = 0; i < a_product['vp'].length; i+= 2)
			s_html += '<tr><td>' + a_product['vp'][i] + '</td><td>' + a_product['vp'][i + 1] + '</td></tr>';
		s_html += '</table>';
		e_elem.innerHTML = s_html;
	}
	else
		e_elem.innerHTML = '&nbsp;';

	// update description
	s_squareNote = a_product['s'].match(/^([\d\/\s]+)\s+x\s+([\d\/\s]+)$/i) && RegExp.$1 == RegExp.$2
		? '<div id="squareNote">Square invitations and envelopes may require extra postage. Please consult your local post office.</div>'
		: '';
	
	e_elem = document.getElementById('tab-description');
	e_elem.innerHTML = (a_product ? a_product['d'] : '') + s_squareNote;
	

	// swap large image
	e_elem = document.getElementById('prodImage');
	e_elem.src = 'http://www.lcipaper.com/catalog/graphics/prods/' + a_product['c'] + 'med.jpg'

	// change product name in shipping cart
	var e_input = document.forms['addToCart'].elements['Product_Code'];
	if (e_input)
		e_input.value = a_product['c'];
		
	window.n_selectedProduct = n_id;

	// switch to description tab
	f_tabShow('#description');

	// load reviews (AJAX request)
	var a_reviewsProdList = f_getFilteredProducts({
		'tw' : a_product['tw'],
		'b'  : a_product['b'],
		'fn' : a_product['fn']
	});
	var a_reviewProdCodes = [];
	for (i = 0; i < a_reviewsProdList.length; i++)
		a_reviewProdCodes[i] = a_prodList[a_reviewsProdList[i]]['c'];
	var s_newReviewProducts = a_reviewProdCodes.join(';');

	if (s_newReviewProducts != window.s_reviewProducts) {

		// hide tab	reviews tab
		document.getElementById('navTabs').getElementsByTagName('LI').item(2).style.display = 'none';
		
		// send request for new reviews
		window.o_http = f_getHTTPObject();
		window.o_http.onreadystatechange = f_updateReviewsHandler;
		window.o_http.open("GET",
			(String(window.location).indexOf('http:') == 0 ? 'http' : 'https')
			+ '://www.lcipaper.com/php/show-reviews.php?p='
			+ escape(s_newReviewProducts), true);
		window.o_http.send(null);
		window.s_reviewProducts = s_newReviewProducts;
	}
}

function f_updateReviewsHandler () {
	if (!window.o_http)
		return;

	if (window.o_http.readyState != 4) return;
	if (window.o_http.status != 200 && o_http.status != 304)
		throw 'AJAX response error';

	var s_html = window.o_http.responseText;
	if (s_html == '') return;

	document.getElementById('tab-reviews').innerHTML = s_html;
	document.getElementById('navTabs').getElementsByTagName('LI').item(2).style.display = '';
}

function f_resetFilters() {
	f_filterSelection ('tw', a_prodFilter['tw']);
}

function f_filterSelection (s_changedProp, s_newValue) {

	var p, s_prop, s_value, e_select, a_options,
		s_firstColor, a_colorsIndex = {}, e_reset;

	f_onAddToBasket (true);

	// filter products
	if (s_changedProp) {
		if (s_changedProp == 'tw') {
			window.a_prodFilter = {'tw': s_newValue};
			
			for (p = 0; p < a_keys.length; p++) {
				e_reset = document.getElementById('filter-reset-' + a_keys[p]);
				if (!e_reset) continue;
				e_reset.style.display = 'none';
			}
		}
		else if (s_changedProp == 'cl')
			window.s_selectedColor = s_newValue;
		else if (s_changedProp == 'lb') {
			window.s_selectedWeight = s_newValue;
		}
		else {
			var a_newFilter = {};
			var b_allClear = true;
			for (p = 0; p < a_keys.length; p++) {
				s_prop = a_keys[p];
				if (s_changedProp == s_prop) {
					if (s_newValue) {
						a_newFilter[s_prop] = s_newValue;
						if (a_labels[s_prop]['a'])
							b_allClear = false;
					}
				}
				else if (window.a_prodFilter[s_prop] && s_prop != 'lb') {
					a_newFilter[s_prop] = window.a_prodFilter[s_prop];
					if (a_labels[s_prop]['a'])
						b_allClear = false;
				}
			}
			for (p = 0; p < a_keys.length; p++) {
				e_reset = document.getElementById('filter-reset-' + a_keys[p]);
				if (!e_reset) continue;
				e_reset.style.display =  b_allClear ? 'none' : 'inline';
			}
			window.a_prodFilter = a_newFilter;
		}
	}
	window.a_displayedProdList = f_getFilteredProducts(window.a_prodFilter, {'lb': 1, 'cl': 1});

	// re-populate drop boxes with available options
	if (s_changedProp != 'cl' && s_changedProp != 'lb') {
		for (p = 0; p < a_keys.length; p++) {
			s_prop = a_keys[p];
			if (s_prop == 'tw') continue;
			if (s_changedProp && s_changedProp == s_prop) continue;
			
			e_select = document.getElementById('select-' + s_prop);
			a_options = f_getPropList(a_displayedProdList, s_prop);
			e_select.options.length = a_labels[s_prop]['a'] ? 1 : 0;
			for (var v = 0; v < a_options.length; v++) {
				s_value = a_options[v];
				e_select.options[e_select.options.length] = new Option (s_value, s_value);
				if (s_prop == 'cl') {
					a_colorsIndex[s_value] = true;
					if (!s_firstColor)
						s_firstColor = s_value;
				}
			}
	
			// disable selects with single option
			if (a_options.length == 1) {
				e_select.selectedIndex = e_select.options.length - 1;
				e_select.disabled = true;
			}
			else
				e_select.disabled = false;
		}
		if (!window.s_selectedColor || !a_colorsIndex[window.s_selectedColor]) 
			window.s_selectedColor = s_firstColor ? s_firstColor : a_prodList[0]['cl'];
	}

	// update swatch
	var a_allColors = a_propList['cl'];
	for (c = 0; c < a_allColors.length; c++) {
		s_color = a_allColors[c];
		s_colorNoSpaces = s_color.replace(/\s+/g, '-');
		e_color = document.getElementById('colorSwatch-' + s_colorNoSpaces);
		
		e_color.className = window.s_selectedColor == s_color ? 'colorSwatchSelected' : 'colorSwatch';
		if (s_changedProp != 'cl' && s_changedProp != 'lb')
			e_color.style.display = a_colorsIndex[s_color] ? 'inline' : 'none';
	}

	// see if there are multiple weights for this product
	var n_selectedProduct = f_getInDifferentColor(window.s_selectedColor, window.s_selectedWeight);
	var a_selectedProduct = a_prodList[n_selectedProduct];

	a_newFilter = {};
	for (p = 0; p < a_keys.length; p++) {
		s_prop = a_keys[p];
		a_newFilter[s_prop] = a_selectedProduct[s_prop]
	}

	a_options = f_getPropList(f_getFilteredProducts(a_newFilter, {'lb':true}), s_prop);
	var e_filter = document.getElementById('filter-lb');
	if (e_filter) {
		if (a_options.length > 1) {
			e_filter.style.display = 'block';
			var e_select = document.getElementById('select-lb');
			e_select.options.length = 0;
			for (var v = 0; v < a_options.length; v++) {
				s_value = a_options[v];
				e_select.options[v] = new Option (s_value, s_value);
				if (s_value == a_selectedProduct['lb'])
					e_select.selectedIndex = v;
			}
		}
		else
			e_filter.style.display = 'none';
	}

	// update product info
	f_updateProduct(n_selectedProduct);
}

function f_getSelects() {
	var p, v, s_prop, s_value, a_localLabels;
	
	for (p = 0; p < a_keys.length; p++) {
		s_prop = a_keys[p];
		a_localLabels = a_labels[s_prop];
		
		var a_values = a_propList[s_prop];
		if (s_prop == 'tw') {
			document.write('<div id="filter-' + s_prop + '"><label for="select-' + s_prop + '">' + a_localLabels['l'] + '</label>');
			for (v = 0; v < a_values.length; v++)
				document.write('<input type="radio" name="select-tw" value="'
					+ a_values[v] + '" onclick="f_filterSelection(\'tw\', this.value)"'
					+ (window.a_prodFilter['tw'] == a_values[v] ? ' checked="yes"' : '')
					+ ' />' + a_values[v] + '<br />'
				);
		}
		else {
			
			document.write('<div id="filter-' + s_prop + '"><label for="select-' + s_prop + '"><span class="float-left">' + a_localLabels['l'] + '</span>');
			if (s_prop != 'cl' && s_prop != 'lb')
				document.write('<span class="filter-reset" id="filter-reset-' +  s_prop + '">[<a href="javascript:f_resetFilters();">show all</a>]</span>');
			document.write('</label><select onchange="f_filterSelection(\'' + s_prop
				+ '\', this.options[this.selectedIndex].value)" onkeyup="f_filterSelection(\'' + s_prop
				+ '\', this.options[this.selectedIndex].value)" id="select-' + s_prop + '" name="select-' + s_prop + '">');
			if (a_localLabels['a'])
				document.write('<option value="">-- ' + a_localLabels['a'] + ' --</option>');
			document.write('</select>');
		}
		document.write('</div>');
	}
}

function f_getSamplesSelects() {
		var a_options = a_propList['tw'];
		if (a_options.length > 1) {
			document.write('<label for="samples-select-tw">', a_labels['tw']['l'],
				':</label><select name="samples-select-tw" id="samples-select-tw" onkeyup="f_samplesTable(true)" onchange="f_samplesTable(true)">');
			for (var i = 0; i < a_options.length; i++)
				document.write('<option value="', a_options[i],'">', a_options[i] , '</option>');
			document.write('</select> ');
		}

		// secondary filter
		var s_prop;
		if (a_propIndex['b'])
			s_prop = 'b';
		else if (a_propIndex['s'])
			s_prop = 's';
		else
			return;
			
		var a_options = a_propList[s_prop];
		if (a_options.length < 2)
			return;
		
		document.write('<label for="samples-select-', s_prop, '">', a_labels[s_prop]['l'],
			':</label><select name="samples-select-', s_prop, '" id="samples-select-', s_prop,
				'" onkeyup="f_samplesTable(true)" onchange="f_samplesTable(true)">',
				'<option value="">-- ', a_labels[s_prop]['a'], ' --</option>');
		for (var i = 0; i < a_options.length; i++)
			document.write('<option value="', a_options[i],'">', a_options[i] , '</option>');
		document.write('</select>');
}

function f_onAddToBasket (b_reset) {
	var e_message = document.getElementById('addToBasketMessage'),
		a_filter = window.a_prodFilter, e_select, s_value,
		s_prop, e_filter, a_options, p, a_messages = [];
		
	if (b_reset) {
		e_message.style.display = 'none';
		for (p = 0; p < a_keys.length; p++) {
			e_filter = document.getElementById('filter-' + a_keys[p]);
			e_filter.className = '';
		}
		return;
	}

	// determine if all properties are explicitly selected
	for (p = 0; p < a_keys.length; p++) {
		s_prop = a_keys[p];
		if (a_filter[s_prop]) continue;
		e_select = document.getElementById('select-' + s_prop);
		s_value = e_select.options[e_select.selectedIndex].value;
		if (s_value == '') continue;
		a_filter[s_prop] = s_value;
	}
	var a_selection = f_getFilteredProducts(a_filter);
	
	for (p = 0; p < a_keys.length; p++) {
		s_prop = a_keys[p];
		if (!a_labels[s_prop]['m'])
			continue;

		a_options = f_getPropList(a_selection, s_prop);
		e_filter = document.getElementById('filter-' + s_prop);
		if (a_options.length > 1) {
			a_messages[a_messages.length] = a_labels[s_prop]['m'];
			e_filter.className = 'highlighted';
		}
		else
			e_filter.className = '';
	}
	if (a_messages.length) {
		e_message.innerHTML = 'Selected Product is available in multiple ' + a_messages.join(' &amp; ') + '. Please make selections to complete your order.';
		e_message.style.display = 'block';
		return false;
	}
	else {
		e_message.style.display = 'none';
		e_message.innerHTML = '';
		return true;
	}
}

function f_samplesTable (b_reload) {

	f_hideEnvelopeSizes();

	// prepare structure with samples
	var p, s_prop, s_value, e_select, a_filter = {};
	if (b_reload) {
		// filter products by selects
		for (p = 0; p < a_keys.length; p++) {
			s_prop = a_keys[p];
			e_select = document.getElementById('samples-select-' + s_prop);
			if (!e_select) continue;
			s_value = e_select.options[e_select.selectedIndex].value;
			if (!s_value) continue;
			a_filter[s_prop] = s_value;
		}
	}
	else {
		// reset selects
		for (p = 0; p < a_keys.length; p++) {
			s_prop = a_keys[p];
			e_select = document.getElementById('samples-select-' + s_prop);
			if (!e_select) continue;
			if (s_prop == 'tw') { // window.a_prodFilter[s_prop]
				for (var o = 0; o < e_select.options.length; o++) {
					s_value = e_select.options[o].value;
					if (window.a_prodFilter[s_prop] == s_value) {
						e_select.selectedIndex = o;
						break;
					}
				}
				a_filter[s_prop] = s_value;
			}
			else {
				e_select.selectedIndex = 0;
				continue;
			}
		}
	}
	
	
	var a_filteredProducts = f_getFilteredProducts(a_filter);
	var i, a_product, s_color, s_horProp,
		a_horPropertyList = [], a_horPropertyIndex = {},
		a_verPropertyList = [], a_prodTree = {};

	for (i = 0; i < a_filteredProducts.length; i++) {
		a_product = a_prodList[a_filteredProducts[i]];
		if (!a_product['sp']) continue;

		s_color = a_product['cl'];
		s_horProp = a_product['s']; // horiz param
		
		if (!a_prodTree[s_color]) {
			a_prodTree[s_color] = {};
			a_verPropertyList[a_verPropertyList.length] = s_color;
		}
		if (!a_horPropertyIndex[s_horProp]) {
			a_horPropertyIndex[s_horProp] = 1;
			a_horPropertyList[a_horPropertyList.length] = s_horProp;
		}
		if (!a_prodTree[s_color][s_horProp])
			a_prodTree[s_color][s_horProp] = [];
		a_prodTree[s_color][s_horProp][a_prodTree[s_color][s_horProp].length] = a_product;
	}

	var x, y, z, a_products, n_itemCount = 1, s_rowHTML, n_rowCount,
		s_html = '<table id="samplesTable"><tr><th>&nbsp;</th>';
	for (x = 0; x < a_horPropertyList.length; x++)
		s_html += '<th>' + a_horPropertyList[x] + '</th>';
	s_html += '</tr>';
	for (y = 0; y < a_verPropertyList.length; y++) {
		s_color = a_verPropertyList[y];
		s_rowHTML = '<tr><th class="colors"><img src="/catalog/graphics/prods/swatches/swatch-' + s_color.replace(/\s+/g, '-') +
		'.gif" alt="' + s_color + '"  class="colorSwatch"  />' + s_color + '</th>';
		n_rowCount = 0;
		for (x = 0; x < a_horPropertyList.length; x++) {
			a_products = a_prodTree[s_color][a_horPropertyList[x]];
			s_rowHTML += '<td>';

			if (a_products) {
				for (z = 0; z < a_products.length; z++) {
					s_rowHTML += '<input type="hidden" name="product_code' +
					n_itemCount  + '" value="' + a_products[z]['c'] + '_s" /><input type="Checkbox"  name="quantity' +
					n_itemCount + '" value="1" /> ' + (a_products.length > 1 ? '<br />' + a_products[z]['lb'] + ' ' : '') + '('+
						a_products[z]['sp'] + ')<br />';
					n_itemCount++;
					n_rowCount++;
				}
			}
			else
				s_rowHTML += '&nbsp;';
			s_rowHTML += '</td>';
		}
		s_rowHTML += '</tr>';
		if (n_rowCount)
			s_html += s_rowHTML;
	}
	if (!n_rowCount)
		s_html += '<div id="not-found">There are no samples<br />matching selected criteria</div>';
	s_html += '</table>';

	e_elem = document.getElementById('samplesTableContainer');
	e_elem.innerHTML = s_html;

	e_elem = document.getElementById('sampleSelector');
	var e_table = document.getElementById('samplesTable');
	var e_iframe = document.getElementById('samplesSelectFix');
	if (!e_elem || !e_table) return;
	e_table.style.display = b_ie6 || b_ie7 || b_ie8 ? 'block' : 'table';

	var n_width  = e_elem.offsetWidth;
	var n_height = e_elem.offsetHeight;
	var n_left, n_top;
	if (!b_reload) {
		n_left = (f_clientWidth() - n_width) / 2;
		if (n_left < 10) n_left = 10;
		n_top = (f_clientHeight() - n_height) / 2;
		if (n_top < 10) n_top = 10;
		
		e_elem.style.left = n_left + 'px';
		e_elem.style.top  = n_top  + 'px';
		e_elem.style.visibility = 'visible';
	}
	else {
		n_left = e_elem.offsetLeft;
		n_top = e_elem.offsetTop;
	}
	if (e_iframe) {
		e_iframe.style.display = "block";
		e_iframe.width = n_width - 1;
		e_iframe.height = n_height - 1;
		e_iframe.style.top = n_top  + 'px';
		e_iframe.style.left = n_left + 'px';
	}
	
	var e_shade = document.getElementById('sampleSelectorShade');
	if (!e_shade) return;
	f_customShade(e_shade, n_width - 1, n_height - 2, n_left + 1, n_top + 1);
	e_shade.style.visibility = 'visible';
}

function f_hideSamplesTable() {
	var e_elem = document.getElementById('sampleSelector');
	if (e_elem)
		e_elem.style.visibility = 'hidden';
	var e_iframe = document.getElementById('samplesSelectFix');
	if (e_iframe)
		e_iframe.style.display = "none";

	var e_shade = document.getElementById('sampleSelectorShade');
	if (e_shade)
		e_shade.style.visibility = 'hidden';
		
	window.scrollTo(0, 0);
}
function f_envelopeSizes() {
	
	f_hideSamplesTable();
//	f_hideColorsTable();
	
	var e_elem = document.getElementById('envelopeSizes');
	if (!e_elem) return;

	var e_elemFrame = document.getElementById('envelopeSizesFrame');
	e_elemFrame.src = 'http://www.lcipaper.com/envelope-sizes.shtml';

	var n_width  = e_elem.offsetWidth;
	var n_height = e_elem.offsetHeight;
	var n_left   = (f_clientWidth() - n_width) / 2;
	if (n_left < 10) n_left = 10;
	var n_top = (f_clientHeight() - n_height) / 2;
	if (n_top < 10) n_top = 10;
	
	e_elem.style.left = n_left + 'px';
	e_elem.style.top  = n_top  + 'px';
	e_elem.style.visibility = 'visible';

	var e_iframe = document.getElementById('samplesSelectFix');
	if (e_iframe) {
		e_iframe.style.display = "block";
		e_iframe.width = n_width;
		e_iframe.height = n_height;
		e_iframe.style.top = n_top  + 'px';
		e_iframe.style.left = n_left + 'px';
	}
	
	var e_shade = document.getElementById('sampleSelectorShade');
	if (!e_shade) return;
	f_customShade(e_shade, n_width - 1, n_height - 1, n_left + 1, n_top + 1);
	e_shade.style.visibility = 'visible';
}

function f_hideEnvelopeSizes() {
	var e_elem = document.getElementById('envelopeSizes');
	if (e_elem)
		e_elem.style.visibility = 'hidden';
	var e_iframe = document.getElementById('samplesSelectFix');
	if (e_iframe)
		e_iframe.style.display = "none";
	var e_shade = document.getElementById('sampleSelectorShade');
	if (e_shade)
		e_shade.style.visibility = 'hidden';
	window.scrollTo(0, 0);
}

function f_selectAllSamples(b_select) {
	var e_checkbox, e_form = document.getElementById('sampleSelector');
	for (n_number = 1; e_checkbox = e_form.elements['quantity' + n_number]; n_number++)
		e_checkbox.checked = b_select;
}

function f_clientWidth() {
	if (typeof(window.innerWidth) == 'number')
		return window.innerWidth;
	if (document.documentElement && document.documentElement.clientWidth)
		return document.documentElement.clientWidth;
	if (document.body && document.body.clientWidth)
		return document.body.clientWidth;
	return null;
}

function f_clientHeight() {
	if (typeof(window.innerHeight) == 'number')
		return window.innerHeight;
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	if (document.body && document.body.clientHeight)
		return document.body.clientHeight;
	return null;
}

function f_setLightbox (e_elem, b_envelope) {
	if (b_envelope) {
		if (a_selectedProduct == null) return;
		e_elem.href  = '/catalog/graphics/prods/' + a_selectedEnvelope['code']  + 'large.jpg'
		e_elem.title = a_selectedEnvelope['name'];
	}
	else {
		if (n_selectedProduct == null) return;
		var a_prod = a_prodList[n_selectedProduct];
		e_elem.href  = '/catalog/graphics/prods/' + a_prod['c']  + 'large.jpg'
		e_elem.title = a_prod['n'];
	}
}

function f_getHTTPObject() {
	var o_http;
	if (!o_http && typeof XMLHttpRequest != 'undefined') {
		try { o_http = new XMLHttpRequest(); }
		catch (e) { o_http = false; }
	}
	if (!o_http && typeof ActiveXObject != "undefined") {
		try { o_http = new ActiveXObject("MSXML2.XMLHTTP"); }
		catch (e) { o_http = false; }
		if (!o_http) {
			try { o_http = new ActiveXObject("MSXML2.XMLHTTP"); }
			catch (e) { o_http = false; }
		}
	}
	return o_http;
}

// --- initial pricedures ---
// init unique property lists
var a_propIndex = {}, a_propList = {}, s_prop;
for (p = 0; p < a_keys.length; p++) {
	s_prop = a_keys[p];
	a_propIndex[s_prop] = {};
	a_propList[s_prop] = [];
}

// group products by properties
var s_value;
for (i = 0; i < a_prodList.length; i++) {
	for (p = 0; p < a_keys.length; p++) {
		s_prop = a_keys[p];
		s_value = a_prodList[i][s_prop];

		if (a_propIndex[s_prop][s_value] == null) {
			a_propIndex[s_prop][s_value] = [];
			a_propList[s_prop][a_propList[s_prop].length] = s_value;
		}
		a_propIndex[s_prop][s_value][a_propIndex[s_prop][s_value].length] = i;
	}
}

// optimize keys by removing properties shared by all products
var a_newKeys = [];
for (p = 0; p < a_keys.length; p++) {
	s_prop = a_keys[p];
	if (a_propList[s_prop].length > 1)
	a_newKeys[a_newKeys.length] = s_prop;
}
a_keys = a_newKeys;
a_newKeys = null;

// sort property lists
for (p = 0; p < a_keys.length; p++) {
	s_prop = a_keys[p];
	if (a_sortFunctions[s_prop])
		a_propList[s_prop].sort(a_sortFunctions[s_prop]);
	else
		a_propList[s_prop].sort();
}

// initial filter
if (a_propIndex['tw']) {
	var n_maxTypeCount = 0, n_selected,
		a_values = a_propList['tw'];

	for (var v = 0; v < a_values.length; v++) {
		n_typeCount = a_propIndex['tw'][a_values[v]].length;
		if (n_typeCount > n_maxTypeCount) {
			n_maxTypeCount = n_typeCount;
			n_selected = v;
		}
	}
	window.a_prodFilter = {'tw': a_values[n_selected]};
}
else 
	window.a_prodFilter = {};

function f_productInit() {
	if (a_keys.length) {
		f_filterSelection();
		var e_inputs = document.getElementsByTagName('INPUT');
		if (e_inputs) {
			for (var i = 0; i < e_inputs.length; i++) {
				if (e_inputs[i].name == 'select-tw' && e_inputs[i].value == window.a_prodFilter['tw']) {
					e_inputs[i].checked = true;
					break;
				}
			}
		}
	}
	else {
		window.a_displayedProdList = [0];
		window.s_selectedColor = a_prodList[0]['cl'];
		f_updateProduct(0);
	}
}
