/* Paste this code into the caption field on the comparison page... modify to taste.

<div style="display: none;">
	<img id="removeX" src="/lib/STORENAME/remove-x.png" width="16" height="16" alt="Remove from Comparison" />
	<img id="loadingImage" src="/lib/STORENAME/loading.png" width="48" height="16" alt="Loading..." />
</div>
<div id="compareContainer"></div>
<script type="text/javascript" language="Javascript">displayInfos();</script>


*** Add checkboxes to each item in the contents so the customer can select them ***
<div class="compareLink">
	<input type="checkbox" value="ITEM_ID" onchange="compareItemCookie(this.value, this.checked);" onclick="this.blur();" onmouseup="this.focus();" />
	<a href="compare-items.html">Compare All Viewed</a>
</div>

*/

var storename = 'furniture-sale';
var compareColumns = 2;
var compareLayout = 'ell'; // ell, vertical
// var compareElements = 'name,price,availability'.split(/,/);
var compareElements = 'name,price,viewmore'.split(/,/);

var compareLoadImg = document.getElementById('loadingImage');
if (compareLoadImg) {
	compareLoadImg = compareLoadImg.cloneNode(false);
} else {
	compareLoadImg = document.createElement('img');
	with (compareLoadImg) {
		src = '/lib/' + storename + '/loading.gif';
		width = '48';
		height = '47';
	}
}

var compareRemoveImg = document.getElementById('removeX');
if (compareRemoveImg) {
	compareRemoveImg = compareRemoveImg.cloneNode(false);
} else {
	compareRemoveImg = document.createElement('img');
	with (compareRemoveImg) {
		src = '/lib/' + storename + '/remove-x.png';
		alt = 'Remove from comparison';
		width = '16';
		height = '16';
	}
}


/* cookies.js */
var expDays = 30;
var exp = new Date(); 
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

function getCookieVal(offset) {  
var endstr = document.cookie.indexOf (";", offset);  
if (endstr == -1)    
endstr = document.cookie.length;  
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie(name) {  
var arg = name + "=";  
var alen = arg.length;  
var clen = document.cookie.length;  
var i = 0;  
while (i < clen) {    
var j = i + alen;    
if (document.cookie.substring(i, j) == arg)      
return getCookieVal (j);    
i = document.cookie.indexOf(" ", i) + 1;    
if (i == 0) break;   
}  
return null;
}
function SetCookie(name, value) {  
var argv = SetCookie.arguments;  
var argc = SetCookie.arguments.length;  
var expires = (argc > 2) ? argv[2] : null;  
var path = (argc > 3) ? argv[3] : null;  
var domain = (argc > 4) ? argv[4] : null;  
var secure = (argc > 5) ? argv[5] : false;  
document.cookie = name + "=" + escape (value) + 
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + 
((path == null) ? "" : ("; path=" + path)) +  
((domain == null) ? "" : ("; domain=" + domain)) +    
((secure == true) ? "; secure" : "");
}
function DeleteCookie(name) {  
var exp = new Date();  
exp.setTime (exp.getTime() - 1);  
var cval = GetCookie (name);  
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

/* scAjax.js */
function scAjax(startURL) {
	this.url = startURL;
	this.query = '';
	this.persistentQuery = '';
	this.content = '';
	this.POST = 0;
	this.GET = 1;
	this.requestType = this.GET;
	this.callbackFunction = function () { return true; };
	this.error = '';
	this.fallbackFunction = function () { alert(this.error); };
	this.mime = 'text/html';
	
	this.newXMLRequestThread = function () {
		var xmlhttp = false;
		var i = this;
		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp = false;
			}
		}
		@end @*/
		if (!xmlhttp && (typeof XMLHttpRequest != 'undefined')) {
			xmlhttp = new XMLHttpRequest();
			if (xmlhttp.overrideMimeType) {
				xmlhttp.overrideMimeType(i.mime);
			}
		}
		return xmlhttp;
	};

	this.serverRequest = function (urlToGet) {
		var i = this;
		var j = i.newXMLRequestThread();
		var h = 'application/x-www-form-urlencoded';
		if (j) {
			if (i.requestType == i.POST) {
				j.open("post", urlToGet, true);
				j.setRequestHeader('Content-Type', h);
				j.setRequestHeader('Content-length', i.query.length);
				j.setRequestHeader('Connnection', 'close');
			} else {
				if (i.query.length) {
					urlToGet += '?' + i.query;
				}
				i.query = null;
				j.open("get", urlToGet, true);
			}
			j.onreadystatechange = function() {
				if (j.readyState == 4) {
					if (j.status == 200) {
						i.content = j.responseText;
						i.callbackFunction();
					} else {
						i.error = 'Server returned an error - the page may have been relocated or removed.';
						i.fallbackFunction();
					}
				}
			};
			j.send(i.query);
		} else {
			i.error = 'Unable to create HTTP request thread.';
			i.fallbackFunction();
		}
	};

	this.addQuery = function (name, value, persistent) {
		var a = persistent ? this.persistentQuery : this.query;
		if (a.length) { a += '&'; }
		a += name + (value ? '=' + encodeURIComponent(value) : '');
		if (persistent) { this.persistentQuery = a; } else { this.query = a; }
	};

	this.init = function () {
		if (this.persistentQuery.length) {
			if (this.query.length) { this.query += '&'; }
			this.query += this.persistentQuery;
		}
		this.serverRequest(this.url);
		this.query = '';
	};
}


