var newSearch;
var errorMsg = {
	'brand': 'Please select the brand of your printer',
	'family': 'Please select the family of your printer',
	'model': 'Please select the model of your printer'
};

var categories = {
	'inkjetcartridges': 'Ink Cartridges',
	'lasertoners': 'Toner Cartridges',
	'coloursticks': 'Solid Ink'
};

var category_values = {
  'Ink Cartridges': 'inkjetcartridges',
  'Toner Cartridges': 'lasertoners',
  'Solid Ink': 'coloursticks'
};

var types = {
  'category': {
    'prev': '',
    'next': 'brand',
    'search': 'get_manufacturers'
  },
  'brand': {
    'prev': 'category',
    'next': 'family',
    'search': 'get_families'
  },
  'family': {
    'prev': 'brand',
    'next': 'model',
    'search': 'get_models'
  },
  'model': { 
    'prev': 'family',
    'next': '',
    'search': ''
  }
};

var csaveSearch = Class.create();
csaveSearch.prototype = {
	
	initialize: function() {
		
		var th = this;
		var first_item = true;
		
		// adding hooks for select boxes in search form
		$('find_carts_widget').select('select').each(function(elm){
		  Element.observe(elm,'change',th.search.bindAsEventListener(th,elm.name));
		  
		  if( first_item ) {
		    th.search(th,types[elm.name].prev,false);
		    first_item = false;
		  } else {
		    elm.disabled = true;
		  }
		});
	
		Element.observe('find_carts_widget','submit',th.go.bindAsEventListener(th));
		
		// sorting search by cartridge number
		Element.observe('toggle_search','click',this.toggle_google_search.bindAsEventListener());
		Element.observe('google_search','click',this.google_search.bindAsEventListener());
		$('search').select('input').each(function(elm){
			if( elm.type == 'text' ) {
				Element.observe(elm,'keypress',function(e){
					if( e.keyCode == 13 ) {
						newSearch.google_search();
					}
				});
			}
		});
	},
	
	search: function(e,search_elm) {
		
		var th = this;
		var next_search_elm = types[search_elm].next;
		
		// get category from optgroup
		var category = $('category').getValue();
		
		if( $('family').tagName == 'SELECT' ) {
		  var family_select = $('family')
		  var selected_family = family_select[$('family').selectedIndex];
		
		  category = ( selected_family.parentNode.tagName == 'OPTGROUP' ) ? category_values[selected_family.parentNode.label] : category;
		  
		} 
		
		// only get the page to go to if it's the model
		if( search_elm == 'model' ) {
		  th.get_page();
		  th.validate(search_elm);
		  return;
		}
		
		category = ( $('all_categories') && search_elm == 'brand' ) ? '' : category;
		
		// setting up vars for search
		var params = {
		  'action': types[search_elm].search,
		  'category': category,
		  'manufacturer': ( $('manufacturer') ) ? $('manufacturer').getValue() : $('brand').getValue(),
		  'family': ( search_elm == 'brand' ) ? '' : $('family').getValue()
		};
		
		th.loading(next_search_elm,true);
		
		// getting printer details
  	new Ajax.Request('/cgi-bin/printer_search.pl',{
  		method: 'post',
  		parameters: params,
  		onComplete: function(t) {
  			var result = t.responseText.evalJSON();
  			th.create_options(result.list,next_search_elm,result.groups);
  			th.loading(next_search_elm,false);
  			th.get_page();
  			th.validate(search_elm);
  		}
  	});
		
	},

	loading: function(elm,show) {
		
		var loader = elm + "_loader";
		
		if( !$(loader) ) return;
		
		if( show ) {
			$(loader).addClassName('show_loader');
		} else {
			$(loader).removeClassName('show_loader');
		}
	
	},
	
	create_options: function(option_list,select_id,opt_group) {
	  
		if( opt_group == 1 ) {
			
			$(select_id).select('option').each(function(elm){
				if( elm.value != "" ) elm.remove();
			});
			
			$(select_id).select('optgroup').each(function(elm){
				elm.remove();
			});
			
			for( var i in option_list ) {
	
				var group_list = option_list[i];
				var thisGroup = new Element('optgroup',{'label': categories[i] });
				
				for( var j=0 ; j < group_list.length; j++ ) {
					var thisOption = new Element('option',{ 'value': group_list[j].value }).update(group_list[j].name);
					thisGroup.insert(thisOption);
				}
				
				$(select_id).insert(thisGroup);
			}
			
			if( select_id == 'family' || select_id == 'model' ) {
				var noOfGroups = $(select_id).select('optgroup').length;
				$(select_id).disabled = ( noOfGroups > 0 ) ? '' : 'disabled';
				if( select_id == 'family' && noOfGroups == 0 ) $('model').disabled = 'disabled';
			}

		} else {
			
			$(select_id).select('option').each(function(elm){
				if( elm.value != "" ) elm.remove();
			});
			
			for( var i = 0; i < option_list.length; i++ ) {

					var thisOption = new Element('option',{ 'value': option_list[i].value }).update(option_list[i].name);
					$(select_id).insert(thisOption);
			
			}
			
		}
		
		// clearing selects so it doesn't get confused
		
		if( select_id == 'brand' ) {
		  $('family').select('optgroup').each(function(elm){
				elm.remove();
			});
			$('family').select('option').each(function(elm){
				if( elm.value != "" ) elm.remove();
			});
		  $('model').select('option').each(function(elm){
				if( elm.value != "" ) elm.remove();
			});
			$('family').disabled = true;
			$('model').disabled = true;
		}
		
		if( select_id == 'family' ) {
		  $('model').select('option').each(function(elm){
				if( elm.value != "" ) elm.remove();
			});
			$('family').disabled = false;
			$('model').disabled = true;
		}
		
		if( select_id == 'model' ) {
		  $('model').disabled = false;
		}

	},
	
	get_page: function() {
		
		var manufacturer = $('manufacturer') ? $('manufacturer').getValue() : $('brand').getValue();
		var params = {
			'action': 'get_page', 
			'category': $('category').getValue(), 
			'manufacturer': manufacturer, 
			'family': $('family').getValue(),
			'model': $('model').getValue()
		};
		
		new Ajax.Request('/cgi-bin/printer_search.pl',{
			method: 'post',
			parameters: params,
			onComplete: function(t) {
				var result = t.responseText.evalJSON();
				$('find_carts_widget').action = result.page;
			}
		});
		
	},
	
	go: function(e) {
		
		//this.get_page();
		
		if( $('find_carts_widget').action.search(/results\.html/) == -1 ) {
			$('find_carts_widget').method = 'post';
			var validate = this.validate();
			if( !validate ) Event.stop(e);
		} 
		
	},
	
	validate: function(elmOnly) {
		
		var validates = true;
		
		if( elmOnly ) {
			
			if( $(elmOnly) ) {
  			var box_id = $(elmOnly+"_error");
  	    var elm_value = $(elmOnly).getValue();
	   
  			if( elm_value != '' && elm_value != undefined ) {
  				if( box_id ) box_id.hide();
  			}
			}
			
		} else {
			
			$('find_carts_widget').select('select').each(function(selectElm) {

				var box_id = selectElm.id+"_error";
		
				if( selectElm.getValue() == '' || selectElm.getValue() == undefined ) {
					if( validates ) {
						newSearch.error_box(selectElm);
						validates = false;
					} else {
						if( $(box_id) ) $(box_id).hide();
					}
				} else {
					if( $(box_id) ) $(box_id).hide();
				}
		
			});
		}
		
		return validates;
	},
	
	error_box: function(elm) {
		var box_id = elm.id+"_error";
		
		if( $(box_id) ) {
			$(box_id).show();
		} else {
			var box = new Element('span',{ 'id': box_id, 'class': 'search_error' }).update(errorMsg[elm.id]);
			new Insertion.After(elm,box);
		}
	},
	
	google_search: function() {
		
		$('find_carts_widget').method = 'get';
		$('find_carts_widget').action = '/results.html';
		
		return true;
		
	},
	
	toggle_google_search: function(e) {
		
		$('search').select('span').each(function(elm){
			
			if( elm.hasClassName('show') ) {
				elm.removeClassName('show');
			} else {
				elm.addClassName('show');
			}
			
		});
		
		Event.stop(e);
		
	}
	
};

function initCSaveSearch() { if( $('find_carts_widget') ) newSearch = new csaveSearch(); }
document.observe('dom:loaded',initCSaveSearch);