var searchBoxElement = Class.create
(
	{
		initialize: function (domNode, widgetId, newWindow)
		{
			this.domNode = domNode;
			this.widgetId = widgetId;
			this.newWindow = newWindow;

			this.fetchSuggestionsTimeout = null;
			this.suggestionHideHandler = null;
			
			this.searchBoxInput = this.domNode.select('.module_search_searchresultinputtext')[0];
			if (this.searchBoxInput)
			{
				this.searchBoxInput.observe
				(
					'keyup',
					this.triggerFetchSuggestions.bind(this, this.searchBoxInput)
				);
			}
			
			this.autocompleterBox = $('mst_search_box_autocompleter' + this.widgetId);
		},
		
		triggerFetchSuggestions: function (searchBoxInput)
		{
			if (this.fetchSuggestionsTimeout)
			{
				window.clearTimeout(this.fetchSuggestionsTimeout);
			}
			
			this.fetchSuggestionsTimeout = window.setTimeout
			(
				this.fetchSuggestions.bind(this, searchBoxInput),
				300
			);
		},
		
		fetchSuggestions: function (searchBoxInput)
		{
			var thisObj = this,
				parameters =
				{
					q: searchBoxInput.value,
					s: siteId,
					v: 'xml',
					cb: Math.round(Math.random() * 10000000)
				};
			
			new Ajax.Request
			(
				'/ebayanywhere/services/suggest/',
				{
					onComplete: function (response) 
					{
						thisObj.renderSuggestions(response.responseXML);
					},
					method: 'get',
					asynchronous: true,
					parameters: parameters
				}
			);
		},
		
		renderSuggestions: function (suggestionsXML)
		{
			var thisObj = this,
				parsedSuggestions = this.parseSuggestions(suggestionsXML);
			
			if (parsedSuggestions.keywordSuggestions.length > 0 || parsedSuggestions.productSuggestions.length > 0)
			{
				var autocompleterEntriesContainer = this.autocompleterBox.select('.mst_search_box_autocompleter_entries')[0];
				autocompleterEntriesContainer.update('');
				
				if (parsedSuggestions.keywordSuggestions.length > 0)
				{
					parsedSuggestions.keywordSuggestions.each
					(
						function (keywordSuggestion)
						{
							thisObj.renderKeywordSuggestion(keywordSuggestion, parsedSuggestions.query, autocompleterEntriesContainer);
						}
					);
				}
				
				if (parsedSuggestions.productSuggestions.length > 0)
				{
					this.renderProductSuggestionSeparator(parsedSuggestions.separatorText, autocompleterEntriesContainer);

					parsedSuggestions.productSuggestions.each
					(
						function (productSuggestion)
						{
							thisObj.renderProductSuggestion(productSuggestion, autocompleterEntriesContainer);
						}
					);
				}
				
				this.suggestionHideHandler = this.hideSuggestions.bind(this);
				
				$(document).observe
				(
					'click',
					this.suggestionHideHandler
				);
				
				this.showSuggestions();
			}
			else
			{
				this.hideSuggestions();
			}
		},
		
		renderKeywordSuggestion: function (keywordSuggestion, query, targetDomNode)
		{
			var thisObj = this,
				keywordSuggestionTemplate = $('searchBoxKeywordSuggestion' + this.widgetId).cloneNode(true);
				keywordSuggestionTemplate.id = '';
			
			keywordSuggestionTemplate.update(keywordSuggestion.Text.replace(new RegExp(query), '<span style="color: #0000ff !important;">' + query + '</span>'));
			
			targetDomNode.appendChild(keywordSuggestionTemplate);
			
			keywordSuggestionTemplate.observe
			(
				'mouseover',
				function ()
				{
					thisObj.searchBoxInput.blur();
					thisObj.searchBoxInput.oldValue = thisObj.searchBoxInput.value;
					thisObj.searchBoxInput.value = keywordSuggestion.Text;
				}
			);

			keywordSuggestionTemplate.observe
			(
				'mouseout',
				function ()
				{
					thisObj.searchBoxInput.value = thisObj.searchBoxInput.oldValue;
				}
			);
			
			keywordSuggestionTemplate.observe
			(
				'click',
				function ()
				{
					thisObj.domNode.select('.module_search_searchresultselect')[0].setValue('-1');
					thisObj.searchBoxInput.oldValue = thisObj.searchBoxInput.value;
					thisObj.domNode.select('.module_search_searchresultinputsubmit')[0].click();
				}
			);
		},
		
		renderProductSuggestionSeparator: function (separatorText, targetDomNode)
		{
			var thisObj = this,
			productSuggestionSeparatorTemplate = $('searchBoxProductSuggestionSeparator' + this.widgetId).cloneNode(true);
			productSuggestionSeparatorTemplate.id = '';
		
			productSuggestionSeparatorTemplate.select('.searchBoxProductSuggestionSeparatorText')[0].update(separatorText);

			targetDomNode.appendChild(productSuggestionSeparatorTemplate);
		},

		renderProductSuggestion: function (productSuggestion, targetDomNode)
		{
			var thisObj = this,
				productSuggestionTemplate = $('searchBoxProductSuggestion' + this.widgetId).cloneNode(true);
				productSuggestionTemplate.id = '';
				
			var imageNode = productSuggestionTemplate.select('.productSuggestionImg')[0],
				textNode = productSuggestionTemplate.select('.productSuggestionText')[0];
			
			imageNode.src = productSuggestion.Image.source;
			imageNode.alt = productSuggestion.Image.alt;
			imageNode.title = productSuggestion.Image.alt;
			imageNode.style.width = '32px';
			
			textNode.update(productSuggestion.Text);
			
			targetDomNode.appendChild(productSuggestionTemplate);
			
			productSuggestionTemplate.observe
			(
				'click',
				function ()
				{
					if (thisObj.newWindow)
					{
						window.open
						(
							productSuggestion.Url,
							'_blank'
						);
					}
					else
					{
						window.location.href = productSuggestion.Url;
					}
				}
			);
		},
		
		parseSuggestions: function (suggestionsXML)
		{
			var suggestions =
			{
				query: '',
				keywordSuggestions: [],
				productSuggestions: [],
				separatorText: ''
			};
			
			var suggestionNodes = suggestionsXML && suggestionsXML.documentElement ? suggestionsXML.documentElement.getElementsByTagName('Item') : [];
			var currentSuggestion, currentSuggestionArray, currentTagContent, currentImage, currentImageAttributes, separatorNode, queryNode;
			var i, x, z;

			if (suggestionNodes.length > 0)
			{
				for (i=0; i < suggestionNodes.length; i++)
				{
					currentSuggestionNode = suggestionNodes[i];
					currentSuggestion = {};
					
					for (y = 0; y < currentSuggestionNode.childNodes.length; y++)
					{
						if (currentSuggestionNode.childNodes[y].tagName != null)
						{
							if (currentSuggestionNode.childNodes[y].tagName == 'Image')
							{
								currentImage = {};
								currentImageAttributes = currentSuggestionNode.childNodes[y].attributes;
								
								for (z = 0; z < currentImageAttributes.length; z++)
								{
									currentImage[currentImageAttributes[z].nodeName] = currentImageAttributes[z].nodeValue;
								}
								
								currentSuggestion[currentSuggestionNode.childNodes[y].tagName] = currentImage;
							}
							else
							{
								currentTagContent = currentSuggestionNode.childNodes[y].hasChildNodes() ? currentSuggestionNode.childNodes[y].childNodes[0].nodeValue : '';
								currentSuggestion[currentSuggestionNode.childNodes[y].tagName] = currentTagContent;
							}
						}
					}
					
					suggestions[currentSuggestion.Description ? 'productSuggestions' : 'keywordSuggestions'].push(currentSuggestion);
				}
				
				if
				(
					(separatorNode = suggestionsXML.documentElement.getElementsByTagName('Separator')[0])
						&& separatorNode.attributes
						&& separatorNode.attributes.length > 0
						&& separatorNode.attributes[0]
				)
				{
					suggestions['separatorText'] = separatorNode.attributes[0].nodeValue;
				}
				
				if
				(
					(queryNode = suggestionsXML.documentElement.getElementsByTagName('Query')[0])
						&& queryNode.childNodes[0]
				)
				{
					suggestions['query'] = queryNode.childNodes[0].nodeValue;
				}
			}
			
			return (suggestions);
		},
		
		hideSuggestions: function ()
		{
			if (this.suggestionHideHandler)
			{
				Event.stopObserving(document, 'click', this.suggestionHideHandler);
				this.suggestionHideHandler = null;
			}
			
			this.autocompleterBox.select('.mst_search_box_autocompleter_entries')[0].update('');
			this.autocompleterBox.hide();
		},
		
		showSuggestions: function ()
		{
			var searchBoxInputOffsets = this.searchBoxInput.cumulativeOffset(),
				searchBoxInputDimensions = this.searchBoxInput.getDimensions();
			
			this.autocompleterBox.setStyle
			(
				{
					left: (searchBoxInputOffsets.left) + 'px',
					top: (searchBoxInputOffsets.top + searchBoxInputDimensions.height) + 'px',
					width: this.searchBoxInput.offsetWidth + 'px'
				}
			).show();
		}
	}
);

