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

	var defaults = {
		cookieName: 'rctview',
		listLength: 5,
		titleLength: 20,
		fieldDelim: '|',
		recordDelim: '~',
		append: false,
		useAsRemove: false,		//only if you want to use this function to remove
		productIfUsed: null		//this will be declared if using useAsRemove
	};
	
 	var list = new Array();
	var options = $.extend(defaults, options);
	
	try {
		if (options.useAsRemove) removeFromCookie(options.productIfUsed);
		else {
			setUpFunc();
			loadList();
			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();
	}
	
	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 = prods.length - 1; i >=0; i--) {
			var attrs = prods[i].split(options.fieldDelim);
			var p = {
				id:unescape(attrs[0])
			};
			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 = '';
			for (var i = 0; i < list.length; i++) {
					var product = list[i];
					var v = getSaveStr(product);
					val += (val.length > 0 ? options.recordDelim : '') + v;
			}
			var date = new Date();
			//set cookie to expire in 30 days time
			date.setTime(date.getTime() + (30*24*60*60*1000));
			var expires = '; expires=' + date.toGMTString();
			document.cookie = options.cookieName + '=' + val + expires + '; path=/';
		}
	}
	
	function getSaveStr(product) {
		var v = escape(product.id);
		return v;
	}

	function getProductDetails() {
	
		if (! window.productDetails) {
			return;
		}
		try {
		
			var prodId = productDetails.productId;
			
			if (prodId) {
				var result = {
					id:prodId
				}
				return result;
			} else {
			// do nothing
			}
		} catch (e) {alert(e)};
		return;
	}


	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
			}
		}
	}
	
	//extra set up needed
	function setUpFunc() {
		//hide hover text
		$("#recentlyviewed .details").css("display","none");
		
		//for each item
		$("#recentlyviewed ul").each(function(){
			//get product id
			var thisProdId = $(this).attr("id");
		
			//info show hide details
			$(this).find(".showdetails").mouseover(function(){
				$(this).parent().parent().find("div.details").show();
			}).mouseout(function(){
				$(this).parent().parent().find("div.details").hide();
			});
			
			
			//close and remove from recently viewed
			$(this).find("span.close").click(function(){
				//remove from cookies
				if (removeFromCookie(thisProdId)) {
				
					//remove from dom				
					$(this).parent().parent().remove();
					if ($("#recentlyviewed ul").length == 0) $("#recentlyviewed").remove();
				
				}
			});
		});		
					
	}
	
	function removeFromCookie(name) {
		//get old recently viewed cookie
		var oldCookieVal = getCookie(options.cookieName);
		
		//split old cookie value
		var oldRecentlyViewedItems = oldCookieVal.split('~');
		
		//create new cookie value
		var newCookie = new Array();
		for (var i = 0; i < oldRecentlyViewedItems.length; i++) {
			//push all but the removed cookie
			if (oldRecentlyViewedItems[i] != name) newCookie.push(oldRecentlyViewedItems[i]);	
		}
		//reset cookie value
		var newCookieString = newCookie.join('~');
		document.cookie = options.cookieName + '=' + newCookieString + '; path=/';
		//alert(document.cookie);
		return true;		
	}
	
	function getCookie(check_name) {
		// split this cookie up into name/value pairs		
		var a_all_cookies = document.cookie.split( ';' );
		var a_temp_cookie = '';
		var cookie_name = '';
		var cookie_value = '';
		var b_cookie_found = false; // set boolean t/f default f
	
		for ( i = 0; i < a_all_cookies.length; i++ )
		{
			// split apart each name=value pair
			a_temp_cookie = a_all_cookies[i].split( '=' );	
	
			// and trim left/right whitespace while we're at it
			cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
			// if the extracted name matches passed check_name
			if ( cookie_name == check_name )
			{
				b_cookie_found = true;
				// we need to handle case where cookie has no value but exists (no = sign, that is):
				if ( a_temp_cookie.length > 1 )
				{
					cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
				}
				// note that in cases where cookie is initialized but no value, null is returned
				return cookie_value;
				break;
			}
			a_temp_cookie = null;
			cookie_name = '';
		}
		if ( !b_cookie_found )
		{
			return null;
		}
	}

};
})(jQuery);