/**
 * @cfg {Integer} maxItems A number between 1 and 10 to indicate the count of maximum displayed products.
 */

/**
 * Add a list of last viewed products.
 * 
 * The `.productLastViewed()` method append a list of last viewed products to each element in the set of matched elements.
 * 
 * This method depends on a storage controller in defined as ''Menu'' in the ''SF PageType'' named ''Script-ProductLastViewed''.
 * 
 * ### Examples
 * Perform an ajax request.
 * 
 * JavaScript:
 * 
 *     de_epages('#lastProducts')
 *         .productLastViewed({
 *             maxItems: 3
 *         });
 * 
 * HTML:
 * 
 *     <div id="lastProducts">
 *     </div>
 * 
 * Results:
 * 
 *     <div id="lastProducts">
 *       <ul class="de_epages-catalogUiProductLastViewed">
 *         <li>
 *           <a href="?ObjectPath=/Example1..."><img src="/Webroot...example1...image.jpg" />Example 1</a>
 *         </li>
 *         <li>
 *           <a href="?ObjectPath=/Example2..."><img src="/Webroot...example2...image.jpg" />Example 2</a>
 *         </li>
 *         <li>
 *           <a href="?ObjectPath=/Example3..."><img src="/Webroot...example3...image.jpg" />Example 3</a>
 *         </li>
 *       </ul>
 *     </div>
 * 
 * 
 * @param {Object} [options] A map of additional options pass to the method.
 * @param {Integer} maxItems A number between 1 and 10 to indicate the count of maximum displayed products.
 * 
 * @method productLastViewed
 * @member jQuery
 * 
 * @since 6.11.0
 */

/*
 * @copyright		© Copyright 2006-2010, epages GmbH, All Rights Reserved.
 *
 * @module			de_epages.catalog.ui.productLastViewed
 */

define("de_epages/catalog/ui/productlastviewed", [
	"jquery",
	"de_epages",
	"util/storage",

	"jquery/ui/widget",
	"jquery/tmpl"
], function ($, de_epages, storage) {

	$.widget( 'ui.catalogUiProductLastViewed', {

		options: {
			maxItems: 5
		},

		_create: function(){
			this.listElem = $('<ul>').addClass('de_epages-catalogUiProductLastViewed');

			this.products = storage.localStorage('Catalog::ProductLastViewed.list');

			if( this.products ){

				var tstampMap = [],
					tstampData = [],
					tmplData = [],
					maxItems = this.options.maxItems-1;

				// create am map with tstamps to sort
				$.each( this.products, function( id, product ){
					tstampMap.push( product.tstamp );
					tstampData[ product.tstamp ] = product;
				});

				// sort
				tstampMap = tstampMap.sort().reverse();

				// push products in the right order
				$.each( tstampMap, function( i, tstamp ){
					tmplData.push( tstampData[ tstamp ] );

					if( i >= maxItems ){
						return false;
					}
				});

				// append elements via template
				this.element.append( this.listElem.append( $.tmpl( '<li><a href="?ObjectPath=${objectPath}"><img src="${image}" />${name}</a></li>', tmplData ) ) );
			}
		},

		destroy: function(){
			this.listElem.remove();

			this._superApply(arguments);
		}
	});

	return de_epages;

});