var itemListContainerElement = Class.create
(
	{
		initialize: function
		(
			domNode, name, query, sortOrder, numberOfResults, countryCode, territory, appId, parameter, widgetId, clickTracking,
				filter_TopRatedSellerOnly,
				filter_ListingType,
				filter_minPrice,
				filter_maxPrice,
				filter_Condition,
				filter_SellerId
		)
		{
			this.clickTracking = clickTracking;
			this.widgetId = widgetId;
			this.domNode = domNode;
			this.query = query;
			this.sortOrder = sortOrder;
			this.numberOfResults = numberOfResults;
			this.countryCode = countryCode;
			this.territory = territory;
			this.appId = appId;
			this.parameter = parameter;

			this.filter_TopRatedSellerOnly = filter_TopRatedSellerOnly;
			this.filter_ListingType = filter_ListingType;
			this.filter_minPrice = filter_minPrice;
			this.filter_maxPrice = filter_maxPrice;
			this.filter_Condition = filter_Condition;
			this.filter_SellerId = filter_SellerId;
			
			this.retryCounter = 0;
			this.refetchCounter = 0;
			
			this.itemsContainer = domNode.select('.items_container')[0];
		},
		
		TABLE_ELEMENT_INNERHTML_BUGGY: function()
		{
			try
			{
				var el = document.createElement('table');
				if (el && el.tBodies)
				{
					el.innerHTML = '<tbody><tr><td>test</td></tr></tbody>';
					var isBuggy = typeof el.tBodies[0] == 'undefined';
					el = null;
					return isBuggy;
				}
			}
			catch (e)
			{
				return true;
			}
		},

		showError: function (errorMessage)
		{
			var itemError = $('itemError').cloneNode(true);
			itemError.id = '';
			
			itemError.select('.error_content')[0].update(errorMessage);
			
			this.itemsContainer.update(itemError);
		},
		
		fetchSearchResults: function (response, status)
		{
			var thisObj = this;
			
			if (!response)
			{
				var itemFilters = [],
					outputSelectors = [],
					callParameters = {};

				callParameters['CACHEBUSTER'] = Math.round(Math.random() * 10000000);
				callParameters['OPERATION-NAME'] = 'findItemsAdvanced';
				callParameters['SERVICE-VERSION'] = '1.0.0';
				callParameters['GLOBAL-ID'] = 'EBAY-' + this.countryCode;
				callParameters['SECURITY-APPNAME'] = this.appId;
				callParameters['RESPONSE-DATA-FORMAT'] = 'JSON';
				callParameters['REST-PAYLOAD'] = 'true';
				callParameters['SERVICE-VERSION'] = '1.0.0';
				callParameters['paginationInput.entriesPerPage'] = this.numberOfResults;
				callParameters['paginationInput.pageNumber'] = 1;
					
				outputSelectors.push('SellerInfo');
				
				itemFilters.push
				(
					{
						name: 'LocatedIn',
						value: this.territory
					}
				);
					
				itemFilters.push
				(
					{
						name: 'HideDuplicateItems',
						value: 1
					}
				);
				
				if (this.refetchCounter == 0)
				{
					if (this.filter_Condition)
						itemFilters.push
						(
							{
								name: 'Condition',
								value: this.filter_Condition
							}
						);
					
					if (this.filter_ListingType)
						itemFilters.push
						(
							{
								name: 'ListingType',
								value: this.filter_ListingType
							}
						);
					
					if (parseInt(this.filter_maxPrice))
						itemFilters.push
						(
							{
								name: 'MaxPrice',
								value: this.filter_maxPrice
							}
						);
					
					if (parseInt(this.filter_minPrice))
						itemFilters.push
						(
							{
								name: 'MinPrice',
								value: this.filter_minPrice
							}
						);

					if (parseInt(this.filter_TopRatedSellerOnly))
						itemFilters.push
						(
							{
								name: 'TopRatedSellerOnly',
								value: this.filter_TopRatedSellerOnly ? true : false
							}
						);

					if (this.filter_SellerId)
						itemFilters.push
						(
							{
								name: 'Seller',
								value: this.filter_SellerId.split(',')
							}
						);
				}

				Object.keys(this.parameter).each
				(
					function (parameter)
					{

						var value,
							isChecked,
							parameterDomNode = thisObj.parameter[parameter];
													
						switch (parameter)
						{
							case 'categoryId':
								if (value = parameterDomNode.value.replace(/^\s+/, '').replace(/\s+$/, ''))							
								{
									callParameters.categoryId = value;
								}
							break;
						
							case 'keyword':

								if (value = parameterDomNode.value.replace(/^\s+/, '').replace(/\s+$/, ''))
								{
									callParameters.keywords = value;
								}
								
								break;
						
							case 'sortOrder':
							
								if (value = parameterDomNode.value.replace(/^\s+/, '').replace(/\s+$/, ''))
								{
									callParameters.sortOrder = value;
								}
								
								break;
						}
					}
				);
				
				itemFilters.each
				(
					function (itemFilter, i)
					{
						callParameters['itemFilter(' + i + ').name'] = itemFilter.name;
						
						if (Object.isArray(itemFilter.value))
						{
							itemFilter.value.each
							(
								function (itemFilterValue, j)
								{
									callParameters['itemFilter(' + i + ').value(' + j + ')'] = itemFilterValue;
								}
							);
						}
						else
						{
							callParameters['itemFilter(' + i + ').value'] = itemFilter.value;
						}
					}
				);
				
				outputSelectors.each
				(
					function (outputSelector, i)
					{
						callParameters['outputSelector(' + i + ')'] = outputSelector;
					}
				);
				
				new Ajax.Request
				(
					'/ebayapifinding/v1',
					{
						onComplete: function (response) 
						{ 
							if (response.status != 200)
							{
								thisObj.retryCounter++;
								if (thisObj.retryCounter < 5)
								{
									thisObj.fetchSearchResults.bind(thisObj).delay(2 * thisObj.retryCounter);
								}
							} 
							else
							{
								thisObj.retryCounter = 0;
								thisObj.fetchSearchResults(response.responseJSON.findItemsAdvancedResponse[0], response.status);
							}
						},
						method: 'get',
						asynchronous: true,
						evalJSON: 'force',
						parameters: callParameters
					}
				);
			}
			else
			{
				
				if (response.ack[0] == 'Failure')
				{
					this.showError
					(
						'eBay API Error: <br><br>'
							+ '[' + response.errorMessage[0].error[0].errorId[0]	+ '] '
							+ response.errorMessage[0].error[0].message[0]
					);
				}
				else
				{
					this.renderSearchResult(response.searchResult[0].item);
				}
			}
		},
				
		renderSearchResult: function (items)
		{
			items = items ? items : [];
					
			if (items.length == 0 && this.refetchCounter < 5)
			{
				this.refetchCounter++;
				this.fetchSearchResults.bind(this).delay(2 * this.refetchCounter);
			}
			
			//this.TABLE_ELEMENT_INNERHTML_BUGGY() ? this.itemsContainer.update('') : this.itemsContainer.innerHTML = '';
			this.itemsContainer.update('');
			for (var it = 0; it < items.length; it++)
			{
				var showLine = it < (items.length - 1) ? true : false;
				this.renderItem(items[it], showLine);
			}
			
			if (ebayLVTrClk && ebayLVTrClk._ebayLVTrackerClk_init_tracker)
			{
				ebayLVTrClk._ebayLVTrackerClk_init_tracker();
			}

			if (Prototype.Browser.IE)
			{
				$$('.module_search_searchresultinputtext').each(function(e) 
				{
					e.setStyle({padding: '1px', height: '20px', top: '-1px'});
				});
				
				$$('.module_search_searchresultinputsubmit').each(function(e) 
				{
					e.setStyle({top: '1px'});
				});
			}
		},
		
		renderItem: function (item, showLine)
		{
			if (this.clickTracking)
			{
				var targetUrl = 'http://rover.ebay.com/rover/1/' + this.clickTracking + '/4?trknvp=sid%3Dp' + this.clickTracking + '%2F4&loc=' + encodeURIComponent(item.viewItemURL[0]);
			}
			else
			{
				var targetUrl = item.viewItemURL[0];
			}
			var	itemTemplate = $('itemTemplate' + this.widgetId).cloneNode(true),
				GalleryURLNode = itemTemplate.select('.GalleryURL')
				LinkNode = itemTemplate.select('.Link'),
				TitleNode = itemTemplate.select('.Title'),
				SubTitleNode = itemTemplate.select('.SubTitle'),
				PriceNode = itemTemplate.select('.Price'),
				PricePostageNode = itemTemplate.select('.PricePostage')
				PostageNode = itemTemplate.select('.Postage'),
				BidsNode = itemTemplate.select('.Bids'),
				BidsTextSingularNode = itemTemplate.select('.BidsTextSingular'),
				BidsTextPluralNode = itemTemplate.select('.BidsTextPlural'),
				TimeLeftNode = itemTemplate.select('.TimeLeft'),
				PlaceBidNode = itemTemplate.select('.PlaceBid'),
				BuyItNowNode = itemTemplate.select('.BuyItNow'),
				ButItNowImgNode = itemTemplate.select('.BuyItNowImg'),
				lineNode = itemTemplate.select('.line');

			itemTemplate.id = '';
			GalleryURLNode[0].src = 'http://thumbs1.ebaystatic.com/pict/' + item.itemId[0] + '8080_100.jpg?' + Math.round(Math.random() * 10000000);
			GalleryURLNode[0].title = item.title[0];
			TitleNode[0].href = targetUrl;
			LinkNode[0].href = targetUrl;
			LinkNode[1].href = targetUrl;
			LinkNode[2].href = targetUrl;
			TitleNode[0].update(item.title[0]);
				
			if (item.subtitle && SubTitleNode.length)
			{
				SubTitleNode[0].update(item.subtitle[0]);
			}
			
			PriceNode[0].update(parseFloat(item.sellingStatus[0].convertedCurrentPrice[0].__value__).toFixed(2).replace(/\./, decimalSeparator) + ' ' + item.sellingStatus[0].convertedCurrentPrice[0]['@currencyId']);
			if (item.shippingInfo[0].shippingServiceCost)
			{
				PricePostageNode[0].update('+' + parseFloat(item.shippingInfo[0].shippingServiceCost[0].__value__).toFixed(2).replace(/\./, decimalSeparator) + ' ' + item.shippingInfo[0].shippingServiceCost[0]['@currencyId']);
				if (PostageNode.length)
				{
					PostageNode[0].show();
				}
			}

			if (item.sellingStatus[0].bidCount && BidsNode.length)
			{
				BidsNode[0].update(item.sellingStatus[0].bidCount[0]);
				
				if (item.listingInfo[0].listingType[0] == 'Auction' || item.listingInfo[0].listingType[0] == 'AuctionWithBIN')
				{
					if (item.sellingStatus[0].bidCount[0] == 1 && BidsTextSingularNode.length)
					{
						BidsTextSingularNode[0].show();
					}
					else if (BidsTextPluralNode.length)
					{
						BidsTextPluralNode[0].show();
					}
				}
			}				

			TimeLeftNode[0].update(parseIsoTimeSpan(item.sellingStatus[0].timeLeft[0], 'string', timeSpanUnitNames));
			if 
			(
				parseInt(parseIsoTimeSpan(item.sellingStatus[0].timeLeft[0], 'date', timeSpanUnitNames)[1]) == 0 &&							
				parseInt(parseIsoTimeSpan(item.sellingStatus[0].timeLeft[0], 'date', timeSpanUnitNames)[2]) == 0 &&						
				parseInt(parseIsoTimeSpan(item.sellingStatus[0].timeLeft[0], 'date', timeSpanUnitNames)[3]) == 0 &&
				parseInt(parseIsoTimeSpan(item.sellingStatus[0].timeLeft[0], 'date', timeSpanUnitNames)[4]) == 0 &&
				parseInt(parseIsoTimeSpan(item.sellingStatus[0].timeLeft[0], 'date', timeSpanUnitNames)[5]) < 24
			) 
			{
				TimeLeftNode[0].style.color = 'red';
			}

			if (item.listingInfo[0].listingType[0] == 'Auction' || item.listingInfo[0].listingType[0] == 'AuctionWithBIN')
			{
				PlaceBidNode[0].show();
			}
			else if (item.listingInfo[0].listingType[0] == 'FixedPrice' || item.listingInfo[0].listingType[0] == 'StoreInventory')
			{
				BuyItNowNode[0].show();
				
				if (ButItNowImgNode.length)
					ButItNowImgNode[0].show();
			}

			if (showLine)
			{
				lineNode[0].show();	
			}
			this.itemsContainer.appendChild(itemTemplate);
		}
	}
);

