/* global filterDecimalSign,filterDecimalPoint,filterDecimalSymbol,filterDecimalSymbolPlace */

// Save current hash for use in IE 6-8
var hash = location.hash;
// Detect if page is loaded in IE 6-8
var isOldIE = jQuery.browser.msie && (parseInt(jQuery.browser.version) == 8 || parseInt(jQuery.browser.version) == 7 || parseInt(jQuery.browser.version) == 6);

var isIE8 = jQuery.browser.msie && (parseInt(jQuery.browser.version) == 8);
// Used to store setTimeout pointer
var timeout;
// Used to calculate position of loading icon
var newCoords = '';
// Used to store the class of the containing div of a clicked filter checkbox
var nodeClass = '';
// Slider
var slider;
// Slider minVal
var minVal;
// Slider maxVal
var maxVal;
// Wether or not this shop has filter
var hasFilter = false;

// Creates a wrapper to call ajax functionality for next- and previous page links and sorting, limit dropdowns in product list
var fixLinks = function() {
	jQuery('.countNumber').html(jQuery('#page-count-text').val());

	if (jQuery('#previous-page-link').val() != '') {
		jQuery('.countPrevious').removeClass('hidden');
		jQuery('.countPrevious a').attr('href', jQuery('#previous-page-link').val());
	} else {
		jQuery('.countPrevious').addClass('hidden');
	}
	if (jQuery('#next-page-link').val() != '') {
		jQuery('.countNext').removeClass('hidden');
		jQuery('.countNext a').attr('href', jQuery('#next-page-link').val());
	} else {
		jQuery('.countNext').addClass('hidden');
	}

	// Bind click action to next and previous product list page links
	jQuery('.countPrevious a, .countNext a, .count a').click(function() {
		var t = this.href.split('?');
		makeHash(t[1]);
		return false;
	});
};

// Create a hash for the url based on the current url, along with the filter options
var makeHash = function(insert) {
	var url = [];
	var brands = [];
	var categories = [];
	var data = '';
	var variants = '';
	var hash = window.location.hash.substr(1).split('&');
	var search = window.location.search.substr(1).split('&');
	var dataType = '';
	var variantType = '';

	// Loop through all checked checkboxes in #filter and create new filter string
	jQuery('#filter input:checked, #filter option:selected').each(function() {
		// If this is a checkbox use this.name, otherwise use name of select name
		var name = this.name == undefined ? this.parentNode.name : this.name;

		if (this.value != '') {
			// News and sale filter
			if (name == 'filternews' || name == 'filtersale') {
				url[url.length] = name;
			}

			// Brands filter
			if ( name == 'filterbrands[]') {
				brands[brands.length] = this.value;
			}

			// Categories filter
			if (name == 'filtercategories[]') {
				categories[categories.length] = this.value;
			}


			// Custom data filter
			if (name.search('filterdata') > -1) {
				var typeChange = name != dataType && dataType != '';
				data += typeChange ? '|' : '';
				data += data != '' && !typeChange ? ',' : '';
				data += this.value;

				dataType = name;
			}

			// Variant filter
			if (name.search('variant') > -1) {
				var typeChange = name != variantType && variantType != '';
				variants += typeChange ? '|' : '';
				variants += variants != '' && !typeChange ? ',' : '';
				variants += this.value;

				variantType = name;
			}
		}
	});

	// Create the filter url
	if (brands.length > 0) {
		url[url.length] = 'filterbrands=' + brands;
	}
	if (categories.length > 0) {
		url[url.length] = 'filtercategories=' + categories;
	}
	if (data != '') {
		url[url.length] = 'filterdata=' + data;
	}
	if (variants != '') {
		url[url.length] = 'filtervariants=' + variants;
	}
	if (insert != undefined) {
		url[url.length] = insert;
	}
	if (jQuery( "#min-price" ).length > 0) {
		url[url.length] = 'filterpricemin=' + jQuery( "#slider" ).slider( "values", 0 );
	}
	if (jQuery( "#max-price" ).length > 0) {
		url[url.length] = 'filterpricemax=' + jQuery( "#slider" ).slider( "values", 1 );
	}

	// Add any existing parameters from url such as search to the new url hash
	jQuery(search).each(function () {
		url[url.length] = this;
	});

	// Set the hash
	window.location.hash = '#filter&' + url.join('&');
}

