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 tracking_categories = {
  '0': undefined,
  '1': 'fc-wizard-model',
  '2': 'fc-wizard-family-model',
  '3': 'fc-wizard-make-family-model'
};

var types = {
  'category': {
    'prev': '',
    'next': 'brand',
    'search': 'get_manufacturers',
    'action': {
      'fc-wizard-make-family-model': undefined,
      'fc-wizard-family-model': undefined,
      'fc-wizard-model': undefined
    }
  },
  'brand': {
    'prev': 'category',
    'next': 'family',
    'search': 'get_families',
    'action': {
      'fc-wizard-make-family-model': 'select-1',
      'fc-wizard-family-model': undefined,
      'fc-wizard-model': undefined
    }
  },
  'family': {
    'prev': 'brand',
    'next': 'model',
    'search': 'get_models',
    'action': {
      'fc-wizard-make-family-model': 'select-2',
      'fc-wizard-family-model': 'select-1',
      'fc-wizard-model': undefined
    }
  },
  'model': { 
    'prev': 'family',
    'next': '',
    'search': '',
    'action': {
      'fc-wizard-make-family-model': 'select-3',
      'fc-wizard-family-model': 'select-2',
      'fc-wizard-model': 'select-1'
    }
  }
};

var csaveSearch = Class.create();
csaveSearch.prototype = {
	
	initialize: function() {
		
		var th = this;
		var first_item = undefined;
		
    if( $('google_custom_search') ) {
      
      var button = $$('span.google_search').first();
      Element.observe(button,'click',th.google_search.bindAsEventListener(th,true));
    
      Element.observe('search_form','keypress',function(e){
        if( e.keyCode == 13 ) {
           th.google_search(e,true);
        }
      });
         
    } else {
      
       // adding hooks for select boxes in search form
       var select_count = 0;
       
       $('find_carts_widget').select('select').each(function(elm){
         Element.observe(elm,'change',th.search.bindAsEventListener(th,elm.name));
         !first_item ? first_item = types[elm.name] : elm.disabled = true;
         select_count++;
       });
   
       // doing initial search
       th.search(th,first_item.prev,false);
       
       // setting up analytics tracking
       th.tracking_category = tracking_categories[select_count];
       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(this));
       Element.observe('google_search','click',this.google_search.bindAsEventListener(this,false));
  
       $('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;
		
		// tracking select of printer
		var tracking_action = types[search_elm].action[this.tracking_category];
		if( tracking_action ) this.track(tracking_action);
		
		// 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(tracking_action);
  			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();
		
		this.track('submit');
		
		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(e,submit) {
		
		$('find_carts_widget').method = 'get';
		$('find_carts_widget').action = '/results.html';
		
		if( submit ) $('find_carts_widget').submit();
		
		return true;
		
	},
	
	toggle_google_search: function(e) {
		
		this.track('search-by-number-link');
		
		$('search').select('span').each(function(elm){
			
			if( elm.hasClassName('show') ) {
				elm.removeClassName('show');
			} else {
				elm.addClassName('show');
			}
			
		});
		
		Event.stop(e);
		
	},
	
	track: function(tracking_action) {
	  
	  _gaq.push(['_trackEvent',this.tracking_category,tracking_action]);
	  
	}
	
};

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