var mstItemListCollection = {};

var mstItemListContainerElement = Class.create
(
	{
		initialize: function (domNode, countryCode, territory, widgetId, clickTracking, mstFeedURL, overallItemFilter, sortKey, sortAsc, mstIdentifier, refreshRate, numberOfItems, pictureSize, minimumDiscount, priceRanges, logVisibleItems)
		{
			if (mstIdentifier)
			{
				mstItemListCollection[mstIdentifier] = this;
			}
			
			this.domNode = domNode;
			this.countryCode = countryCode;
			this.territory = territory;
			this.widgetId = widgetId;
			this.clickTracking = clickTracking;
			this.mstFeedURL = mstFeedURL;
			this.overallItemFilter = overallItemFilter;
			this.sortKey = sortKey;
			this.sortAsc = sortAsc;
			this.mstIdentifier = mstIdentifier;
			this.refreshRate = refreshRate;
			this.numberOfItems = numberOfItems;
			this.pictureSize = pictureSize;
			this.minimumDiscount = minimumDiscount;
			this.priceRanges = priceRanges;
			this.logVisibleItems = logVisibleItems;
			
			this.retryCounter = 0;
			this.refetchCounter = 0;
			
			this.aspects = {};
			this.aspectsInAllItems = [];
			
			this.filterData = {};
			
			this.mstItemsContainer = domNode.select('.mst_items_container')[0];
		},

		TABLE_ELEMENT_INNERHTML_BUGGY: function()
		{
			try
			{
				var el = document.createElement('table');
				if (el && el.tBodies)
				{
					el.innerHTML = '<tbody><tr><td>test</td></tr></tbody>';
					var isBuggy = typeof el.tBodies[0] == 'undefined';
					el = null;
					return isBuggy;
				}
			}
			catch (e)
			{
				return true;
			}
		},

		showError: function (errorMessage)
		{
			var mstItemError = $('mstItemError').cloneNode(true);
			mstItemError.id = '';
			
			//this.TABLE_ELEMENT_INNERHTML_BUGGY() ? mstItemError.select('.error_content')[0].update(errorMessage) : (mstItemError.select('.error_content')[0].innerHTML = errorMessage);
			mstItemError.select('.error_content')[0].update(errorMessage);
			
			this.mstItemsContainer.update(mstItemError);
		},

		fetchMstFeed: function (response, status)
		{
			var thisObj = this;
			
			if (!response)
			{
				if (!this.mstFeedURL)
				{
					this.showError(mstItemListErrorFeedLoading);
					return;
				}
				
				new Ajax.Request
				(
					this.mstFeedURL + (this.mstFeedURL.search(/\?/) == -1 ? '?' : '&') + Math.round(Math.random() * 10000000),
					{
						onComplete: function (response) 
						{ 
							if (response.status != 200)
							{
								thisObj.retryCounter++;
								if (thisObj.retryCounter < 5)
								{
									thisObj.showError(mstItemListErrorFeedLoading);
									thisObj.fetchMstFeed.bind(thisObj).delay(2 * thisObj.retryCounter);
								}
								else
								{
									thisObj.showError(mstItemListErrorFeedLoading);
								}
							} 
							else
							{
								thisObj.retryCounter = 0;
								thisObj.fetchMstFeed(response.responseXML, response.status);
							}
						},
						method: 'get',
						asynchronous: true
					}
				);
			}
			else
			{
				if (this.refreshRate > 0)
				{
					this.fetchMstFeed.bind(this).delay(this.refreshRate * 60);
				}

				this.renderFeedContent(response);
			}
		},
		
		acceptFeedData: function (aspects, aspectsInAllItems, priceRangeSortOrder)
		{
			this.aspects = aspects;
			this.aspectsInAllItems = aspectsInAllItems;
			
			var priceRangeSortOrder = priceRangeSortOrder;
			
			if (this.refreshRate > 0)
			{
				this.fetchMstFeed.bind(this).delay(this.refreshRate * 60);
			}
			
			if(mstFilterConnectionCollection[this.mstIdentifier])
			{
				var thisObj = this;
				
				mstFilterConnectionCollection[this.mstIdentifier].each
				(
					function (mstFilter)
					{
						mstFilter.acceptAspectsForItems(thisObj.aspects, priceRangeSortOrder, thisObj.aspectsInAllItems);
						
						window.setTimeout
						(
							mstFilter.shareFilterDataWithItemBoxes.bind(mstFilter),
							0
						);
					}
				);
			}
			else
			{
				this.filterItems();
			}
			
			if (ebayLVTrClk && ebayLVTrClk._ebayLVTrackerClk_init_tracker)
			{
				ebayLVTrClk._ebayLVTrackerClk_init_tracker();
			}
			
			this.aspects = {};
			this.aspectsInAllItems = [];
		},
		
		renderFeedContent: function(feedContent)
		{
			var thisObj = this,
				mstItems = this.parseFeedXml(feedContent);
			
			if (mstItems.length == 0)
			{
				this.showError(mstItemListErrorFeedEmpty);
			}
			else
			{
				if (this.sortKey != 'none')
				{
					this.sortMstItems(mstItems);
				}
				
				this.mstItemsContainer.update('');
				
				mstItems.each
				(
					function (mstItem)
					{
						thisObj.renderMstItem(mstItem);
					}
				);

				if (mstFilterConnectionCollection[this.mstIdentifier])
				{
					mstFilterConnectionCollection[this.mstIdentifier].each
					(
						function (mstFilter)
						{
							window.setTimeout
							(
								mstFilter.shareFilterDataWithItemBoxes.bind(mstFilter),
								0
							);
						}
					);
				}
				else
				{
					this.filterItems();
				}
				
				if (ebayLVTrClk && ebayLVTrClk._ebayLVTrackerClk_init_tracker)
				{
					ebayLVTrClk._ebayLVTrackerClk_init_tracker();
				}
			}
			
			this.aspects = {};
			this.aspectsInAllItems = [];
		},
		
		sortMstItems: function (mstItems)
		{
			mstItems.sort(this.customItemSorter.bind(this));
		},
		
		customItemSorter: function(mstItem1, mstItem2)
		{
			if (this.sortKey in mstItem1 && this.sortKey in mstItem2)
			{
				if (this.sortKey == 'hptoRanking')
				{
					mstItem1[this.sortKey] = parseInt(mstItem1[this.sortKey]);
					mstItem2[this.sortKey] = parseInt(mstItem2[this.sortKey]);

					if (isNaN(mstItem1[this.sortKey]))
					{
						mstItem1[this.sortKey] = (this.sortAsc ? 10000 : 0);
					}
					
					if (isNaN(mstItem2[this.sortKey]))
					{
						mstItem2[this.sortKey] = (this.sortAsc ? 10000 : 0);
					}
				}
								
				if (this.sortAsc) 
				{
					return (mstItem1[this.sortKey] > mstItem2[this.sortKey] ? 1 : -1);
				}
				else
				{
					return (mstItem1[this.sortKey] < mstItem2[this.sortKey] ? 1 : -1);
				}
			}
			else if (this.sortKey in mstItem1)
			{
				return (-1);
			}
			else
			{
				return (1);
			}
		},
		
		mstItemMatchesOverallItemFilter: function (mstItem)
		{
			var itemMatchesFilter = true;

			this.overallItemFilter.tagFilter.each
			(
				function (tagFilter)
				{
					if (tagFilter.key == 'Savings')
					{
						if (!mstItem[tagFilter.key] || parseInt(mstItem[tagFilter.key]) < parseInt(tagFilter.value))
						{
							itemMatchesFilter = false;
							throw $break;
						}
					}
					else
					{
						if (mstItem[tagFilter.key] != tagFilter.value)
						{
							itemMatchesFilter = false;
							throw $break;
						}
					}
				}
			);
			
			if (itemMatchesFilter)
			{
				this.overallItemFilter.aspectFilter.each
				(
					function (aspectFilter)
					{
						if
						(
							!mstItem.Aspects
								|| !mstItem.Aspects[aspectFilter.key]
								|| mstItem.Aspects[aspectFilter.key].indexOf(aspectFilter.value) == -1
						)
						{
							itemMatchesFilter = false;
							throw $break;
						}
					}
				);
			}
			
			return (itemMatchesFilter);
		},
		
		renderMstItem: function (mstItem)
		{
			if (!mstItem.ViewItemURLForNaturalSearch)
			{
				mstItem.ViewItemURLForNaturalSearch = 'http://cgi.' + siteSubDomain + 'ebay.' + siteTLD + '/ws/eBayISAPI.dll?ViewItem&item=' + mstItem.ItemID
			}
			
			if (this.clickTracking)
			{
				var targetUrl = 'http://rover.ebay.com/rover/1/' + this.clickTracking + '/4?trknvp=sid%3Dp' + this.clickTracking + '%2F4&loc=' + encodeURIComponent(mstItem.ViewItemURLForNaturalSearch);
			}
			else
			{
				var targetUrl = mstItem.ViewItemURLForNaturalSearch;
			}
			
			var currencyTemplate = new Template(currencyFormat),
				mstItemTemplate = $('mstItemTemplate' + this.widgetId).cloneNode(true),
				GalleryURLNode = mstItemTemplate.select('.GalleryURL'),
				LinkNode = mstItemTemplate.select('.Link'),
				TitleNode = mstItemTemplate.select('.Title'),
				PriceNode = mstItemTemplate.select('.Price'),
				RRPNode = mstItemTemplate.select('.RRP'),
				RRPContainerNode = mstItemTemplate.select('.RRPContainer'),
				SavingsContainerNode = mstItemTemplate.select('.SavingsContainer'),
				SavingsNode = mstItemTemplate.select('.Savings'),
				ShippingContainerNode = mstItemTemplate.select('.ShippingContainer'),
				ShippingRowNode = mstItemTemplate.select('.ShippingRow'),
				ShippingNode = mstItemTemplate.select('.Shipping');

			mstItemTemplate.id = 'item_' + '_' + Math.round(Math.random() * 10000000) + '_' + this.widgetId + '_' + mstItem.ItemID;
			
			var itemTitle = mstItem.hptoTitle ? mstItem.hptoTitle : mstItem.Title;

			if (this.pictureSize == 225){
				GalleryURLNode[0].src = 'http://thumbs1.ebaystatic.com/pict/' + mstItem.ItemID + '2525_100.jpg?' + Math.round(Math.random() * 10000);
			}
			else
			{
				GalleryURLNode[0].src = 'http://thumbs1.ebaystatic.com/pict/' + mstItem.ItemID + '4040_100.jpg?' + Math.round(Math.random() * 10000);
			}	
			GalleryURLNode[0].title = itemTitle;
			GalleryURLNode[0].alt = itemTitle;
			TitleNode[0].href = targetUrl;
			TitleNode[0].update(itemTitle);
			LinkNode[0].href = targetUrl;
			LinkNode[1].href = targetUrl;
			LinkNode[0].writeAttribute('clickid', LinkNode[0].readAttribute('clickid') + '::' + mstItem.ItemID);
			LinkNode[1].writeAttribute('clickid', LinkNode[1].readAttribute('clickid') + '::' + mstItem.ItemID);
			
			if (mstItem.RRP && parseFloat(mstItem.RRP) > parseFloat(mstItem.ConvertedCurrentPrice))
			{
				RRPNode[0].update
				(
					currencyTemplate.evaluate({price: parseFloat(mstItem.RRP).toFixed(2).replace(/\./, decimalSeparator)})
				);
				
				if (SavingsContainerNode[0])
				{
					if (mstItem.Savings && mstItem.Savings >= this.minimumDiscount)
					{
						SavingsNode[0].update(mstItem.Savings);
						SavingsContainerNode[0].show();
					}
				}
			}
			else
			{
				RRPContainerNode[0].hide();
				RRPContainerNode[1].hide();
			}
			
			PriceNode[0].update
			(
				currencyTemplate.evaluate({price: parseFloat(mstItem.ConvertedCurrentPrice).toFixed(2).replace(/\./, decimalSeparator)})
			);
			
			if (typeof mstItem.ShippingCost == 'undefined')
			{
				ShippingRowNode[0].hide();
			}
			else
			{
				if (mstItem.ShippingCost > 0)
				{
					ShippingNode[0].update
					(
						currencyTemplate.evaluate({price: parseFloat(mstItem.ShippingCost).toFixed(2).replace(/\./, decimalSeparator)})
					);
				}
				else
				{
					ShippingNode[0].update(mstItemPostageFree);
				}
			}
			
			mstItemTemplate.mstItem = mstItem;
			
			this.mstItemsContainer.appendChild(mstItemTemplate);
		},
		
		parseFeedXml: function (feedContent)
		{
			var itemsNode = feedContent && feedContent.documentElement ? feedContent.documentElement.getElementsByTagName('Item') : [];
			var mstItems = [], currentItem, currentItemArray, currentTag, currentTagContent, aspectsArray, currentSavings, currentDiscount, keyName, minPriceRange, maxPriceRange;
			var i, x, z;
			var rawAspects = {}, aspectsCounter = {};
			var numberOfItemsToRender = Math.min(itemsNode.length, 150);
			
			if (numberOfItemsToRender > 0)
			{
				for (i = 0; i < numberOfItemsToRender; i++)
				{
					currentItem = itemsNode[i];
					
					
					currentItemArray = {};
					
					for (y = 0; y < currentItem.childNodes.length; y++)
					{
						if (currentItem.childNodes[y].tagName != null)
						{
							currentTag = currentItem.childNodes[y].tagName;
							
							currentTagContent = currentItem.childNodes[y].hasChildNodes() ? currentItem.childNodes[y].childNodes[0].nodeValue : '';

							if (currentTag == 'AspectString')
							{
								if (currentTagContent.length > 0)
								{
									aspects = currentTagContent.split(';');
									aspectsArray = {};
									
									if (aspects.length > 0)
									{
										for (z = 0; z < aspects.length; z++)
										{
											if (aspects[z].length > 0)
											{
												currentAspect = aspects[z].split('=');
												
												if (currentAspect.length == 2)
												{
													if (currentAspect[0].length == 0 || currentAspect[1].length == 0)
													{
														//for now do nothing
														//this.showError('show error malformed aspect: ' +  aspects[z]);	
													}
													else
													{
														aspectsArray[currentAspect[0]] = currentAspect[1].split(',');
													}
												}
												else
												{
													//for now do nothing
													//this.showError('show error malformed AspectString');
												}
											}
										}
									}
									else
									{
										//for now do nothing
										//this.showError('show error aspects string feed is empty');
									}
									
									currentItemArray['Aspects'] = aspectsArray;
								}
							}
							else
							{
								currentItemArray[currentTag] = currentTagContent;
							}
						}
					}
					
					if (currentItemArray.ItemID)
					{
						if ('ConvertedCurrentPrice' in currentItemArray && 'RRP' in currentItemArray)
						{
							if (parseFloat(currentItemArray['RRP']) > 0 && parseFloat(currentItemArray['RRP']) > parseFloat(currentItemArray['ConvertedCurrentPrice']))
							{
								currentSavings = Math.floor(((currentItemArray['RRP'] - currentItemArray['ConvertedCurrentPrice']) / currentItemArray['RRP']) * 100);
								currentDiscount = parseFloat(parseFloat(currentItemArray['RRP']) - parseFloat(currentItemArray['ConvertedCurrentPrice'])).toFixed(2);
								
								if (isNaN(currentSavings) == false)
								{
									currentItemArray['Savings'] = currentSavings;
								}

								if (isNaN(currentDiscount) == false)
								{
									currentItemArray['Discount'] = currentDiscount;
								}
							}
						}
							
						if (!currentItemArray['GarmentName'])
						{
							if (currentItemArray['hptoGarmentName'])
							{
								currentItemArray['GarmentName'] = currentItemArray['hptoGarmentName'];
							}
							else if (currentItemArray['PrimaryCategoryName'])
							{
								var lastPartOfPrimaryCategoryName = currentItemArray['PrimaryCategoryName'].split(':').pop();
								currentItemArray['GarmentName'] = lastPartOfPrimaryCategoryName.replace('  ',' & ');
							}
						}	
						
						this.priceRanges.each
						(
							function (priceRange)
							{
								minPriceRange = parseFloat(priceRange.minPrice);
								maxPriceRange = parseFloat(priceRange.maxPrice);
								
								if (maxPriceRange == 0)
								{
									if (parseFloat(currentItemArray['ConvertedCurrentPrice']) >= minPriceRange)
									{
										currentItemArray['PriceRange'] = priceRange.filterText;
										throw $break;
									}
								}
								else
								{
									if
									(
										parseFloat(currentItemArray['ConvertedCurrentPrice']) >= minPriceRange
											&& parseFloat(currentItemArray['ConvertedCurrentPrice']) <= maxPriceRange
									)
									{
										currentItemArray['PriceRange'] = priceRange.filterText;
										throw $break;
									}
								}
							}
						);
						
						if (this.mstItemMatchesOverallItemFilter(currentItemArray))
						{
							if (!currentItemArray.Aspects)
							{
								currentItemArray['Aspects'] = {};
							}
							
							for (keyName in currentItemArray)
							{
								if (keyName != 'Aspects' && keyName != 'Savings')
								{
									currentItemArray['Aspects'][keyName] = [currentItemArray[keyName]];
								}
							}
							
							for (keyName in currentItemArray['Aspects'])
							{
								if (!rawAspects[keyName])
								{
									rawAspects[keyName] = currentItemArray['Aspects'][keyName];
								}
								else
								{
									rawAspects[keyName] = rawAspects[keyName].concat(currentItemArray['Aspects'][keyName]);
								}
								
								if (!aspectsCounter[keyName])
								{
									aspectsCounter[keyName] = 0;
								}

								aspectsCounter[keyName]++;
							}

							mstItems.push(currentItemArray);
						}
					}
				}
			}
			
			for (aspectName in rawAspects)
			{
				this.aspects[aspectName] = rawAspects[aspectName].uniq();
			}
			
			for (aspectName in aspectsCounter)
			{
				if (aspectsCounter[aspectName] >= numberOfItemsToRender)
				{
					this.aspectsInAllItems.push(aspectName); 
				}
			}
			
			if
			(
				mstItems.length
					&& mstFilterConnectionCollection[this.mstIdentifier]
			)
			{
				var thisObj = this,
					priceRangeSortOrder = [];
				
				this.priceRanges.each
				(
					function (priceRange)
					{
						priceRangeSortOrder.push(priceRange.filterText);
					}
				);
				
				mstFilterConnectionCollection[this.mstIdentifier].each
				(
					function (mstFilter)
					{
						mstFilter.acceptAspectsForItems(thisObj.aspects, priceRangeSortOrder, thisObj.aspectsInAllItems);
					}
				);
			}
			
			return (mstItems);
		},
		
		collectAspects: function ()
		{
			var priceRangeSortOrder = [];
		
			this.priceRanges.each
			(
				function (priceRange)
				{
					priceRangeSortOrder.push(priceRange.filterText);
				}
			);

			return ({ Aspects: Object.keys(this.aspects).length ? this.aspects : {}, priceRangesSortOrder: priceRangeSortOrder, aspectsInAllItems: this.aspectsInAllItems});
		},
		
		applyFilter: function (mstFilter, filterData, isCalledFromMasterBox)
		{
			var thisObj = this;
			
			this.filterData[mstFilter.mstFilterIdentifier] = 
			{
				isMasterFilter: isCalledFromMasterBox ? true : false,
				data: filterData
			};
			
			if (isCalledFromMasterBox)
			{
				// we need to clear all filters when called from master filter
				// before collecting possible filter values
				Object.keys(mstFilterCollection).each
				(
					function (currentMstFilterIdentifier)
					{
						if (!mstFilterCollection[currentMstFilterIdentifier].isMasterFilter)
						{
							mstFilterCollection[currentMstFilterIdentifier].clearAllFilter();
						}
					}
				);
			}

			var possibleFilterValues = this.collectPossibleFilterValues();
			
			Object.keys(mstFilterCollection).each
			(
				function (currentMstFilterIdentifier)
				{
					window.setTimeout
					(
						mstFilterCollection[currentMstFilterIdentifier].applyPossibleFilterValues.bind(mstFilterCollection[currentMstFilterIdentifier], possibleFilterValues, isCalledFromMasterBox, thisObj.filterData),
						0
					);
				}
			);

			if (!isCalledFromMasterBox)
			{
				this.filterItems();
				this.trackFilter();
			}
		},
		
		collectPossibleFilterValues: function()
		{
			var possibleFilterValues = {},
				thisObj = this;
			
			Object.keys(this.filterData).each
			(
				function (mstFilterIdentifier)
				{
					thisObj.filterData[mstFilterIdentifier].data.each
					(
						function (filter)
						{
							possibleFilterValues[filter.name] = thisObj.collectPossibleFilterValuesForAspectName(filter.name);
						}
					);
				}
			);
			
			return (possibleFilterValues);
		},
		
		collectPossibleFilterValuesForAspectName: function(aspectName)
		{
			var thisObj = this,
				possibleAspectValues = [];
			
			this.mstItemsContainer.select('.mst_item').each
			(
				function (mstItem)
				{
					if (thisObj.itemAspectsMatchesFilter(mstItem.mstItem, aspectName))
					{
						if (mstItem.mstItem.Aspects && mstItem.mstItem.Aspects[aspectName])
						{
							mstItem.mstItem.Aspects[aspectName].each
							(
								function (aspectValue)
								{
									possibleAspectValues.push(aspectValue);
								}
							);
						}
					}
				}
			);
			
			return (possibleAspectValues.uniq());
		},
		
		filterItems: function ()
		{
			var thisObj = this,
				visibleItems = [];

			this.mstItemsContainer.select('.mst_item').each
			(
				function (mstItem)
				{
					if
					(
						thisObj.itemAspectsMatchesFilter(mstItem.mstItem)
							&& (!thisObj.numberOfItems || visibleItems.length < thisObj.numberOfItems)
					)
					{
						visibleItems.push(mstItem);
						mstItem.show();
					}
					else
					{
						mstItem.hide();
					}
				}
			);
			
			if
			(
				!isPreview
					&& this.logVisibleItems
					&& visibleItems.length > 0
			)
			{
				this.pushVisibleItemsToLogger(visibleItems);
			}
		},
		
		itemAspectsMatchesFilter: function(mstItemData, excludeFilterName)
		{
			var thisObj = this,
				itemMatchesFilter = true,
				itemAspects = mstItemData.Aspects;
			
			Object.keys(this.filterData).each
			(
				function (mstFilterIdentifier)
				{
					thisObj.filterData[mstFilterIdentifier].data.each
					(
						function (filter)
						{
							if (!excludeFilterName || filter.name != excludeFilterName)
							{
								if (filter.value)
								{
									if (filter.name == 'Savings')
									{
										if
										(
											!mstItemData.Savings
												|| parseInt(mstItemData.Savings) < parseInt(filter.value.match(/(\d+)/)[1])
										)
										{
											itemMatchesFilter = false;
											throw $break;
										}
									}
									else
									{
										if
										(
											!mstItemData.Aspects
												|| !mstItemData.Aspects[filter.name]
												|| mstItemData.Aspects[filter.name].indexOf(filter.value) == -1
										)
										{
											itemMatchesFilter = false;
											throw $break;
										}
									}
								}
							}
						}
					);
					
					if (!itemMatchesFilter)
					{
						throw $break;
					}
				}
			);

			return (itemMatchesFilter);
		},
		
		pushVisibleItemsToLogger: function (mstItems)
		{
			var logItems = [], currentLogItem, i;
			
			for (i = 0; i < mstItems.length; i++)
			{
				if (mstItems[i].mstItem && mstItems[i].mstItem.ItemID)
				{
					currentLogItem = {'ItemID': mstItems[i].mstItem.ItemID};
					
					if (mstItems[i].mstItem.SellerID)
					{
						currentLogItem.SellerID = mstItems[i].mstItem.SellerID; 
					}
					logItems.push(currentLogItem);
				}
			}
			if (solutionId && logItems.length)
			{
				new Ajax.Request
				(
					'/itemLogger.php',
					{
						method: 'post',
						asynchronous: true,
						parameters: {'SolutionID': solutionId, 'views': Object.toJSON(logItems)}
					}
				);
			}
		},
		
		trackFilter: function()
		{
			if (roverPageId)
			{
				var thisObj = this,
					clkEvent = _rover.createClickEvent(roverPageId, roverSiteId);
					clkEvent.setLVTrk(true);
	
				Object.keys(this.filterData).each
				(
					function (mstFilterIdentifier)
					{
						thisObj.filterData[mstFilterIdentifier].data.each
						(
							function (filter)
							{
								if (filter.value)
								{
									clkEvent.getTrackData().addNvp(filter.name, filter.value);
								}
							}
						);
					}
				);
				
				clkEvent.track();
			}
		}
	}
);

