/*=============================================
	Search Page Side Filters
	Blake Ropelato
==============================================*/

$(document).ready(function(){
	
	// Determine if a string is in an array element
	function inArray(needle, haystack) {
		var n = haystack.length;
		for (var i=0; i<n; i++) {
			if (haystack[i]==needle) {
				return true;
			}
		}
		return false;
	}
	
	// Determine what section we are in
	function determineSection(selector, filter){
		var title = selector.parents('li').attr('id');
		title = title.replace('Filter','');
		title = title.toLowerCase();
		var nonAttributes = new Array('price', 'brand', 'weight', 'category');
		if(!inArray(title, nonAttributes) && filter != ''){
			applyFilters(title, filter, 'add');
		}
		else{
			applyFilters(title, filter, true);
		}
	}
	
	// Add the appropriate filter to the url and refreshes the page
	function applyFilters(title, filter, valid) {
		tb_show(null,'#TB_inline?width=230&height=80&inlineId=ShowLoadingIndicator',false);
		var url = window.location;
		url = unescape(url);
		url = String(url);
		
		if(valid === true){
			url = removeFilter(url, title, false);
			
			if(filter != ''){
				if(url.indexOf('?') >=0 ){
					url = url + '&' + title + "=" + filter;
				}
				else{
					url = url + '?' + title + "=" + filter;
				}
			}
		}		
		else if(valid == 'add'){
			url = addFilter(url, title, filter);
		}
		else{
			url = removeFilter(url, title, filter);	
		}
		
		// page always needs to get removed, same with submit, same with cache
		url = removeFilter(url, 'page', false);
		url = removeFilter(url, 'submit', false);
		url = removeFilter(url, 'cache', false);
		
		
		//Go and get the original brand list if it isn't already in the url
		/*if(url.indexOf('orig_brand=') < 0){
			//url = url + getOrigBrands();
		}*/
		
		window.location.href = url;
	}
	
	// Adds a filter to the group
	function addFilter(url, section, filter){		
		var revisedSection;
		if(url.indexOf('&'+section) >= 0 || url.indexOf('?' + section) >= 0){
			var secStart = url.indexOf(section);
			var urlFront = url.substr(0, secStart);
			var urlBack = url.substr(secStart);
			var secEnd = urlBack.indexOf('&');
			if(secEnd >= 0){
				revisedSection = urlBack.substr(0,secEnd);
				urlBack = urlBack.substr(secEnd);				
			}else{
				revisedSection = urlBack;
				urlBack = '';				
			}
			revisedSection = revisedSection + '|' + filter;
			url = urlFront + revisedSection + urlBack;
			return url;
		}
		else{
			if(url.indexOf('?') >=0 ){
				url = url + '&' + section + '=' + filter;
			}
			else{
				url = url + '?' + section + '=' + filter;
			}
			return url;
		}
	}
	
	// Removes a entire condition or just 1 filter from that condition
	function removeFilter(url, section, filter){
		
		var revisedSection = '';
		var secStart;
		var attach_q = false;
			
		if(url.indexOf('&' + section) < 0){
			if(url.indexOf('?' + section) < 0){
				return url;
			}else{
				secStart = url.indexOf('?' + section);
				attach_q = true;
			}
		}else{
			secStart = url.indexOf('&' + section);
		}
		
		var urlFront = url.substr(0, secStart);
		var urlBack = url.substr(secStart);
		
		var secEnd = urlBack.indexOf('&',1);
		if(filter != false){
			var revisedSection = urlBack;
		}
		if(secEnd >= 0){
			if(filter != false){
				revisedSection = urlBack.substr(0, secEnd);
			}
			urlBack = urlBack.substr(secEnd);	
		}else{
			urlBack = '';	
		}
		
		if(filter != false){
			var preserve = new Array();
			var idStart = revisedSection.indexOf('=');
			var idAllString = revisedSection.substr(idStart + 1);
			
			revisedSection = revisedSection.substr(0, idStart + 1);
			
			var idAllArray = idAllString.split('|');
			
			var count = 0;
			for(var i = 0; i < idAllArray.length; i++){
				if(idAllArray[i] != filter){
					preserve[count] = idAllArray[i];
					count++;
				}
			}
			
			if(preserve.length > 0 && section != 'search_query'){
				revisedSection = revisedSection + preserve.join('|');
			}
			else{
				revisedSection = '';	
			}
		}
		if(attach_q == true && revisedSection == '' && urlBack != ''){
			urlFront = urlFront + '?';
			urlBack = urlBack.substr(1);
		}
		url = urlFront + revisedSection + urlBack;
		
		return url;
	}
	
	
	$('#filterBar :checkbox').click( function(){
		var id = $(this).attr('id');
		var section = $(this).attr('value');
		applyFilters(section, id, false);												
	});
	
	/*function getOrigBrands(){
		var filter = '&orig_brand=';
		var value;
		$('#FilterBrand #MultiplePane #BrandList div').each( function(){
	   		value = $(this).children('input').attr('id');
			filter = filter + value + '|';
	    });
		filter = filter.substring(0, filter.length -1);
		return filter;
	}*/
	
	// Handles select box for products displayed per page
	$('#perPage').change(function(){
		var filter = $(this).attr('value');
		applyFilters('per_page', filter, true);
	});
	
	// Handles select box for preferred display order
	$('.sort').change(function(){
		var filter = $(this).attr('value');
		applyFilters('sort', filter, true);
	});
	
	// opens and closes a filter list li
	$('.FilterSectionTitle').click(function(){
		$(this).siblings('.FilterContent').toggleClass('active');
		$(this).parent().toggleClass('expanded');
		/*$(this).parent().find('.FilterClearList').each( function(){
			$(this).toggleClass('inactive');
		});*/
	});
	
	$('.SideFilterList ul span').mouseover(function(){
		$(this).css({"cursor" : "pointer"});					   
	});
	
	$('.SideFilterList a').mouseover(function(){
		$(this).css({"cursor" : "pointer"});					   
	});
	
	$('#CategoryList div').mouseover(function(){
		$(this).css({"cursor" : "pointer"});					   
	});
	
	$('.SelectMultiple').mouseover(function(){
		$(this).css({"cursor" : "pointer"});					   
	});
	
	$('.SelectSingle').mouseover(function(){
		$(this).css({"cursor" : "pointer"});					   
	});
	$('.FilterClearList').mouseover(function(){
		$(this).css({"cursor" : "pointer"});					   
	});
	
	// Performs the filterings of the search box for brands
	$('#BrandSearch').keyup(function(){
		var phrase=$(this).val();
		phrase = phrase.toUpperCase();
		var style='<div class="HighLight">';		
		$(this).parent().siblings('div').each(function(){
			var tag = 'a';
			if($(this).attr('id') == 'MultiplePane'){
				tag = 'label';
			}
			var brandList = $(this).children('#BrandList');
			if(brandList != null){
				brandList.children('div').each(function(){
					var brandLabel=$(this).find(tag);
					var brandName=brandLabel.html();
					var highLightHtml=$(this).attr("id");
					if(phrase.length>0){
						if(highLightHtml.toUpperCase().indexOf(phrase)>-1){
							var start=highLightHtml.toUpperCase().indexOf(phrase);
							var end=start+phrase.toString().length;
							highLightHtml=highLightHtml.substring(0,start)+style+highLightHtml.substring(start,end)+"</div>"+highLightHtml.substring(end,brandName.length);
							brandLabel.html(highLightHtml);					
							$(this).css({"display" : "block"});
						}else{
							$(this).css({"display" : "none"});
						}
					}else{
						brandLabel.html(highLightHtml);
						$(this).css({"display" : "block"});
					}
				});
			}
		});
	});
	
	// Handles a filter being selected and refreshes the page
	$('.SideFilterList a').click(function(){		
		var filter = $(this).attr('id'); 
		determineSection($(this), filter);
	});
	
	//handles multiple checkboxes being selected
	$('.UpdateMultiple').click(function(){
		var clickedElement = $(this);
		var filter = '';
		$(this).parents('li').find(':checkbox').each( function(){
			var value = $(this).attr('id');
			if($(this).is(":checked")){
				filter = filter + value + "|";
			}								 
		});
		
		filter = filter.substring(0, filter.length -1);
		determineSection(clickedElement, filter);
	});
	
	
	// Handles clearing of all selected checkboxes in a section
	$('.FilterClearList').click(function(){
		determineSection($(this), '');
	});
	
	// Handles the displaying of the filtercategory section
	$('#CategoryList .CategorySectionClick').click(function(){
		var parent = $(this).parent();
		parent.toggleClass('CatExpand');
		parent.siblings('div').each( function(){
			$(this).toggleClass('inactive');														 
		});
		var keepHidden = true;
		if(parent.is('.CatExpand')){
			keepHidden = false;	
		}
		parent.children('div').each( function(){
			if(keepHidden == true){
				if(!$(this).is('.inactive')){
					$(this).toggleClass('inactive');
				}
			}
			else{
				if($(this).is('.inactive')){
					$(this).toggleClass('inactive');
				}
			}
		})
	});
	
	// Toggles between the select single and select multiple panes
	$('.SelectMultiple').click(function(){
		$(this).parent().toggleClass('inactive');
		$(this).parent().siblings('#MultiplePane').toggleClass('inactive');
	});
	$('.SelectSingle').click(function(){
		$(this).parent().toggleClass('inactive');
		$(this).parent().siblings('#SinglePane').toggleClass('inactive');
	});
	
	// Will toggle a checkbox when its label is clicked on
	$('.SideFilterList label').click(function(){
		var checkbox = $(this).siblings('input');	
		if(checkbox.is(':checked')){
			checkbox.attr('checked', false);	
		}
		else{
			checkbox.attr('checked', true);	
		}
	});
	
});