(function() {
	addEvent('productsready',function() {
		motorola.controls.template = $('productTemplate').getFirst().dispose();
	});
	motorola.pages.SupportFamily = new Class({
		Extends: motorola.controls.Page,
		Implements: [Events, Options],
		collapseProductStyles: {
			'opacity':'0'
		},		
		columns: 4,
		defaultViewProducts: null,
		expandProductStyles: {
			'opacity':'1'
		},		
		initialData: null,
		productIds: [],
		productIdsBySeries: {},
		productStorageName: 'data',
		cache: {},
		rows: 3,
		maxPerPage: null,
		maxViewProducts: 120,
		pagination: null,
		productOptions: {
			highlightedStyles: {
				'border-width': '2px',
				'border-style': 'solid',
				'border-color': '#c6dde8'
			},
			unhighlightedStyles: {
				'border-width': '2px',
				'border-style': 'solid',
				'border-color': '#fff'
			}
		},
		searcher: null,
		seriesSelect: null,
		viewingAll: false,
		
		//
		//
		//
		initialize: function() {

			this.parent();
			addEvent('productsready',this.productsready.bind(this));
			this.maxPerPage = this.defaultViewProducts = this.columns * this.rows;
		},
		
		//
		//
		//
		addToSeries: function(productSeries, productId) {

			// Get the list of product ids for this series
			var productIdsBySeries = this.productIdsBySeries;
			var ids = productIdsBySeries[productSeries];
			
			// If the list does not exist - create it
			if ( !ids ) {
				ids = [];
				productIdsBySeries[productSeries] = ids;
			}
			ids.push(productId);
		},
		
		//
		//
		//
		domready: function() {

			motorola.utils.PngFix.fixClass('png');
		},
		
		//
		//
		//
		fadeProducts: function(styles, spec) {
		
			// Setup the fade out with the spec
			var elementOptions = {};
			var i;
			var products = $E('ol.products').getElements('.product');

			var length = products.length;
			for (i = 0; i < length; i = i + 1) {
				elementOptions['' + i] = styles;
			}		

			var effectsOptions = $extend($clone(motorola.fxoptions), spec);
	
			var elementEffects = new Fx.Elements(products,effectsOptions);
			elementEffects.start(elementOptions);			
		},
		
		//
		//
		//
		filter: function() {
	
			// Ignore case where there is no selected option
			var seriesSelect = this.seriesSelect;
			if ( !$defined(seriesSelect) || !$defined(seriesSelect.selectedOption) ) {
				return;
			}
			
			// Get the corresponding product Ids for the selected 
			// series
			var selectedOption = seriesSelect.selectedOption;
			var productIds;
		
			// Handle view all case
			var value = selectedOption.value;
			if ( value === '' ) {
				productIds = this.productIds;
				value = 'View All';
			}
			// Otherwise filter products on series
			else {
				productIds = this.productIdsBySeries[value];
			}

			// Fade out and update page
			this.fadeProducts(this.collapseProductStyles, {
				'onStart': this.updateProductsListStart.bind(this),
				'onComplete': this.updateProductsListFinish.pass([productIds],this),
				'duration': motorola.fxoptions.duration
			});
			
			// Update pagination
			this.setupPagination(productIds);
			
			dcsMultiTrack('WT.ti', 'Support - Search by Series', 'WT.cg_n', 'Search by Model', 'WT.cg_s', 'Product Search Field', 'DCSext.srch_series', value);
		},		
		
		//
		// 
		//
		getFromCache: function(data, id) {
		
			var cache = this.cache;
			var product;
			// Check if product is already in cache
			product = cache[id];
			if ( !product ) {
			
				// Product is not in cache - create it 
				// and to cache
				var productData = data[id];		
				if ( !productData.productId ) {
					productData.productId = id;
				}
				product = new motorola.controls.SupportProduct(productData,this.productOptions);
				cache[id] = product;
			}	
			else {
			
				product.retrieve(this.productStorageName).forceUnhighlight();
			}

			return product;			
		},
		
		//
		// 
		//
		hideLoading: function() {
		
		},
		
		//
		//
		//
		setupPagination: function(productIds) {
		
			var totalCount = productIds.length;
			var maxPerPage = this.maxPerPage;
			var defaultViewProducts = this.defaultViewProducts;
			
			// If there is no series filter (ie currently
			// viewing all products), then
			// we only ever want to show the default
			// pages per view
			var seriesSelect = this.seriesSelect;
			if ( $defined(seriesSelect) && $defined(seriesSelect.selectedOption) &&  seriesSelect.selectedOption.value === '') {
				maxPerPage = this.maxPerPage = defaultViewProducts;
			}
			// Also need to reset max per page if currently
			// viewing all. This handles the case
			// where user is viewing all, then clears
			// the filter then filters again
			if ( this.viewingAll ) {
				maxPerPage = this.maxPerPage = this.maxViewProducts;
			}
		
			// Setup pagination object
			var pagination = this.pagination = new motorola.controls.Pagination(productIds,{maxPerPage:maxPerPage});
			pagination.addEvent('onSet',this.replacePagination.bind(this));
			pagination.pager.replaces($E('div.pagination'));		
			
			// Setup all/default links
			var viewAll = $E('div.navigation .viewAll');
			var viewAllLink = viewAll.getElement('a');
			viewAllLink.set('text',viewAllLink.get('text').replace(/\d*$/,totalCount));	
			
			// Add events to view all link
			// with the max per page 
			viewAll.removeEvents();
			viewAll.addEvent('click',this.viewAll.bindWithEvent(this,[productIds]));

			// Add events to view default link, update link text
			var viewDefault = $E('div.navigation .viewDefault');
			viewDefault.removeEvents();
			viewDefault.addEvent('click', this.viewDefault.bindWithEvent(this,[productIds]));
			viewDefault.getElement('a').set('html','view '.concat(defaultViewProducts).concat(' per page'));
			
			// Always hide the view all link if the total
			// count is greater than the max viewable products
			// or if the total count is that the page size
			if ( Browser.Engine.trident4 || totalCount > this.maxViewProducts || totalCount < defaultViewProducts  ) {
				viewAll.setStyle('display','none');
				viewDefault.setStyle('display', 'none');
			}
			// Show view default link
			else if ( this.viewingAll ) {
				viewAll.setStyle('display','none');
				viewDefault.setStyle('display', 'block');
			}
			// Otherwise show view default link
			else {
				viewAll.setStyle('display','block');
				viewDefault.setStyle('display', 'none');			
			}
		},
		
		//
		//
		//
		load: function() { },
		
		//
		//
		//
		productsready: function() {

			// Setup active search
			var searcher = this.searcher = new motorola.controls.ProductSearcher($('s'),$('searchResults'),{
				'onSelect': function(searcher) {
					var url;
					var productFamilyName = document.getElementById('productFamilyName').value + ';Model Search Field';
					dcsMultiTrack('WT.ti', 'Support- Model Search Field Click', 'WT.cg_n', 'Search by Model', 'WT.cg_s', 'Product Search Field', 'DCSext.action', productFamilyName, 'WT.z_evt2', '12');
					if (searcher.highlighted) {
						url = searcher.highlighted.retrieve('productData').productUrl;
						location.href = url;
					}
				}
			});
			var products = searcher.products;
			
			// Determine if the series dropdown should
			// be displayed
			var showSeries = this.initialData.filterable === '1' ? true : false;
	
			// Setup product ID list, search's
			// product list and series list and map
			var productId, product, productData;
			var productIds = this.productIds;
			var productsData = this.initialData.productsData;
			var series, data;
			var allSeries = [];
			for (productId in productsData) {
			
				productIds.push(productId);
				
				// Add product to active search product list
				data = productsData[productId];
				data.productId = productId;
				products.push(data);
				
				// Add to list of products for this series
				if ( !showSeries ) {
					continue;
				}
				series = data.filterValue;
				this.addToSeries(series, productId);
				
				// Add series to list of series
				if ( !allSeries.contains(series) ) {
					allSeries.push(series);
				}
			}

			// Setup product elements
			this.updateProductsList(productIds)
			
			// Setup pagination		
			this.setupPagination(productIds);				
	
			// Setup series
			if ( showSeries && $('sel-series') ) { 
				this.setupSeries(allSeries);
			}
		},		
		
		//
		//
		//
		replacePagination: function(pageNum,items) {
	
			// Update the pagination controls
			this.pagination.pager.replaces($E('div.pagination'));
			
			// Setup the fade out and update page with new items
			this.fadeProducts(this.collapseProductStyles, {
				'onStart': this.updateProductsListStart.bind(this),
				'onComplete': this.updateProductsListFinish.pass([items],this),
				'duration': motorola.fxoptions.duration
			});
		},	
		
		//
		//
		//
		updateProductsListFinish: function(newProducts) {
			this.updateProductsList(newProducts);
			this.pagination.inTransition = false;
		},
		
		//
		//
		//
		updateProductsListStart: function() {
			this.showLoading();
			this.pagination.inTransition = true;
		},	
		
		
		// A comparator for series
		compareSeries: function(serieA, serieB) {
			if (serieA > serieB) {
				return 1;
			}
			if (serieA == serieB) {
				return 0;
			}
			if (serieA < serieB) {
				return -1;
			}
		},
		
		setupSeries: function(series) {
			// First sorting the series
			motorola.quicksort(series, 0, series.length -1, this.compareSeries);
			// After setup the series options
			var seriesSelect = $('sel-series');
			var option;
			var options = [];
			for ( var i = 0 ; i < series.length ; i++ ) {
				option = new Element('option', {
					html: series[i],
					value: series[i]
				});	
				options.push(option);
			}
			seriesSelect.adopt(options);

			// Create the drop down
			var viewSelectOptions = $extend($clone(motorola.fxoptions),{
				'onSelect': [this.filter.bind(this), motorola.utils.storeDropdownValue],
				'duration': 250,
				'initialValue': '',
				'animate': Browser.Engine.webkit
			});
			var seriesSelect = this.seriesSelect = new MOTO.StyledForm.Dropdown(seriesSelect,viewSelectOptions);
			var searcher = this.searcher;
			if (searcher.field){
				seriesSelect.addEvents({
					'onExpand': function() { searcher.quitSearch();	},
					'onChange': function() { searcher.reset(); }
				});
			}
			
			// Display series container which contains
			// "or" text and drop down
			$('seriesWrap').setStyle('display','inline');
		},				
		
		//
		//
		//
		showLoading: function() {
		
		},		
		
		//
		//
		//
		updateProductsList: function(productIds) {

			// Clear the current product list and 
			// setup the new product blocks
		
			// Get the product block container 
			var parentEl = $('productTemplate').getParent(); 
			
			// Remove list of products (ol) from DOM
			var productList = $('productTemplate').dispose(); 

			// Remove product blocks from product list
			var products = productList.getChildren().dispose();			
		
			// Setup products - create product 
			// if it does not exist and add to cache
			// Add product to product list
			var productId, product, element;
			var productsData = this.initialData.productsData;
			var maxPerPage = this.maxPerPage;	
			var collapseStyles = this.collapseProductStyles;	
			var i = 0;
			while (i - maxPerPage && i - productIds.length) {
			
				// Get product from cache
				productId = productIds[i];
				product = this.getFromCache(productsData, productId);
				
				// Make sure product is collapsed so we 
				// can fade in
				product.set('styles', collapseStyles);
				
				// Add product to product list
				productList.adopt(product);
			
				i = i + 1;				
			}
			
			// Hide loading
			this.hideLoading();
			
			// Add product list to product block container
			parentEl.adopt(productList);	
			
			// Fade in options
			var expandStyles = this.expandProductStyles;
			this.fadeProducts(expandStyles, {
				'duration': motorola.fxoptions.duration
			});
		},
		
		//
		//
		//
		viewAll: function(e, productIds) {
			motorola.utils.stopEvent(e);
			
			// Set the max per page to be the max 
			// viewable products
			this.maxPerPage = this.maxViewProducts;
			this.viewingAll = true;
			
			// Setup the fade out and update page with new items
			this.fadeProducts(this.collapseProductStyles, {
				'onStart': this.updateProductsListStart.bind(this),
				'onComplete': this.updateProductsListFinish.pass([productIds],this),
				'duration': motorola.fxoptions.duration
			});
			
			// Update pagination controls
			this.setupPagination(productIds);
		},
		
		//
		//
		//
		viewDefault: function(e, productIds) {
		
			motorola.utils.stopEvent(e);
			
			// Set the max per page back to the default
			this.maxPerPage = this.defaultViewProducts;
			this.viewingAll = false;
			
			// Setup the fade out and update page with new items
			this.fadeProducts(this.collapseProductStyles, {
				'onStart': this.updateProductsListStart.bind(this),
				'onComplete': this.updateProductsListFinish.pass([productIds],this),
				'duration': motorola.fxoptions.duration
			});

			// Update pagination
			this.setupPagination(productIds);
		},		
		
		//
		//
		//
		destroy: function() {
		}
	});
	motorola.supportFamily = new motorola.pages.SupportFamily();
})();
motorola.supportFamily.utils = {
	beforeunload: function() {
		motorola.supportFamily.destroy();
		motorola.globals.Header.destroy();
		motorola.globals.Footer.destroy();
	}
};