var mstFilterCollection = {};
var mstFilterConnectionCollection = {};

var mstFilterContainerElement = Class.create
(
	{
		initialize: function (domNode, widgetId, aspectFilters, filterConnections, mstFilterIdentifier, sizeSelectorNames, hideInconsistentlyAspects)
		{
			if (mstFilterIdentifier)
			{
				mstFilterCollection[mstFilterIdentifier] = this;
			}

			var thisObj = this;
			
			this.priceRangeSortOrder = [];
			this.currentSortingAspectName = '';
			
			this.domNode = domNode;
			this.widgetId = widgetId;
			this.aspectFilters = aspectFilters;
			this.filterConnections = filterConnections;
			this.mstFilterIdentifier = mstFilterIdentifier;
			this.hideInconsistentlyAspects = hideInconsistentlyAspects;

			this.sizeSelectorNames = sizeSelectorNames ? sizeSelectorNames.split(',') : ['Size'];
			this.garmentNameSelectorName = 'GarmentName';
			
			this.filterConnections.each
			(
				function (filterConnection)
				{
					if (!mstFilterConnectionCollection[filterConnection])
					{
						mstFilterConnectionCollection[filterConnection] = [];
					}
					
					mstFilterConnectionCollection[filterConnection].push(thisObj);
				}
			);
			
			this.mstFilterContainer = domNode.select('.mst_filter_container')[0];
			this.mstFilterExtraContainer = domNode.select('.mst_filter_extra_container')[0];

			var filterSearch = this.domNode.select('.mst_filter_search')[0];
			if (filterSearch)
			{
				filterSearch.observe
				(
					'click',
					this.shareFilterDataWithItemBoxes.bind(this)
				);
			}

			if ($('mstFilterSelectorEntryDropDown' + thisObj.widgetId))
			{
				this.layoutType = 'dropdown';
			}
			else if ($('mstFilterSelectorEntryRadio' + thisObj.widgetId))
			{
				this.layoutType = 'radio';
			}
			
			this.preRenderAspectFilters();
		},
		
		preRenderAspectFilters: function ()
		{
			var thisObj = this;
			
			this.aspectFilters.each
			(
				function (aspectFilter, index)
				{
					var selector = thisObj.renderAspectFilter(aspectFilter, index < thisObj.aspectFilters.length - 1 ? false : true);
					selector.hide();
				}
			);
		},
		
		TABLE_ELEMENT_INNERHTML_BUGGY: function()
		{
			try
			{
				var el = document.createElement('table');
				if (el && el.tBodies)
				{
					el.innerHTML = '<tbody><tr><td>test</td></tr></tbody>';
					var isBuggy = typeof el.tBodies[0] == 'undefined';
					el = null;
					return isBuggy;
				}
			}
			catch (e)
			{
				return true;
			}
		},
		
		getFilterValues: function ()
		{
			var filterValues = [],
				filterValue;
			
			this.domNode.select('.mst_filter_selector').each
			(
				function (filterSelector)
				{
					filterValue = 
					{
						name: filterSelector.name,
						value: null
					};
					
					filterSelector.select('.mst_filter_selector_entry').each
					(
						function (filterSelectorEntry)
						{
							if (filterSelectorEntry['selected'] || filterSelectorEntry['checked'])
							{
								filterValue.value = filterSelectorEntry.value;
								
								throw $break;
							}
						}
					);
					
					filterValues.push(filterValue);
				}
			);

			this.mstFilterExtraContainer.select('.mst_extra_filter').each
			(
				function (mstExtraFilter)
				{
					filterValues.push
					(
						{
							name: mstExtraFilter.filterKey,
							value: mstExtraFilter.filterValue
						}
					);
				}
			);

			return (filterValues);
		},

		setFilter: function (filterKey, filterValue, filterLabel)
		{
			var thisObj = this,
				filterKeyFound = false,
				filterValueFound = false;
			
			this.domNode.select('.mst_filter_selector').each
			(
				function (filterSelector)
				{
					if (filterSelector.name == filterKey)
					{
						filterKeyFound = true;
						
						filterSelector.select('.mst_filter_selector_entry').each
						(
							function (filterSelectorEntry)
							{
								var filterSelectorValue = filterSelectorEntry.value;
								
								if (filterSelector.name == 'Savings' && filterSelectorValue)
								{
									filterSelectorValue = filterSelectorValue.match(/(\d+)/)[1];
								}
								
								if (filterValue == filterSelectorValue)
								{
									filterValueFound = true;
									
									if ($('mstFilterSelectorEntryDropDown' + thisObj.widgetId))
									{
										filterSelectorEntry.selected = true;
									}
									else if ($('mstFilterSelectorEntryRadio' + thisObj.widgetId))
									{
										if (!filterSelectorEntry.checked && filterSelectorEntry.up('.mst_filter_selector_entry_container').visible())
										{
											filterSelectorEntry.click();
										}
									}
									else
									{
										filterSelectorEntry.click();
									}
									
									throw $break;
								}
							}
						);
						
						throw $break;
					}
				}
			);
			
			if (!filterKeyFound)
			{
				var thisObj = this,
					selectorExtraFound = false;

				this.mstFilterExtraContainer.select('.mst_extra_filter').each
				(
					function (mstExtraFilter)
					{
						if (mstExtraFilter.filterKey == filterKey)
						{
							thisObj.modifyExtraFilter(mstExtraFilter, filterValue, filterLabel);
							
							selectorExtraFound = true;
							throw $break;
						}
					}
				);
				
				if (!selectorExtraFound)
				{
					this.attachExtraFilter(filterKey, filterValue, filterLabel);
				}
				
				this.domNode.select('.mst_filter_error')[0].update('');
			}
			
/* commented out becouse of hiding error message as requested. */
//		
//			else if (!filterValueFound)
//			{
//				this.domNode.select('.mst_filter_error')[0].update(mstFilterErrorInvalidValue + ': ' + '"' + (filterLabel ? filterLabel : filterKey) + ': ' + filterValue + '"');
//			}
			
			this.shareFilterDataWithItemBoxes();
		},

		attachExtraFilter: function (filterKey, filterValue, filterLabel)
		{
			if (filterValue != '')
			{
				var extraFilterTemplate = $('mstFilterExtra' + this.widgetId).cloneNode(true);
					extraFilterTemplate.id = '';
					extraFilterTemplate.filterKey = filterKey;
					extraFilterTemplate.filterValue = filterValue;
	
				var extraFilterKey = extraFilterTemplate.select('.mst_extra_filter_key')[0];
				extraFilterKey.update(filterKey);
				
				var extraFilterValue = extraFilterTemplate.select('.mst_extra_filter_value')[0];
				extraFilterValue.update(filterLabel ? filterLabel : filterValue);
				
				this.mstFilterExtraContainer.appendChild(extraFilterTemplate);
	
				var extraFilterClose = extraFilterTemplate.select('.mst_extra_filter_close')[0];
				extraFilterClose.observe
				(
					'click',
					this.removeExtraFilterElement.bind(this, extraFilterTemplate, false)
				);
			}
		},
		
		modifyExtraFilter: function (extraFilterElement, filterValue, filterLabel)
		{
			if (filterValue == '')
			{
				this.removeExtraFilterElement(extraFilterElement, true);
			}
			else
			{
				extraFilterElement.filterValue = filterValue;
				
				var extraFilterValue = extraFilterElement.select('.mst_extra_filter_value')[0];
				extraFilterValue.update(filterLabel ? filterLabel : filterValue);
			}
		},
		
		removeExtraFilterElement: function (extraFilterElement, preventRunningFilter)
		{
			extraFilterElement.remove();

			if (!preventRunningFilter)
			{
				this.shareFilterDataWithItemBoxes();
			}
		},
		
		clearAllFilter: function (preventSharingFilter)
		{
			var thisObj = this;
			
			this.domNode.select('.mst_filter_selector').each
			(
				function (filterSelector)
				{
					filterSelector.select('.mst_filter_selector_entry').each
					(
						function (filterSelectorEntry)
						{
							if (thisObj.layoutType == 'dropdown')
							{
								if (filterSelectorEntry.value == '')
								{
									filterSelectorEntry.selected = true;
									throw $break;
								}
							}
							else if (thisObj.layoutType == 'radio')
							{
								if (filterSelectorEntry.checked)
								{
									thisObj.activateSelector(filterSelectorEntry, filterSelector, true)
									throw $break;
								}
							}
						}
					);
				}
			);
			
			this.mstFilterExtraContainer.select('.mst_extra_filter').each
			(
				function (mstExtraFilter)
				{
					thisObj.removeExtraFilterElement(mstExtraFilter);
				}
			);

			this.domNode.select('.mst_filter_error')[0].update('');
			
			if (!preventSharingFilter)
			{
				this.shareFilterDataWithItemBoxes();
			}
		},
		
		shareFilterDataWithItemBoxes: function ()
		{
			var thisObj = this,
				filterValues = this.getFilterValues();
			
			this.filterConnections.each
			(
				function (filterConnection)
				{
					if (mstItemListCollection[filterConnection])
					{
						mstItemListCollection[filterConnection].applyFilter(thisObj, filterValues, false);
					}
				}
			);
		},
		
		collectAspects: function ()
		{
			var aspects,
				thisObj = this;
			
			this.filterConnections.each
			(
				function (filterConnection)
				{
					if
					(
						mstItemListCollection[filterConnection]
							&& (aspectsObject = mstItemListCollection[filterConnection].collectAspects())
					)
					{
						thisObj.acceptAspectsForItems(aspectsObject.Aspects, aspectsObject.priceRangesSortOrder, aspectsObject.aspectsInAllItems);
					}
				}
			);
		},
		
		acceptAspectsForItems: function (aspectsForItems, priceRangesSortOrder, aspectsAvailableInAllItems)
		{
			var thisObj = this;
			
			this.priceRangeSortOrder = priceRangesSortOrder;
			
			this.acceptAspects(aspectsForItems, aspectsAvailableInAllItems);
			
			this.sortSelectorEntries();
		},
		
		sortSelectorEntries: function()
		{
			var thisObj = this;
			
			if ($('mstFilterSelectorEntryDropDown' + this.widgetId))
			{
				this.domNode.select('.mst_filter_selector').each
				(
					function (selector)
					{
						thisObj.currentSortingAspectName = selector.name;
						
						var selectorEntries = selector.select('.mst_filter_selector_entry');
						selectorEntries.sort(thisObj.customSelectorEntriesSorter.bind(thisObj));
						
						// this.TABLE_ELEMENT_INNERHTML_BUGGY() ? currentAspectFilterSelector.update('') : (currentAspectFilterSelector.innerHTML = '');
						selector.update('');
						selectorEntries.each
						(
							function (selectorEntry)
							{
								selector.appendChild(selectorEntry);
							}
						);
					}
				);
			}
			else if ($('mstFilterSelectorEntryRadio' + this.widgetId))
			{
				this.domNode.select('.mst_filter_selector').each
				(
					function (selector)
					{
						thisObj.currentSortingAspectName = selector.name;
						
						var selectorContainers = selector.select('.mst_filter_selector_entry_container');
						selectorContainers.sort(thisObj.customSelectorEntriesSorter.bind(thisObj));

						var dummy = document.createElement('div');
						selectorContainers.each
						(
							function (selectorContainer)
							{
								dummy.appendChild(selectorContainer);
							}
						);

						selector.update(dummy);
					}
				);
			}
		},
		
		acceptAspects: function (aspects, aspectsAvailableInAllItems)
		{
			var thisObj = this;
			
			this.aspectFilters.each
			(
				function (aspectFilter)
				{
					var showAspect = true;
					
					if (thisObj.hideInconsistentlyAspects)
					{
						if (aspectsAvailableInAllItems.indexOf(aspectFilter.key) == -1)
						{
							showAspect = false;
						}
					}
						
					if (showAspect)
					{
						if (aspectFilter.key == 'Savings' && aspectFilter.additionalValues)
						{
							aspectFilter.additionalValues.each
							(
								function (additionalValue)
								{
									thisObj.attachAspectToFilterElement(aspectFilter, additionalValue);
								}
							);
						}
						else if
						(
							aspects[aspectFilter.key]
								&& aspects[aspectFilter.key].length
						)
						{
							aspects[aspectFilter.key].each
							(
								function (aspect)
								{
									thisObj.attachAspectToFilterElement(aspectFilter, aspect);
								}
							)
						}
					}
				}
			);
		},
		
		attachAspectToFilterElement: function (aspectFilter, value)
		{
			var currentAspectFilter = null;
			
			this.mstFilterContainer.select('.mst_filter').each
			(
				function (mstFilter)
				{
					if (mstFilter.filterKey == aspectFilter.key)
					{
						currentAspectFilter = mstFilter;
						throw $break;
					}
				}
			);
			
			if (!currentAspectFilter)
			{
				currentAspectFilter = this.renderAspectFilter(aspectFilter);
			}
			
			//deactivated by mico to avoid flickering when showing Size only if GarmentName is selected  
			//currentAspectFilter.show();
			
			var selectorEntryFound = false;

			currentAspectFilter.select('.mst_filter_selector_entry').each
			(
				function (mstFilterSelectorEntry)
				{
					if (mstFilterSelectorEntry.value == value)
					{
						selectorEntryFound = true;
						throw $break;
					}
				}
			);
			
			if (!selectorEntryFound)
			{
				if ($('mstFilterSelectorEntryDropDown' + this.widgetId))
				{
					var selectorEntryDropDown = $('mstFilterSelectorEntryDropDown' + this.widgetId).cloneNode(true);
						selectorEntryDropDown.id = '';
						selectorEntryDropDown.value = value;
						
					selectorEntryDropDown.update(value);
					
					var currentAspectFilterSelector = currentAspectFilter.select('.mst_filter_selector')[0];
					currentAspectFilterSelector.appendChild(selectorEntryDropDown);
				}
				else if ($('mstFilterSelectorEntryRadio' + this.widgetId))
				{
//					var selectorEntryRadio = $('mstFilterSelectorEntryRadio' + this.widgetId).cloneNode(true);
//						selectorEntryRadio.id = '';
//						selectorEntryRadio.value = value;
//						
//					var selectorEntry = selectorEntryRadio.select('input')[0];
//						selectorEntry.name = aspectFilter.key;
//						selectorEntry.value = value;
//						selectorEntry.id = 'radio_' + Math.round(Math.random() * 10000000);
//					
//					var selectorEntryLabel = selectorEntryRadio.select('label')[0];
//						selectorEntryLabel.htmlFor = selectorEntry.id;
//						selectorEntryLabel.update(value);
					
					var newId = Math.round(Math.random() * 10000000);

					var currentAspectFilterSelector = currentAspectFilter.select('.mst_filter_selector')[0];
						currentAspectFilterSelector.insert
						(
							{
								bottom: '<div class="mst_filter_selector_entry_container mst_filter_leftbox"><input id="' + 'radio_' + newId + '" type="radio" value="' + value.escapeHTML() + '" name="' + aspectFilter.key.escapeHTML() + '" class="mst_filter_selector_entry mst_filterbox_radio"><label for="' + 'radio_' + newId + '" class="mst_filter_leftfilter_label">' + value.escapeHTML() + '</label></div>' 
							}
						);
					
					var selectorEntryRadio = $('radio_' + newId).up('div');
						selectorEntryRadio.value = value;
					
					var selectorEntry = selectorEntryRadio.select('input')[0];
						selectorEntry.value = value;
					
					selectorEntry.observe
					(
						'click',
						this.activateSelector.bind(this, selectorEntry, currentAspectFilterSelector, false)
					);
				}
			}
		},
		
		renderAspectFilter: function (aspectFilter)
		{
			var aspectFilterTemplate = $('mstFilterTemplate' + this.widgetId).cloneNode(true);
				aspectFilterTemplate.id = '';
				aspectFilterTemplate.filterKey = aspectFilter.key;
				
			var label = aspectFilterTemplate.select('.mst_filter_label')[0];
				label.update(aspectFilter.label.toUpperCase());
				
			var selector = aspectFilterTemplate.select('.mst_filter_selector')[0];
				selector.name = aspectFilter.key;
				
			this.mstFilterContainer.appendChild(aspectFilterTemplate);
			
			if ($('mstFilterSelectorEntryDropDown' + this.widgetId))
			{
				var selectorEntryDropDown = $('mstFilterSelectorEntryDropDown' + this.widgetId).cloneNode(true);
					selectorEntryDropDown.id = '';
					selectorEntryDropDown.value = '';
					selectorEntryDropDown.selected = true;
	
				selectorEntryDropDown.update(mstFilterSearchAll);
				selector.appendChild(selectorEntryDropDown);

				selector.observe
				(
					'change',
					this.shareFilterDataWithItemBoxes.bind(this)
				);
			}
			else if ($('mstFilterSelectorEntryRadio' + this.widgetId))
			{
				/* removed ALL radio button for now

				var selectorEntryRadio = $('mstFilterSelectorEntryRadio' + this.widgetId).cloneNode(true);
					selectorEntryRadio.id = '';
					selectorEntryRadio.value = '';
					
				var selectorEntry = selectorEntryRadio.select('input')[0];
					selectorEntry.name = aspectFilter.key;
					selectorEntry.value = '';
					selectorEntry.checked = true;
					selectorEntry.id = 'radio_' + Math.round(Math.random() * 10000000);
				
				var selectorEntryLabel = selectorEntryRadio.select('label')[0];
					selectorEntryLabel.htmlFor = selectorEntry.id;
					selectorEntryLabel.update(mstFilterSearchAll);

				selector.appendChild(selectorEntryRadio);

				selectorEntryRadio.observe
				(
					'click',
					this.shareFilterDataWithItemBoxes.bind(this)
				);
				
				*/
			}

			return (aspectFilterTemplate);
		},
		
		customSelectorEntriesSorter: function (selectorEntry1, selectorEntry2)
		{
			if (this.currentSortingAspectName == 'PriceRange')
			{
				if (selectorEntry1.value == '')
				{
					return (-1);
				}
				else if (selectorEntry2.value == '')
				{
					return (1);
				}
				else
				{
					return (this.priceRangeSortOrder.indexOf(selectorEntry1.value) > this.priceRangeSortOrder.indexOf(selectorEntry2.value) ? 1 : -1);
				}
			}
			else
			{
				return (selectorEntry1.value > selectorEntry2.value ? 1 : -1);
			}
		},

		activateSelector: function (selectorEntry, selector, preventSharingFilter)
		{
			if (this.layoutType == 'radio')
			{
				selector.select('.mst_filter_selector_entry').each
				(
					function (currentSelectorEntry)
					{
						if (selectorEntry.value == currentSelectorEntry.value)
						{
							if (currentSelectorEntry.up('.mst_filter_selector_entry_container').hasClassName('highlight'))
							{
								currentSelectorEntry.checked = false;
								currentSelectorEntry.up('.mst_filter_selector_entry_container').removeClassName('highlight');
							}
							else
							{
								currentSelectorEntry.up('.mst_filter_selector_entry_container').addClassName('highlight');
							}
						}
						else
						{
							currentSelectorEntry.up('.mst_filter_selector_entry_container').removeClassName('highlight');
						}
					}
				);
			}
			
			if (!preventSharingFilter)
			{
				this.shareFilterDataWithItemBoxes();
			}
		},

		applyPossibleFilterValues: function(possibleFilterValues, isCalledFromMasterBox, filterData)
		{
			var thisObj = this,
				filterSelectorEntryContainer,
				filterSelectorEntries;
			
			if (!isCalledFromMasterBox)
			{
				this.domNode.select('.mst_filter_selector').each
				(
					function (filterSelector)
					{
						if (possibleFilterValues[filterSelector.name])
						{
							if (possibleFilterValues[filterSelector.name].length > 0)
							{
								filterSelectorEntries = filterSelector.select('.mst_filter_selector_entry');
								
								if (filterSelectorEntries.length > 0)
								{
									filterSelectorEntries.each
									(
										function (filterSelectorEntry)
										{
											filterSelectorEntryContainer = filterSelectorEntry.up('.mst_filter_selector_entry_container');
											
											if (filterSelectorEntry.value == '' || possibleFilterValues[filterSelector.name].indexOf(filterSelectorEntry.value) != -1)
											{
												filterSelectorEntryContainer ? filterSelectorEntryContainer.show() : filterSelectorEntry.show();
											}
											else
											{
												filterSelectorEntryContainer ? filterSelectorEntryContainer.hide() : filterSelectorEntry.hide();
											}
										}
									);
									
									filterSelector.up('.mst_filter').show();
								}
								else
								{
									filterSelector.up('.mst_filter').hide();
								}
							}
							else
							{
								filterSelector.up('.mst_filter').hide();
							}
						}
						else
						{
							filterSelector.up('.mst_filter').show();
						}
					}
				);

				this.mstFilterExtraContainer.select('.mst_extra_filter').each
				(
					function (mstExtraFilter)
					{
						if (!possibleFilterValues[mstExtraFilter.filterKey] || possibleFilterValues[mstExtraFilter.filterKey].indexOf(mstExtraFilter.filterValue) == -1)
						{
							thisObj.removeExtraFilterElement(mstExtraFilter);
						}
					}
				);
			}

			this.domNode.select('.mst_filter_selector').each
			(
				function (filterSelector)
				{
					if (thisObj.sizeSelectorNames.indexOf(filterSelector.name) != -1)
					{
						Object.keys(filterData).each
						(
							function (filterName)
							{
								filterData[filterName]['data'].each
								(
									function (filterEntry)
									{
										if (filterEntry.name == thisObj.garmentNameSelectorName)
										{
											if
											(
												filterEntry.value
													&& possibleFilterValues[filterSelector.name]
													&& possibleFilterValues[filterSelector.name].length > 0
											)
											{
												filterSelector.up('.mst_filter').show();
											}
											else
											{
												filterSelector.up('.mst_filter').hide();
											}
										}
									}
								);
							}
						);
					}
				}
			);
		}
	}
);