// Call ajax product list and update filter options based on response.
// NOTE: Uses container #product-listing-container and 3 hidden fields #custom-data-available, #brands-available and #variants-available that must be present in list return
var hashChange = function() {
	var location = window.location.hash.replace('#', '?');
	// Hide the current container
	if (isOldIE) {
		jQuery('.productList').css('visibility', 'hidden');
	} else {
		jQuery('.productList').animate({ opacity: 0 }, 250);
	}

	// Show loading icon after 400ms
	timeout = setTimeout(function() {
		var contentCoords = jQuery('.productList').offset();

		if (newCoords == '') {
			newCoords = { left: contentCoords.left + 274, top: contentCoords.top };
			jQuery('#ajaxLoading').offset(newCoords);
		}

		jQuery('#ajaxLoading').show();
	}, 400);

	// Perform ajax load of list, with forajax parameter which limits output to be only the product list
	jQuery('#productListContainer').load(window.location.pathname + location + (location.search(/\?/) > -1 ? '&' : '?') + 'forajax .productList,.category-empty', function() {
  		// On ajax load return
		// Display no products text if return is empty
		if (jQuery('#productListContainer .category-empty').length > 0) {
			if (categoryEmptyText != undefined) {
				jQuery('#productListContainer .category-empty:empty').html(categoryEmptyText);
			}
			jQuery('div.count').hide();
		} else {
			jQuery('div.count').show();
		}

		// Clear timeout on icon display and hide icon
		clearTimeout(timeout);
		jQuery('#ajaxLoading').hide();

		// Fix the previous and next product page links in the list
		fixLinks();

		// Show the new list page
		if ( isOldIE ) {
			jQuery('.productList').css('visibility', 'visible');
		} else {
			jQuery('.productList').animate({ opacity: 100 }, 100);
		}

		// Only apply if the shop has filter
		if (hasFilter) {

			// Update the filter options
			if (nodeClass != undefined && nodeClass != '') {
				jQuery('div#filter > div:not(#' + nodeClass +') div input:checkbox').attr('disabled', 'disabled').next('.filterText').css('color', 'gray');
				jQuery('div#filter > div:not(#' + nodeClass +') div option[value!=""]').css('color', 'grey').attr('notavailable', 'true');
				nodeClass = '';
			}

			// If no products were found return at this point
			if (jQuery('#products-new').length == 0) {
				return;
			}

			// Enable new products if available
			if (jQuery('#products-new').val() == '1') {
				jQuery('#filternews').removeAttr('disabled').next('span').css('color', 'black');
			}

			// Enable products on sale if available
			if (jQuery('#products-on-sale').val() == '1') {
				jQuery('#filtersale').removeAttr('disabled').next('span').css('color', 'black');
			}

			// Enable available custom data
			jQuery('#custom-data-available').val().split(',').each(function(v) {
				jQuery('#filterdata_' + v).removeAttr('disabled').removeAttr('notavailable').css('color', 'black').next('span').css('color', 'black');
			});

			// Enable available brands
			jQuery('#brands-available').val().split(',').each(function(v) {
				jQuery('#filterbrand_' + v).removeAttr('disabled').removeAttr('notavailable').css('color', 'black').next('span').css('color', 'black');
			});

			// Enable available categories
			jQuery('#categories-available').val().split(',').each(function(v) {
				jQuery('#filtercat_' + v).removeAttr('disabled').removeAttr('notavailable').css('color', 'black').next('span').css('color', 'black');
			});

			// Enable available variants
			jQuery('#variants-available').val().split(',').each(function(v) {
				jQuery('#filtervariant_' + v).removeAttr('disabled').removeAttr('notavailable').css('color', 'black').next('span').css('color', 'black');
			});

			// Make array of url hash parts
			var t = location.replace('?', '');
			t = t.split('&');

			// In case the page is loaded first time, recheck selected variants, custom data and brands
			jQuery(t).each(function() {
				// Check price min
				if (this.search('filterpricemin') > -1) {
					slider.slider('values', 0, this.substr(15));
					jQuery("#min-price").html(numberFormat(slider.slider('values', 0)));
				}
				// Check price max
				if (this.search('filterpricemax') > -1) {
					slider.slider('values', 1, this.substr(15));
					jQuery("#max-price").html(numberFormat(slider.slider('values', 1)));
				}

				// Check news
				if (this.search('filternews') > -1) {
					jQuery('#filternews').attr('checked', true);
				}
				// Check sale
				if (this.search('filtersale') > -1) {
					jQuery('#filtersale').attr('checked', true);
				}
				// Check brands
				if (this.search('filterbrands=') > -1) {
					var t2 = this.substr(13).split(',');
					jQuery(t2).each(function(i, v2) {
						jQuery('#filterbrand_' + v2).attr('checked', true);
					});
				}
				// Check categories
				if (this.search('filtercategories=') > -1) {
					var t2 = this.substr(17).split(',');
					jQuery(t2).each(function(i, v2) {
						jQuery('#filtercat_' + v2).attr('checked', true);
					});
				}
				// Check variants
				if (this.search('filtervariants=') > -1) {
					var t2 = this.substr(15).replace('|', ',').split(',');
					jQuery(t2).each(function(i, v2) {
						jQuery('#filtervariant_' + v2).attr('checked', true);
					});
				}
				// Check custom data
				if (this.search('filterdata=') > -1) {
					var t2 = this.substr(11).replace('|', ',').split(',');
					jQuery(t2).each(function(i, v2) {
						jQuery('#filterdata_' + v2).attr('checked', true);
					});
				}
			});

			// Reset Clear links
			jQuery('#filter .filterClear').hide();
			jQuery('#filter div').has('input:checked').find(' .filterClear').show();

			if (slider.length > 0 && (slider.slider('values', 0) != slider.slider('option', 'min') || slider.slider('values', 1) != slider.slider('option', 'max'))) {
				jQuery('#filterMisc .filterClear').show();
			}
		}
	});
}

