$(document).ready(function () {
    $('.attributeSelector').change(function(){
    	attributeSelectorChange(this);
    });
	$('#Model-Drilldown > form > #manufacturer').change(function(){	
		if(!checkZeroVal($('#Model-Drilldown > form > #manufacturer'), "M") && !getAll($('#Model-Drilldown > form > #manufacturer'), "eOfficeProducts.TF_models_by_sku", "Model","series","name")){
			getData("series","name","eOfficeProducts.TF_models_by_sku","Model",$('#Model-Drilldown > form > #manufacturer'));
		}
	});
	$('#Supplies-Drilldown > form > select').change(function(){	
		if(!checkZeroVal($('#Supplies-Drilldown > form > select'), "S") && !getAll($('#Supplies-Drilldown > form > select'), "eOfficeProducts.TF_supplies_by_sku", "Supplies","type","part_number")){
			getData("type","part_number","eOfficeProducts.TF_supplies_by_sku","Supplies",$('#Supplies-Drilldown > form > select'));
		}
	});

	
    $('#filterResults').closest('form').submit(function(event){
    	$('[name="addToSearchTrail"]').val('1$'+$('#keyword').val());
    });
    
    $('.spextabs li').click(function(){
    	$('.spextabs li').removeClass('active');
    	$(this).addClass('active');
    	$('.spextab').css('display', 'none');
    	var tab = parseInt($(this).attr('id').toString().replace('tabcontrol', ''));
    	$('div#tab'+tab).fadeIn();
    });
    
    $('#viewAllManufacturers').click(function(){
		if ($(this).text() != 'Collapse') {
			$('#viewAllManufacturers').text('Collapse');
			if($('#allManufacturers').html() == '') {
				$('#allManufacturers').hide();
		    	$.get(
					"ajaxRequests.php?"+parseUrl(), 
					{'type': 'manufacturers', 'keyword': $('#persistent_keyword').html()},
					function(data){
						if(data == '') {
							$('#viewAllFeatures').text('Already shown all');
							$('#viewAllFeatures').fadeOut(2500);
							return;
						}
						$('#allManufacturers').html(data);
						$('#allManufacturers').slideDown();
					}
				);
			} else {
				$('#allManufacturers').slideDown();
			}
			
		} else {
			$('#allManufacturers').slideUp();
			$('#viewAllManufacturers').text('View all');
		}
    });
    
    $('#viewAllFeatures').click(function(){
    	if ($(this).text() != 'Collapse') {
    		$('#viewAllFeatures').text('Collapse');
    		if($('#allFeatures').html() == '') {
    			$('#allFeatures').hide();
    			$.get(
    					"ajaxRequests.php?"+parseUrl(), 
    					{'type': 'features', 'keyword': $('#persistent_keyword').html()},
    					function(data){
    						if(data == '') {
    							$('#viewAllFeatures').text('Already shown all');
    							$('#viewAllFeatures').fadeOut(2500);
    							return;
    						}
    						$('#allFeatures').html(data);
    						$('#allFeatures').slideDown();
    						$('.attributeSelector').change(function(){
    							attributeSelectorChange(this);
    						});
    					}
    			);
    		} else {
	    		$('#allFeatures').slideDown();
    		}
    	} else {
    		$('#allFeatures').slideUp();
    		$('#viewAllFeatures').text('View all');
    	}
    });
    
    $('#viewAllCategories').click(function(){
    	if ($(this).text() != 'Collapse') {
    		$('#viewAllCategories').text('Collapse');
    		if($('#allCategories').html() == '') {
    			$('#allCategories').hide();
    			$.get(
					"ajaxRequests.php?"+parseUrl(), 
					{'type': 'categories', 'keyword': $('#persistent_keyword').html()},
					function(data){
						if(data == '') {
							$('#viewAllCategories').text('Already shown all');
							$('#viewAllCategories').fadeOut(2500);
							return;
						}
						$('#allCategories').html(data);
						$('#allCategories').slideDown();
					}
    			);
    		} else {
    			$('#allCategories').slideDown();
    		}
    	} else {
    		$('#allCategories').slideUp();
    		$('#viewAllCategories').text('View all');
    	}
    });
    
});