var mstMasterFilterContainerElement = Class.create
(
	mstFilterContainerElement,
	{
		initialize: function ($super, domNode, widgetId, aspectFilters, filterConnections, mstFilterIdentifier, sizeSelectorNames)
		{
			this.isMasterFilter = true;

			$super(domNode, widgetId, aspectFilters, filterConnections, mstFilterIdentifier, sizeSelectorNames);
		},
		
		sortSelectorEntries: function()
		{
			var thisObj = this;

			this.domNode.select('.mst_filter_selector').each
			(
				function (selector)
				{
					var selectorEntries = selector.select('.mst_filter_selector_entry');
					selectorEntries.sort(thisObj.customSelectorEntriesSorter.bind(thisObj));

					var dummy = document.createElement('div');
					selectorEntries.each
					(
						function (selectorEntry)
						{
							dummy.appendChild(selectorEntry);
						}
					);

					selector.update(dummy);
				}
			);
		},

		attachAspectToFilterElement: function (aspectFilter, value)
		{
			var currentAspectFilter = null;
			
			this.mstFilterContainer.select('.mst_filter').each
			(
				function (mstFilter)
				{
					if (mstFilter.filterKey == aspectFilter.key)
					{
						currentAspectFilter = mstFilter;
						throw $break;
					}
				}
			);
			
			if (!currentAspectFilter)
			{
				currentAspectFilter = this.renderAspectFilter(aspectFilter);
			}
			
			currentAspectFilter.show();
			
			var selectorEntryFound = false;

			currentAspectFilter.select('.mst_filter_selector_entry').each
			(
				function (mstFilterSelectorEntry)
				{
					if (mstFilterSelectorEntry.value == value)
					{
						selectorEntryFound = true;
						throw $break;
					}
				}
			);
			
			if (!selectorEntryFound)
			{
				var selectorEntry = $('mstFilterSelectorEntryDiv' + this.widgetId).cloneNode(true);
					selectorEntry.id = '';
					selectorEntry.value = value;
				
				selectorEntry.update(value.escapeHTML());
				
				var currentAspectFilterSelector = currentAspectFilter.select('.mst_filter_selector')[0];
				currentAspectFilterSelector.appendChild(selectorEntry);

				selectorEntry.observe
				(
					'click',
					this.activateSelector.bind(this, selectorEntry, currentAspectFilterSelector, false)
				);
			}
		},
		
		renderAspectFilter: function (aspectFilter, isLast)
		{
			var aspectFilterTemplate = $('mstMasterFilterTemplate' + this.widgetId).cloneNode(true);
				aspectFilterTemplate.id = '';
				aspectFilterTemplate.filterKey = aspectFilter.key;
				
			if (isLast)
			{
				aspectFilterTemplate.addClassName('mst_master_filter_last');
			}
					
			var label = aspectFilterTemplate.select('.mst_filter_label')[0];
				label.update(aspectFilter.label.toUpperCase());
				
			var selector = aspectFilterTemplate.select('.mst_filter_selector')[0];
				selector.name = aspectFilter.key;
				
			this.mstFilterContainer.appendChild(aspectFilterTemplate);
			
			var selectorEntry = $('mstFilterSelectorEntryDiv' + this.widgetId).cloneNode(true);
				selectorEntry.id = '';
				selectorEntry.value = '';
				selectorEntry.selected = true;
				selectorEntry.checked = true;

			selectorEntry.update(mstFilterSearchAll);
			selector.appendChild(selectorEntry);

			selectorEntry.observe
			(
				'click',
				this.activateSelector.bind(this, selectorEntry, selector, false)
			);

			return (aspectFilterTemplate);
		},
		
		activateSelector: function (selectorEntry, selector, preventSharingFilter)
		{
			selector.select('.mst_filter_selector_entry').each
			(
				function (currentSelectorEntry)
				{
					if (selectorEntry.value == currentSelectorEntry.value)
					{
						currentSelectorEntry.selected = true;
						currentSelectorEntry.checked = true;
						
						currentSelectorEntry.addClassName('highlight');
					}
					else
					{
						currentSelectorEntry.selected = false;
						currentSelectorEntry.checked = false;

						currentSelectorEntry.removeClassName('highlight');
					}
				}
			);

			if (!preventSharingFilter)
			{
				this.shareFilterDataWithItemBoxes();
			}
		},

		clearAllFilter: function ()
		{
			var thisObj = this;
			
			this.domNode.select('.mst_filter_selector').each
			(
				function (filterSelector)
				{
					filterSelector.select('.mst_filter_selector_entry').each
					(
						function (filterSelectorEntry)
						{
							if (filterSelectorEntry.checked || filterSelectorEntry.selected)
							{
								filterSelectorEntry.checked = false;
								filterSelectorEntry.selected = false;
								filterSelectorEntry.removeClassName('highlight');
								throw $break;
							}
						}
					);
				}
			);
			
			this.mstFilterExtraContainer.select('.mst_extra_filter').each
			(
				function (mstExtraFilter)
				{
					thisObj.removeExtraFilterElement(mstExtraFilter);
				}
			);

			this.domNode.select('.mst_filter_error')[0].update('');
			
			this.shareFilterDataWithItemBoxes();
		},

		shareFilterDataWithItemBoxes: function ()
		{
			var thisObj = this,
				filterValues = this.getFilterValues();
			
			this.filterConnections.each
			(
				function (filterConnection)
				{
					if (mstItemListCollection[filterConnection])
					{
						mstItemListCollection[filterConnection].applyFilter(thisObj, filterValues, true);
					}
				}
			);
		},

		applyPossibleFilterValues: function(possibleFilterValues, isCalledFromMasterBox, filterData)
		{
			var thisObj = this;

			if (isCalledFromMasterBox)
			{
				this.mstFilterExtraContainer.select('.mst_extra_filter').each
				(
					function (mstExtraFilter)
					{
						if (!possibleFilterValues[mstExtraFilter.filterKey] || possibleFilterValues[mstExtraFilter.filterKey].indexOf(mstExtraFilter.filterValue) == -1)
						{
							thisObj.removeExtraFilterElement(mstExtraFilter);
						}
					}
				);
			}
		}
	}
);