// Perform on page load
jQuery(function() {

	hasFilter = jQuery('#filter').length > 0;


	// Only apply if the shop has filter
	if (hasFilter) {
		var hasSlider = jQuery('#slider').length > 0;
		if (hasSlider) {
			// Check if ui is aldready loaded, in that case load compatible version
			var uiVersion = '1.8.16';
			if (jQuery.ui && jQuery.ui.version.substr(0,3) == '1.7') {
				uiVersion = '1.7.3';
			}

			// Slider
			 slider = jQuery('#slider');
			// Slider minVal
			 minVal = Math.floor(parseFloat(jQuery('#products-min-price').val()));
			// Slider maxVal
			 maxVal = Math.ceil(parseFloat(jQuery('#products-max-price').val()));

 			jQuery("#min-price").html(numberFormat(minVal));
			jQuery("#max-price").html(numberFormat(maxVal));

			// Load slider script and create slider on return
			jQuery.getScript('/_design/common/js/jquery/jquery-ui-' + uiVersion + '.slider.min.js', function() {
				slider.slider({
					range: true,
					min: minVal,
					max: maxVal,
					values: [ minVal, maxVal ],
					slide: function( event, ui ) {
						// Set the text for min and max beneath slider
						jQuery("#min-price").html(numberFormat(ui.values[0]));
						jQuery("#max-price").html(numberFormat(ui.values[1]));
					},
					stop: function ( event, ui ) {
						nodeClass = 'filterSlider';
						makeHash();
					}
				});
			});
		}

		// Bind script to clear all checkboxes and reset range slider to clear buttons
		jQuery('.filterClear').click(function() {
			jQuery(this).parent().find('input:checkbox').attr('checked', false);
			nodeClass = jQuery(this).parent().attr('id');
			var s = jQuery('#' + nodeClass + ' #slider');

			if (s.length > 0) {
				s.slider('values', 0, s.slider('option', 'min'));
				s.slider('values', 1, s.slider('option', 'max'));
				jQuery("#min-price").html(numberFormat(s.slider('values', 0)));
				jQuery("#max-price").html(numberFormat(s.slider('values', 1)));
			}

			makeHash();

		});

		// Enable new products if available
		if (jQuery('#products-new').val() == '1') {
			jQuery('#filternews').removeAttr('disabled').next('span').css('color', 'black');
		}

		// Enable products on sale if available
		if (jQuery('#products-on-sale').val() == '1') {
			jQuery('#filtersale').removeAttr('disabled').next('span').css('color', 'black');
		}

		// Bind hashchange event to filter inputs
		jQuery('#filter input').click(function() {
			nodeClass = jQuery(this).parent().parent().attr('id');

			makeHash();
		});

		// Bind hashchange event to filter inputs
		jQuery('#filter select').change(function() {
			if (jQuery(this).find('option:selected[notavailable]').length > 0) {
				this.selectedIndex = 0;
				return false;
			}

			nodeClass = jQuery(this).parent().parent().attr('id');

			makeHash();
		});
	}

    // Bind blur to links
    jQuery('div.categories-listing-item a').focus(function() {
		this.blur();
	});

    // Unbind onchange from order and limit dropdowns, in case of custom lists
    jQuery('div.sorting select[name="order"] ,div.sorting select[name="limit"]').removeAttr('onchange');

    // Bind change action to sorting dropdown
    jQuery('#order-select, div.sorting select[name="order"]').change(function () {
        makeHash('fo='+ jQuery(this).val());
    });

    // Bind change action to limit dropdown
    jQuery('#limit-select, div.sorting select[name="limit"]').change(function () {
		makeHash('fl='+ jQuery(this).val());
    });

	// Bind hashchange event
	jQuery(window).bind('hashchange', function() {
		hashChange();
	});

	// IE 6 and IE 7 compatability, perform 100ms timeout that triggers hashchange if hash has changed
	if ( isOldIE && !isIE8 ) {
		setInterval(function() {
			if (location.hash != hash) {
				jQuery(window).trigger('hashchange');
    			hash = location.hash;
		   }
	   }, 100);
	}

	// Trigger hashchange first time page is loaded if hash is set
	if (window.location.hash.length > 0) {
		jQuery(window).trigger('hashchange');
	}

	// Make additional binds for ajax functionality
	fixLinks();
});