/* compare.js */

function resizeTable() {
	try {
		var obj = document.getElementById('compareContainer');
		var ts = obj && obj.getElementsByTagName('table') ?
			obj.getElementsByTagName('table')[0].getElementsByTagName('table') : null;
		if (ts) {
			var max = 0;
			for (var i = 0, j = ts.length; i < j; i++) ts[i].style.height = 'auto';
			for (var i = 0, j = ts.length; i < j; i++) max = ts[i].offsetHeight > max ? ts[i].offsetHeight : max;
			if (max > 0) {
				max = max + 'px';
				for (var i = 0, j = ts.length; i < j; i++) ts[i].style.height = max;
			}
		}
	} catch (err) { }
}

function compareRemoveDisplay(id) {
	var container = document.getElementById('compareContainer');
	var obj = document.getElementById(('table' + id).toLowerCase());
	tId = ('table' + id).toLowerCase();
	var t = container ? container.getElementsByTagName('table') : null;
	if (container && obj && t && t[0]) {
		t = t[0];
		var tables = t.getElementsByTagName('table');
		var found = false;
		for (var i = 0, j = tables.length; i < j; i++) {
			if (tables[i].id == tId) found = true;
			if (found && i + 1 < tables.length && tables[i + 1].id !== tId)
				tables[i].parentNode.replaceChild(tables[i + 1].cloneNode(true), tables[i]);
		}
		with (tables[tables.length - 1]) parentNode.parentNode.removeChild(parentNode);
		var trs = t.getElementsByTagName('tr');
		for (var i = 0, j = trs.length; i < j; i++)
			if (trs[i].childNodes.length === 0)
				trs[i].parentNode.removeChild(trs[i]);
	}
	compareItemCookie(id, false);
}

function displayInfo() {
	var tag = this.content.match(/(?:<!--sc-caption-start-->((?:.|\n|\r)*?)<!--sc-caption-end-->(?:.|\n|\r)*?)?<!--sc-tag-start ((?:.|\n|\r)*?) sc-tag-end-->/);
	if (tag) {
		var info = eval(tag[2]);
		var t = document.getElementById(('table' + info.id).toLowerCase());
		if (t) {
			var tds = t.getElementsByTagName('td');
			var outputTd;
			for (var i = 0, j = tds.length; i < j; i++) tds[i].className += ' vTop';

			outputTd = tds[(compareLayout === 'ell') ? 1 : 0];

			var d = document.createElement('div');
			d.className = 'removeX';
			var a = document.createElement('a');
			a.href = "javascript:compareRemoveDisplay('" + info.id + "');";
			a.appendChild(compareRemoveImg.cloneNode(false));
			d.appendChild(a);
			if (compareLayout === 'ell') {
				outputTd.appendChild(d);
			} else {
				var firstImg = outputTd.getElementsByTagName('img');
				if (firstImg && firstImg[0]) outputTd.insertBefore(d, firstImg[0]);
				  else outputTd.appendChild(d);
			}

			for (var i = 0, j = compareElements.length; i < j; i++) {
				switch (compareElements[i]) {
					case 'name':
						var d = document.createElement('div');
						d.className = 'name';
						var a = document.createElement('a');
						a.href = info.id + '.html';
						a.appendChild(document.createTextNode(info.name));
						d.appendChild(a);
						outputTd.appendChild(d);
						break;

					case 'price':
						if (info.price) {
							var d = document.createElement('div');
							d.className = 'price' + (info.saleprice ? '' : ' price-bold');
							d.innerHTML = info.price;
							outputTd.appendChild(d);
						}
						if (info.saleprice) {
							var d = document.createElement('div');
							d.className = 'sale-price' + (info.price ? '' : ' sale-price-bold');
							d.innerHTML = info.saleprice;
							outputTd.appendChild(d);
						}
						if (info.price || info.saleprice) {
							var d = document.createElement('div');
							d.className = 'order';
							d.innerHTML = info.order;
							outputTd.appendChild(d);
						}
						break;

					default:
						var el = compareElements[i];
						if (info[el]) {
							var d = document.createElement('div');
							d.className = el;
							d.innerHTML = info[el];
							outputTd.appendChild(d);
						}
						break;
				}
			}

			if (info.image) {
				var d = document.createElement('div');
				d.className = 'image';
				var img = document.createElement('img');
				img.src = info.image;
				img.onload = resizeTable;
				img.alt = info.name;
				var a = document.createElement('a');
				a.href = info.id + '.html';
				a.appendChild(img);
				d.appendChild(a);
				var imgs = tds[0].getElementsByTagName('img');
				var oldImg;
				for (var i = 0, j = imgs.length; i < j; i++)
					if (imgs[i].className.match(/\bloadingImage\b/))
						oldImg = imgs[i];
				if (oldImg) oldImg.parentNode.replaceChild(d, oldImg);
			} else if (compareLayout === 'ell') tds[0].parentNode.removeChild(tds[0]);

			resizeTable();
		}
	}
}

