if(typeof DRAG == 'undefined') { DRAG = {}; }

DRAG.DEF = {}; // holds pseudo constants

DRAG.CatalogBrowser = {
	params: null,
	serviceURL: null,
	responseType: null,
	encodedParams: null, // string of current selected filters with url encoding
	applicationName: null,

	init: function() {
		this.params = DRAG.DEF.browseParams;
		this.applicationName = "dragspecialties";
		
		// decode selectedValues
		if(typeof this.params.selectedValues == 'object') {
			var len = this.params.selectedValues.length;
			for(var i=0; i<len; i++) {
				this.params.selectedValues[i] = decodeURIComponent(this.params.selectedValues[i]);
			}
		}
		
		// gather selected filters string
		this.encodedParams = this.getEncodedParams();
		
		// add parameters to extra link sets
		this.addFiltersToLinks();
		
		if(this.params.firstComCode != null && this.params.firstComCode != "") {
			this.params.comCode = this.params.firstComCode;
		}
		if(this.params.firstSubComCode != null && this.params.firstSubComCode != "") {
			this.params.subComCode = this.params.firstSubComCode;
		}
		
		this.delegate();	
		this.request();
	},
	
	addFiltersToLinks: function() {
		if(this.encodedParams == '')
			return false;
		
		var productLinks = $('.productRow .product a');
		var paginationLinks = $('.itemsPerPage span a');
		var i = 0;
		
		// catalog browsing product detail links
		if(productLinks.length > 0) {
			var productLen = productLinks.length;
			for(i=0; i<productLen; i++) {
				var productDetailURL = $(productLinks[i]).attr('href').toString() + this.encodedParams;
				$(productLinks[i]).attr('href', productDetailURL);
			}
		}
		
		// pagination links
		if(paginationLinks.length > 0) {
			var paginationLen = paginationLinks.length;
			for(i=0; i<paginationLen; i++) {
				var paginationURL = $(paginationLinks[i]).attr('href').toString() + this.encodedParams;
				$(paginationLinks[i]).attr('href', paginationURL);
			}
		}
	},
	
	build: function(json) {
		var container, filters = null;
		switch(this.responseType) {
			case 'segments':
				// this case should never exist.
				// remove?
				break;
			case 'comCodes':
				container = this.buildStructure({
					title: json.parents.segment.description,
					results: json.results
				});
				break;
			case 'subComCodes':
				container = this.buildStructure({
					title: json.parents.segment.description,
					subTitle: json.parents.comCode.alias,
					results: json.results
				});
				break;
							
			case 'attributeValuePairs':
				container = this.buildFilterStructure({
					title: json.availableAttributeValues.parents.segment.description,
					subTitle: json.availableAttributeValues.parents.comCode.alias,
					category: json.availableAttributeValues.parents.subComCode.alias,
					results: json.selectedValues.results
				});
				
				filters = this.buildFilters({
					results: json.availableAttributeValues.results
				});
				break;
			default:
				break;
		}
		
		// attach contents to document
		if(container) {
			$('#browseMenu .mid .loading').remove();
			var content = $(container).html();
			if(content != "") {
				$('#browseMenu .mid').append(container);
			}
		}
		if(filters) {
			$('#browseMenu .mid').append(filters);
		}
	},
	
	buildFilters: function(options) {
		var container = document.createElement("div");
		container.className = 'rowFade filterPad';
		
		var wrapper = document.createElement('div');
		wrapper.id = 'filters';
		/*wrapper.innerHTML = '<h3>Filters</h3>';*/
		
		var ul = document.createElement("ul");
		ul.id = "attributes";
		
		if(options.results && options.results.length > 0) {
			var len = options.results.length;
			for(var i=0; i<len; i++) {
				// compile url
				var url = "browseProduct.do";
				if(this.params.productId) {
					url = 'getProductDetails.do';
				}
				url += '?application=' + this.applicationName;
				url += '&regions=6';
				url += '&segmentId=' + this.params.segment;
				url += '&comCodeId=' + this.params.comCode;
				url += '&subComCodeId=' + this.params.subComCode;
				url += '&productId=' + this.params.productId;
				
				// add selectedValues to url
				var paramLen = this.params.selectedValues.length;
				for(var n=0; n<paramLen; n++) {
					url += '&selectedValues[]=' + encodeURIComponent(this.params.selectedValues[n]);
				}
				
				// create attribute value pairs
				var avps = document.createElement('ul');
				var attributeLen = options.results[i].attributeValuePairs.length;
				for(var inc=0; inc<attributeLen; inc++) {
					var li = document.createElement("li");
					if(inc == attributeLen - 1) {
						li.className = "last";
					}
					var a = document.createElement('a');

					var href = url + '&selectedValues[]=' + encodeURIComponent(options.results[i].attributeId +
						',' + options.results[i].attributeName +
						',' + options.results[i].attributeValuePairs[inc].attributeValueId +
						',' + options.results[i].attributeValuePairs[inc].attributeValue);
					$(a).attr('href', href);
					$(a).html(options.results[i].attributeValuePairs[inc].attributeValue);
					$(li).append(a);
					$(avps).append(li);
				}
				
				// create attributes
				var li = document.createElement("li");
				if(i == len - 1) {
					li.className = "last";
				}
				var a = document.createElement('a');
				$(a).attr('href', url);
				$(a).html(options.results[i].attributeName.toLowerCase());
				$(li).append(a);
				$(li).append(avps);
				$(ul).append(li);
				
				// show or hide attribute values when attributes are clicked
				$(a).bind('click', function(e) {
					e.preventDefault();
					$(this).toggleClass('selected');
					$(this).next('ul').toggle();
				});
			}
			wrapper.appendChild(ul);
		} else {
			// no filters were present
			var p = document.createElement('p');
			if(this.params.selectedValues.length > 0) {
				p.innerHTML = 'Based on your previous selections, there are no more available filters.';
			} else {
				p.innerHTML = 'Sorry, but there are no available filters for this category.';
			}
			wrapper.appendChild(p);
		}
		container.appendChild(wrapper);
		return container;
	},
	
	buildFilterStructure: function(options) {
		var titleContainer = $('#browseMenu');
		var container = document.createElement("div");
		container.className = 'wrapper';
		
		var ul = document.createElement("ul");
		ul.id = "selectedFilters";
		
		var title = document.createElement("div");
		$(title).html(options.title);
		$(title).attr('class', 'title');
		$(title).html("<a href='" + "browseProduct.do?application=" + this.applicationName + "&regions=6&segmentId=" + this.params.segment + "'>" + options.title + "</a> &gt;");
			
		var subTitle = document.createElement('div');
		$(subTitle).html(options.subTitle);
		$(subTitle).attr('class', 'title');
		$(subTitle).html("<a href='" + "browseProduct.do?application=" + this.applicationName + "&regions=6&segmentId=" + this.params.segment + "&comCodeId=" + this.params.comCode + "'>" + options.subTitle + "</a> &gt;");

		// add selectedValues to url
		var paramLen = this.params.selectedValues.length;
		var selectedParams = '';
		for(var n=0; n<paramLen; n++) {
			selectedParams += '&selectedValues[]=' + encodeURIComponent(this.params.selectedValues[n].replace('&#034;','"'));
		}

		var category = document.createElement('div');
		$(category).html(options.category);
		$(category).attr('class', 'activeTitle');
		$(category).html(options.category);

		if (this.params.productId) {
			$(category).html("<a href='" + "browseProduct.do?application=" + this.applicationName + "&itemOffset=" + this.params.itemOffset + "&pageSize=" + this.params.pageSize + "&regions=6&segmentId=" + this.params.segment + "&comCodeId=" + this.params.comCode + "&subComCodeId=" + this.params.subComCode + selectedParams + "'>" + options.category + "</a> &gt;");
			$(category).attr('class', 'title');
		}
		
		// stuff listing with selected values
		if(options.results && options.results.length > 0) {
			var len = options.results.length;
			for(var i=0; i<len; i++) {
				
				options.results[i] = options.results[i].replace('&#034;','"'); // unencode the double quote character 

				var url = window.location.href.replace('&selectedValues[]=' + options.results[i], '');
				
				url = url.replace('&selectedValues[]=' + encodeURIComponent(options.results[i]), '');
				
				var li = document.createElement("li");
				if(i == len -1) {
					li.className = "last";
				}
				var p = document.createElement('p');
				var a = document.createElement('a');
				$(a).attr('href', url);
				$(a).html('&nbsp;');
				$(p).append('<span>' + options.results[i].split(',')[1].toLowerCase() + ':</span> ' + options.results[i].split(',')[3]);
				$(li).append(a);
				$(li).append(p);
				$(ul).append(li);
			}
			
		}
		else {
			$(container).attr('style', 'display:none');
		}
		
		$(titleContainer).prepend(ul);
		this.injectProductName(titleContainer);
		$(titleContainer).prepend(category);
		$(titleContainer).prepend(subTitle);
		$(titleContainer).prepend(title);
		
		return container;
	},
	
	buildStructure: function(options) {
		var titleContainer = $('#browseMenu');
		var container = document.createElement("div");
		container.className = 'wrapper';
		
		var title = document.createElement("div");
		$(title).html(options.title);
		$(title).attr('class', 'activeTitle');

		if (this.params.productId) {
			$(title).html("<a href='" + "browseProduct.do?application=" + this.applicationName + "&regions=6&segmentId=" + this.params.segment + "'>" + options.title + "</a> &gt;");
			$(title).attr('class', 'title');
		}
		
		if(options.subTitle) {
			$(title).html("<a href='" + "browseProduct.do?application=" + this.applicationName + "&regions=6&segmentId=" + this.params.segment + "'>" + options.title + "</a> &gt;");
			$(title).attr('class', 'title');
			var subTitle = document.createElement('div');
			$(subTitle).html(options.subTitle);
			$(subTitle).attr('class', 'activeTitle');
			
			if (this.params.productId) {
				$(subTitle).html("<a href='" + "browseProduct.do?application=" + this.applicationName + "&regions=6&segmentId=" + this.params.segment + "&comCodeId=" + this.params.comCode + "'>" + options.subTitle + "</a> &gt;");
				$(subTitle).attr('class', 'title');
			}
		}
		
		if(options.category) {
			$(subTitle).html("<a href='" + "browseProduct.do?application=" + this.applicationName + "&regions=6&segmentId=" + this.params.segment + "&comCodeId=" + this.params.comCode + "'>" + options.subTitle + "</a> &gt;");
			$(subTitle).attr('class', 'title');
			var category = document.createElement('div');
			$(category).html(options.category);
			$(category).attr('class', 'activeTitle');

			if (this.params.productId) {
				$(category).html("<a href='" + "browseProduct.do?application=" + this.applicationName + "&itemOffset=" + this.params.itemOffset + "&pageSize=" + this.params.pageSize + "&regions=6&segmentId=" + this.params.segment + "&comCodeId=" + this.params.comCode + "&subComCodeId=" + this.params.subComCode + selectedParams + "'>" + options.category + "</a> &gt;");
				$(category).attr('class', 'title');
			}
		}
		
		var ul = document.createElement("ul");
		ul.id = "classifications";
		
		// stuff listing
		var len = options.results.length;
		for(var i=0; i<len; i++) {
			var url = "browseProduct.do?application=" + this.applicationName + "&regions=6&segmentId=" + this.params.segment;
			var li = document.createElement("li");
			if(i == len -1) {
				li.className = "last";
			}
			if(title) {
				url += '&comCodeId=' + options.results[i].comCodeId;
			}
			if (subTitle) {
				url += '&subComCodeId=' + options.results[i].subComCodeId;
			}
			var a = document.createElement('a');
			$(a).attr('href', url);
			$(a).html(options.results[i].alias);
			$(li).append(a);
			$(ul).append(li);
		}
		
		this.injectProductName(titleContainer);
		if(category) { $(titleContainer).prepend(category); }
		if(subTitle) { $(titleContainer).prepend(subTitle); }
		$(titleContainer).prepend(title);
		
		if (!this.params.productId) {
			$(container).append(ul);
		}
		return container;
	},
	
	delegate: function() {
		if (this.params.segment && this.params.comCode && this.params.subComCode || (this.params.firstComCode != null && this.params.firstComCode != "") || (this.params.firstSubComCode != null && this.params.firstSubComCode != "")) {
			this.serviceURL = 'product-browse/attribute/getAttributes.do';
			this.responseType = 'attributeValuePairs';
		} else if(this.params.segment && this.params.comCode) {
			this.serviceURL = 'product-browse/subcomcode/getSubComCodes.do';
			this.responseType = 'subComCodes';
		} else if(this.params.segment) {
			this.serviceURL = 'product-browse/comcode/getComCodes.do';
			this.responseType = 'comCodes';
		} else {
			this.serviceURL = 'product-browse/segment/getSegments.do';
			this.responseType = 'segments';
		}
	},
	
	getEncodedParams: function() {
		var links = this.params.selectedValues;
		var len = links.length;
		var params = "";
		for(var i=0; i<len; i++) {
			params += '&selectedValues[]=' + encodeURIComponent(links[i].replace('&#034;','"'));
		}
		return params;
	},
	
	injectProductName: function(c) {
		if (this.params.productId) {
			var productName = document.createElement('div');
			var pn = $("#productDesc h3").text().replace($("#productDesc h3 span").text(),"");
			pn = $.trim(pn);
			$(productName).html(pn);
			$(productName).attr('class', 'activeTitle');
			$(c).prepend(productName);
		}
	},
	
	request: function() {
		var _this = this;
		var requestParams = {
			'segmentId': this.params.segment,
			'comCodeId': this.params.comCode,
			'subComCodeId': this.params.subComCode,
			'selectedValues': this.params.selectedValues,
			'regions': 6,
			'shippingFrom': 'US',
			'productId': this.params.productId
		};

		$.ajax({
			url: DRAG.DEF.SERVICES_URL + this.serviceURL,
			type: 'GET',
			data: requestParams,
			dataType: 'json',
			success: function(json) {
				if(json) { 
					_this.build(json); 
				}
			}
		});
	}
};

$(document).ready(function() {
	DRAG.CatalogBrowser.init();	
});
