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

// text for select boxes
var a_labels = {
	'tw' : {'l':'Select Type'},
	'f' : {'l':'Select Size', 'a':'Show all Sizes', 'm':'size'},
	'b' : {'l':'Select Brand', 'a':'Show all Brands', 'm':'brand'},
	'cl' : {'l':'Select Color'}
};
 // list of the properties that are URL encoded for transport
var a_decodeKeys = ['n','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) {
  	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];
		if (a_prodList[i][s_prop])
			a_prodList[i][s_prop] = f_urlDecode(a_prodList[i][s_prop]);
	}
}

// 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;
	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 (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['s'] : '&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'];
	if (document.forms['addToCart']) {
		e_elem = document.forms['addToCart'].elements['Product_Code'];
		if (e_elem) e_elem.value = a_product['c'];
	}
	e_elem = document.getElementById('att_size');
	e_elem.innerHTML = a_product['s'];
	e_elem = document.getElementById('att_scoring');
	if (e_elem) e_elem.value = a_product['s'];
	e_elem = document.getElementById('att_color');
	e_elem.innerHTML = a_product['cl'];
	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['s'] : '&nbsp;';
	e_elem = document.getElementById('att_printtpl');
	if (e_elem) e_elem.innerHTML = a_product['pt'] ? '<a href="' + a_product['pt'] + '">download</a>' : 'n/a - submit request';

	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
	if (!window.s_defaultImg) {
		e_elem = document.getElementById('prodImage');
		e_elem.src =  'http://www.lcipaper.com/catalog/graphics/prods/' + a_product['c'] + 'med.jpg';
	}
	window.n_selectedProduct = n_id;
}

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;

	// 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';
			}
		}
		if (s_changedProp == 'cl') {
			window.s_selectedColor = s_newValue;
		}
		else {
			var a_newFilter = {'tw' : window.a_prodFilter['tw']};
			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;
					}
				}
			}
			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, {'cl': 1});

	// re-populate drop boxes with available options
	if (s_changedProp != 'cl') {
		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);
			if (!e_select) continue;
			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')
			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, {}), s_prop);

	// 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 (a_values.length < 1) continue;
		
		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>');
			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_onPersonalize (e_button) {
	var e_type = document.getElementById('select-f');
	if (!e_type || e_type.selectedIndex)
		window.location = '/' + a_prodList[window.n_selectedProduct]['c'] + '.html?cat=' + s_categoryCode + (window.s_event ? '&event=' + escape(s_event) : '');
	else
		alert('Please select size');
}

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 () {
	var e_type = document.getElementById('select-f');
	if (!e_type || e_type.selectedIndex)
		return true;
	alert('Please select size');
	return false;
}
function f_samplesTable (b_reload) {

	// 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_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];
	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();
	}
	else {
		window.a_displayedProdList = [0];
		window.s_selectedColor = a_prodList[0]['cl'];
		f_updateProduct(0);
	}
}