function displayInfos() {
	var con = document.getElementById('compareContainer');
	if (con) {
		var ids = GetCookie('compares');
		if (ids) {
			var table = document.createElement('table');
			table.border = table.cellSpacing = table.cellPadding = '0';
			table.width = '100%';

			var t = document.createElement('tbody');

			var tr, td;
			ids = ids.replace(/^.(.*).$/, '$1');
			ids = ids.split(/\]\[/);
			for (var i = 0, j = ids.length; i < j; i++) {
				if (i % compareColumns === 0) {
					if (tr) t.appendChild(tr);
					tr = document.createElement('tr');
				}
				td = document.createElement('td');
				td.width = (100 / compareColumns) + '%';

				var innerTable = document.createElement('table');
				innerTable.id = ('table' + ids[i]).toLowerCase();
				innerTable.className = compareLayout;
				innerTable.setAttribute('width', '100%');
				/* Stop! Hammertime! */
				var innerT = document.createElement('tbody');
				with (innerT) {
					border = cellSpacing = cellPadding = '0';
					width = '100%';
				}
				var innerTr = document.createElement('tr');
				var innerTd = document.createElement('td');
				var loadImg = compareLoadImg.cloneNode(false);
				loadImg.className += ' loadingImage';
				innerTd.appendChild(loadImg);
				if (compareLayout === 'ell') {
					innerTr.appendChild(innerTd);
					var innerTd = document.createElement('td');
					innerTd.width = '100%';
				}
				innerTr.appendChild(innerTd);
				innerT.appendChild(innerTr);
				innerTable.appendChild(innerT);
				td.appendChild(innerTable);
				tr.appendChild(td);

				var req = new scAjax(ids[i].toLowerCase() + '.html?ts=' + (new Date()).getTime());
				req.callbackFunction = displayInfo;
				req.init();
			}
			if (tr) t.appendChild(tr);
			table.appendChild(t)
			con.appendChild(table);
		}
	}
}


function checkCompareBoxes() {
	var cookie = GetCookie('compares') || '';
	if (cookie) {
		var inps = document.getElementsByTagName('input');
		for (var i = 0, j = inps.length; i < j; i++)
			if (inps[i].getAttribute('type').toLowerCase() === 'checkbox' &&
			  cookie.search(RegExp('\\[' + inps[i].getAttribute('value') + '\\]')) >= 0 &&
			  inps[i].parentNode.className.match(/\bcompareLink\b/))
				inps[i].checked = true;
	}
}

function compareItemCookie(c, add) {
	var temp = GetCookie('compares');
	var compareFindId = new RegExp('\\[' + c.toLowerCase() + '\\]', 'g');
	if (add) {
		if (temp === null || temp === '' || (temp || '').search(compareFindId) < 0) {
			SetCookie('compares', (temp || '') + '[' + c.toLowerCase() + ']');
		}
	} else SetCookie('compares', (temp || '').replace(compareFindId, ''));
}

function clearCompares() {
	var obj = document.getElementById('compareContainer');
	if (obj) with(obj) while (firstChild) removeChild(firstChild);
	DeleteCookie('compares');
}