function attributeSelectorChange(item)
{
	var location = window.location.toString();
	if(location.search(/"?"/i) == -1){
		location += "?";	
	}
	var parts = location.split('&');
	location = '';
	var newParts = new Array();
	var k = 0
	for (i in parts) {
		if(parts[i].toString().substring(0,16) != 'addToSearchTrail') {
			newParts[k] = parts[i]; 
			k++;
		}
	}
	
	location = newParts.join('&');
	
	var caption = '';
	var attributeCaption = $('#attributeCaption'+$(item).attr('name')).text();
	
	caption += attributeCaption + ': ' + $('[name="' + $(item).attr('name') + '"] option[value="' + $(item).val() + '"]').text();
	location += '&addToSearchTrail=' + '7$' + $(item).attr('name') + '$' + $(item).val() + '$' + escape(caption);
	
	var operator = $('[name="operator' + $(item).attr('name') + '"]').val();
	if (operator != undefined) {
		location += '&operator' + $(item).attr('name') + '=' + operator;
	}
	var trail = $('[name="trail"]').val();
	window.location = location+'&trail='+trail;
}


function in_array( what, where ){
	var a=false;
	for(var i=0;i<where.length;i++){
	  if(what == where[i]){
	    a=true;
        break;
	  }
	}
	return a;
}

function parseUrl()
{
	var neededParameters = new Array('trail', 'addToSearchTrail', 'removeFromTrail');
	var url = window.location.toString();
	var parts = url.split('?');
	var qString = parts[1].toString();
	//return qString;
	parts = qString.split('&');
	var ret = new Array(); 
	for (i in parts) {
		var part = parts[i].toString().split('=');
		if (in_array(part[0], neededParameters))
			ret[ret.length] = parts[i];
	}
	return ret.join('&');
}
	function clearSelects(code){
		$('#'+ code + 'Drill_2').html("");
		$('#'+ code + 'Drill_3').html("");
	}
	function checkZeroVal(selector, code){
		if(selector.val() == 0){
			clearSelects(code);
			return true;
		}
		return false;
	}
	function createHiddenInput(searchType,name, value){
		$('#' + searchType + '-Drilldown > form').append('<input type="hidden" name="'+ name +'" value="' + value + '"/>');
	}
	function getAll(selector, database, searchType, type, type2){
		var code=searchType.charAt(0);
		if(selector.val() == -1){
			$.get("modules/Toner_Finder/ajax_toner.php?",{'type': selector.attr("id"),'search':database, 'selected_value' : selector.val()},																																		 			function(data){		
				selector.html(data);
				clearSelects(code);
				});	
			return true;
		}
		return false;
	}
	function getData(type, type2, database, searchType, manufacturer){
	var code=searchType.charAt(0);
	$('#'+ code + 'Drill_2').html("<span class='toner-loading'>Loading...</span>");
	$.get("modules/Toner_Finder/ajax_toner.php?",{'type': type,'search':database, 'selected_value' : manufacturer.val()},																																  			function(data){																																																																	 					$('#'+ code + 'Drill_3').length != 0 ? clearSelects(code) : "";
					$('#'+ code + 'Drill_2').html(data);
					$('#'+type).change(function(){
						if($('#'+ code + 'Drill_3').length == 0){																																																	
							$('#'+ code + 'Drill_2').after("<div id='"+ code +"Drill_3'><span class='toner-loading'>Loading...</span></div>");
						}
						else{
							$('#'+ code + 'Drill_3').html("<span class='toner-loading'>Loading...</span>");
						}
						$.get("modules/Toner_Finder/ajax_toner.php?",{'type': type2,'search':database, 'selected_value' : $('#'+type).val(), 'manufacturer':manufacturer.val()},																															  					function(data){																																																																																 							$('#'+type).val() != 0 ? $('#'+ code + 'Drill_3').html(data) : $('#'+ code + 'Drill_3').html("");
							$('#'+type2).change(function(){
								$('#' + searchType + '-Drilldown > form').attr("action", "toner_finder.php?mode=search");
								$('#' + searchType + '-Drilldown > form').attr("method", "POST");
								createHiddenInput(searchType,"database", database);
								createHiddenInput(searchType,"search1", type);
								createHiddenInput(searchType,"search2", type2);
								createHiddenInput(searchType,"value1", $('#'+type).val());
								createHiddenInput(searchType,"value2", $('#'+type2).val());
								$('#' + searchType + '-Drilldown > form').submit();		
								$('#toner_finder').html('<img src="skin1/images/loading.gif"/>');
													  
							});
							
						});
						
					});
					if($('#'+type + " option[value='-1']").attr("selected")){
						$('#'+type).change();
					}
				});
	
	}
