$(function() {
	
	// if #productBlockContainer do all stuff
	var $productBlockContainer = $('#productBlockContainer');

	if($productBlockContainer.length > 0){
		//$('#productBlockContainer .block .product h3').equalizeHeights();		
		var currentHash = (window.location.hash).substring(1);
		$('#availableProducts').removeClass('shown');
		var $productFilters = $('#productFilters');
		var productFiltersExists = $productFilters.length > 0;
		var $forms = $('form');	
		var $productFiltersInputs =  $('#productFilters').find('input');
		var $sortFormSerialize = $('#sortForm').serialize();	
		
		// default values
		var defAttributes = {};
		defAttributes['iNavID'] = $productBlockContainer.attr('class');
		defAttributes['productsPerPage'] = 20;
		defAttributes['page'] = 1;
		defAttributes['sortCol'] = 'name';
		defAttributes['sortOrder'] = 'asc';
		defAttributes['filter'] = productFiltersExists;
		
		//Create Attributes
		var attributes = {};
		$.each(defAttributes,function(i,e) {
			//console.log(i, e);
			attributes[i] = e;
		});
			
		//FIX MARGINS
		function fixProductMargins(){
			var $paginatedProducts = $('.block', '#paginatedProducts');
			$paginatedProducts.removeClass('noLeftMargin');
			$paginatedProducts.each(function(i){
				if($(this).is(':nth-child(5n+1)')){
					$(this).addClass('noLeftMargin');
				}
			});
		}
		
		function hashDeCo(string, doWhat){
	    	var theString = decodeURIComponent(string.toString());
	    	
	    	var compress = {
	    		'v1' : ['iNavID=','i='],
	    		'v2' : ['&productsPerPage=','&pp='],
	    		'v3' : ['&page=','&p='],
	    		'v4' : ['&sortCol=','&sc='],
	    		'v5' : ['&sortOrder=','&so='],
	    		'v6' : ['&filter=','&f='],
	    		'v7' : ['&colors\\[\\]','&c[]'],
	    		'v8' : ['&brands\\[\\]','&b[]'],
	    		'v9' : ['&sorteer-op=','&soop=']
	    	}
	    	
	    	var decompress = {
	    		'v1' : ['iNavID=','i='],
	    		'v2' : ['&productsPerPage=','&pp='],
	    		'v3' : ['&page=','&p='],
	    		'v4' : ['&sortCol=','&sc='],
	    		'v5' : ['&sortOrder=','&so='],
	    		'v6' : ['&filter=','&f='],
	    		'v7' : ['&colors[]','&c\\[\\]'],
	    		'v8' : ['&brands[]','&b\\[\\]'],
	    		'v9' : ['&sorteer-op=','&soop=']
	    	}
	    	
	    	if(doWhat === "compress"){
	    		$.each(compress ,function(i,e) {
	    			var thevalue = e[0];
	    			var regex = new RegExp(thevalue,"g");
	    			//theString = theString.replace(regex, e[1]);
	    			theString = theString.replace(regex, e[1]);
	    			//console.log(theString);	
	    		});
	    	} else if(doWhat === "decompress"){
	    		$.each(decompress ,function(i,e) {
	    			var thevalue = e[1];
	    			var regex = new RegExp(thevalue,"g");
	    			theString = theString.replace(regex, e[0]);	
	    		});
	    	}
	    	
	    	return theString;
	    }
		
		function doPagination(data){
			//console.log(data['attributes']['page']);	
			var activePage = parseFloat(data['attributes']['page'])-1;
	    	$('#productPagination').pagination($('.block', '#availableProducts').length, {
				items_per_page: attributes['productsPerPage'],
				current_page: activePage,
				callback: function pageselectCallback(page_index, jq, sortType){
					
					//console.log(data);	
										
					//update page attribute
					data['attributes']['page'] = page_index+1;
					var decodedUri = decodeURIComponent($.param(data['attributes']));
					window.location.hash = hashDeCo(decodedUri, "compress");
						
					// Get number of elements per pagionation page from form
			        var max_elem = Math.min((page_index+1) * attributes['productsPerPage'], $('.block', '#availableProducts').length);
			        var newcontent = '';
			       	
			        // Iterate through a selection of the content and build an HTML string
			        for(var i=page_index*attributes['productsPerPage'];i<max_elem;i++) {
			            newcontent += $('.block', '#availableProducts').eq(i).wrap('<div class="new" />').parent().html();
			        }
			        
			        // Replace old content with new content
			        $('#paginatedProducts').html(newcontent);
			        $('.new .block', '#availableProducts').unwrap();
			        
			        fixProductMargins();
			        $('#paginatedProducts .block').equalizeHeights();
			        // Prevent click event propagation
			        return false;
				}
			});
	    }
		
		// do ajax and refresh productBlockContainer
		function refreshOverview(extraData, refresh){ 	
			var filterData = hashDeCo(extraData, "decompress");
			if(refresh){ //if refresh or hash already on adres bar
				var attributesSerialized = filterData
				var filterDataArr = filterData.split('&');
				$(filterDataArr).each(function(i,e) {
					var splittedArr	= e.split('=');
					var leftBracketPos = splittedArr[0].indexOf('[');
					if(leftBracketPos !== -1){
						var leftval = splittedArr[0].substring(0, leftBracketPos);
						if($.browser.msie){
							$('#'+leftval+"_"+splittedArr[1]).trigger('click');
							if($('#'+leftval+"_"+splittedArr[1]).is(':checked')){
								$('#'+leftval+"_"+splittedArr[1]).next('label.color').addClass('active');
							} else {
								$('#'+leftval+"_"+splittedArr[1]).next('label.color').removeClass('active');
							}
						} else {
							$('#'+leftval+"_"+splittedArr[1]).attr('checked', true).next('label.color').toggleClass('active');
						}
					} else if(splittedArr[0] === "sorteer-op") {
						$('#sorteer-op').find('option[value="'+splittedArr[1]+'"]').attr('selected', true);
					}
				});
				
			} else {
				var attributesSerialized = (filterData.length) ? ($.param(attributes) + "&" + filterData) : $.param(attributes);
			}
  		    
			$.ajax({  
				type: 'GET',
				async: false,
				cache: false,
				url: '/webshop/products/front/task.php?task=filter-prods&' + attributesSerialized,  
				dataType: 'json',  
				success: function(xml_list) {
					$('#noProducts').hide();
					xml_list['attributes'] = $.deparam(attributesSerialized);
					if(xml_list['products']){
						var html = "";
						for (i=0; i<=xml_list['products'].length-1; i++) {
							html += '<div class="block">';
							html += $("#product_"+xml_list['products'][i]).html();
							html += '</div>';
						}
						$('#availableProducts').html(html);	
						//console.log(xml_list['products']);
						doPagination(xml_list);
					} else {
						$('#availableProducts').html("");
						$('#noProducts').show();
						doPagination(xml_list);
					}
					
				}
			}); //END GET XML
		
		}
		
		if(productFiltersExists){
			$productFiltersInputs.change(function(i, e){
				refreshOverview($productFiltersInputs.serialize()  + "&" + $sortFormSerialize, false);
				var item = i.currentTarget;
				$(item).next('label').toggleClass('active');
			});
		}
		
		$('#sorteer-op').change(function(e) {
			var $this = $(this);
			var $thisSerialize = $this.serialize();
			var theValue = e.currentTarget.value;
			var theValueArr = theValue.split('_');
			attributes['sortCol'] = theValueArr[0];
			attributes['sortOrder'] = theValueArr[1];
			$sortFormSerialize = $('#sortForm').serialize();
			if(productFiltersExists){
				refreshOverview($productFiltersInputs.serialize() + "&" + $sortFormSerialize, false);
			} else {
				refreshOverview($thisSerialize, false);
			}
		});
		
		//color label clicking not working
		//this fixes it
		if($.browser.msie){
			$labels = $forms.find('label.color');
			
			$labels.click(function(event, element){
				var $this = $(this);
				var inputId = $this.attr('for');
				$('#'+inputId).trigger('click').trigger('click'); // double becase of IE bug ;(
			});
		}
		
		//$(window).bind( 'hashchange', function(i,e){
			//refreshOverview(i.fragment, true);
		//});
		
		if(currentHash){
			refreshOverview(decodeURIComponent(currentHash), true);
		} else {
			refreshOverview("", false);
		}
	
	} //end f($productBlockContainer.length > 0)
		
});
