(function($) {
$.fn.recentlyViewedProducts = function(options) {

	var defaults = {
		cookieName: 'recprd2',
		listLength: 6,
		titleLength: 20,
		fieldDelim: '|',
		recordDelim: '~',
		append: false
	};
	
 	var list = new Array();
	var options = $.extend(defaults, options);
	var result = this;
	
	try {
		loadList();
		result = this.each(function(){
			renderList($(this));
		});
		addProduct(getProductDetails(), options.append); //true = APPEND, false = INSERT
		saveList();
	} catch (e) {
		// if there is an error, empty the list and delete the cookie
		alert(e);
		list = new Array();
		saveList();
	}
	return result;
	
	function loadList() {
		//debugger;
		list = new Array();
		var results = document.cookie.match ( '(^|;) ?' + options.cookieName + '=([^;]*)(;|$)' );
		if (!results) return;

		var val = results[2];

		var prods = val.split(options.recordDelim);
		var c = 0;
		for (var i = 0; i < prods.length; i++) {
			var attrs = prods[i].split(options.fieldDelim);
			var p = {
				id:unescape(attrs[0]),
				sku:unescape(attrs[1]), 
				title:unescape(attrs[2]), 
				price:unescape(attrs[3]),
				img:unescape(attrs[4])
			};
			if (attrs.length > 5) {
				p['catId'] = attrs[5];
			}
			addProduct(p, options.append);
			c++;
		}
	}

	function saveList() {
		if (!list || list.length == 0) {
			document.cookie = options.cookieName + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/';
		} else {
			var val = '';
			if (options.append) {
				for (var i = 0; i < list.length; i++) {
					var product = list[i];
					var v = getSaveStr(product);
					val += (val.length > 0 ? options.recordDelim : '') + v;
				}
			} else {
				for (var i = list.length - 1; i >=0; i--) {
					var product = list[i];
					var v = getSaveStr(product);
					val += (val.length > 0 ? options.recordDelim : '') + v;
				}
			}
			document.cookie = options.cookieName + '=' + val + '; path=/';
		}
	}
	
	function getSaveStr(product) {
		var v = escape(product.id) + options.fieldDelim + escape(product.sku) + options.fieldDelim + escape(product.title) + options.fieldDelim + escape(product.price) + options.fieldDelim + escape(product.img);
		if (product.catId) {
			v += options.fieldDelim + escape(product.catId);
		}
		return v;
	}

	function getProductDetails() {
	
		if (! window.productDetails) {
			return;
		}
		try {
		
			var title = productDetails.title;
			var price = productDetails.price;
			var prodId = productDetails.productId;
			var sku = productDetails.partnumber;
			var img = productDetails.img;
			var catId = productDetails.categoryId;
			
			if (title && price && prodId) {
				var result = {
					title:title, 
					price:price, 
					id:prodId,
					sku:sku,
					img:img
				}
				if (catId && catId.length > 0) {
					result['catId'] = catId;
				}				
				return result;
			} else {
			// do nothing
			}
		} catch (e) {alert(e)};
		return;
	}


	function renderList(obj) {
		if (list.length == 0) return;
		var cId = $("#CatalogSearchForm input[name='catalogId']").attr('value');
		var lId = $("#CatalogSearchForm input[name='langId']").attr('value');
		var sId = $("#CatalogSearchForm input[name='storeId']").attr('value');

		var items = $('<ul></ul>');
		for (var i = 0; i < list.length; i++) {
			var product = list[i];
			var url = '/webapp/wcs/stores/servlet/product_storeId_' + sId + '_catalogId_' + cId + '_productId_' + product.id + '_langId_' + lId;
			if (product.catId && product.catId.length > 0) {
				url += '_categoryId_' + product.catId;
			}
			items.append('<li><a class="thumb" href="' + url + '"><img src="http://washford.scene7.com/is/image/Washford/' + 
			product.img + '?$prodthumb$" /></a><div class="pricedescbox"><a class="title" href="' + url + '" title="Click to view product details">' + 
			product.title + '</a><a class="price" href="' + url + '"><div >' + product.price + '</div></a></div></li>');
		}

		obj.append('<h2>recently viewed</h2>');
		obj.append(items);
		obj.show();

	}

	function addProduct(product, atTail) {
		if (!product) return;

		if (atTail) {
			// append to the tail end of the list
			list[list.length] = product;
		} else {
			// insert it into the front of the list
			list.splice(0,0,product);
		}
		
		if (list.length > 1) {
			// de-dupe the list
			var beginIndex = atTail ? 0 : 1;
			var endIndex = atTail ? list.length - 1 : list.length;

			// iterate through the list to remove duplicates
			var i = beginIndex;
			while (i < endIndex) {
				if (list[i].id == product.id) {
					list.splice(i,1);
					endIndex--;
				} else {
					i++;
				}
			}
		}
		
		//IE compatible list truncation
		if (atTail) {
			while(list.length > options.listLength) {
				list.splice(0, 1); //chop off list head
			}
		} else {
			while(list.length > options.listLength) {
				list.splice(options.listLength, 1); //chop off list tail
			}
		}
	}

};
})(jQuery);