var addCustomFilter = function (mstFilterIdentifier, filterKey, filterValue, filterLabel)
{
	if (mstFilterCollection[mstFilterIdentifier])
	{
		mstFilterCollection[mstFilterIdentifier].setFilter(filterKey, filterValue, filterLabel);
	}
};

var clearAllFilter = function (mstFilterIdentifier)
{
	if (mstFilterCollection[mstFilterIdentifier])
	{
		mstFilterCollection[mstFilterIdentifier].clearAllFilter();
	}
};

var parseIsoTimeSpan = function (timeSpan, returnType, timeSpanUnitNames)
{
	if (!timeSpan)
	{
		return (0);
	}

	// var regexp_IsoTimeSpan = /(-)?P([0-9]+(?=Y))?([0-9]+(?=M))?([0-9]+(?=D))?T?([0-9]+(?=H))?([0-9]+(?=M))?([0-9]+(?=S))?/;
	var regexp_IsoTimeSpan = /(-)?P([0-9]+Y)?([0-9]+M)?([0-9]+D)?T?([0-9]+H)?([0-9]+M)?([0-9]+S)?/;
	var timeSpanArray = regexp_IsoTimeSpan.exec(timeSpan ? timeSpan : 'PT0S');

	for (var i = 1; i <= 7; i++)
	{
		if (timeSpanArray[i])
		{
			timeSpanArray[i] = timeSpanArray[i].substr(0, timeSpanArray[i].length - 1);
		}
		else
		{
			timeSpanArray[i] = '0';
		}
	}
	
	switch (returnType)
	{
		case 'string':
		
			var timeSpanString = '';
			
			if (timeSpanArray[4] > 0)
				timeSpanString += timeSpanArray[4] + timeSpanUnitNames[0] + ' ';
			if (timeSpanArray[4] > 0 || timeSpanArray[5] > 0)
				timeSpanString += timeSpanArray[5] + timeSpanUnitNames[1] + ' ';
			if (timeSpanArray[4] > 0 || timeSpanArray[5] > 0 || timeSpanArray[6] > 0)
				timeSpanString += timeSpanArray[6] + timeSpanUnitNames[2] + ' ';
			if (timeSpanArray[4] == 0 && timeSpanArray[5] == 0 /*&& timeSpanArray[6] == 0 && timeSpanArray[7] > 0*/)
				timeSpanString += timeSpanArray[7] + timeSpanUnitNames[3];
				
			return (timeSpanString);
			break;
			
		default:
	
			return (timeSpanArray);
			break;
	}
};
