jQuery.query = function() {
        var r = {};
        var q = location.search;
        q = q.replace(/^\?/,''); // remove the leading ?
        q = q.replace(/\&$/,''); // remove the trailing &
        jQuery.each(q.split('&'), function(){
                var key = this.split('=')[0];
                var val = this.split('=')[1];
                // convert floats
                //if(/^[0-9.]+$/.test(val))
                        //val = parseFloat(val);
                // ingnore empty values
                if(val)
                        r[key] = val;
        });
        return r;
}; 

function urldecode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
   
    if( String(str) === 'undefined' ) str = '';
    var histogram = {};
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
 
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}


$(document).ready(function(){
	$('.defaultText').focus(function(srcc){
		if ($(this).val() == $(this).attr('title')){
	        	$(this).removeClass('defaultTextActive');
	        	$(this).val('');
	    	}
	});
	
	$('.defaultText').blur(function(){
		if ($(this).val() == ''){
			$(this).addClass('defaultTextActive');
			$(this).val($(this)[0].title);
		}
	});

	$('#primary-search-form').submit(function() {
		$('.defaultText').each(function() {
			if($(this).val() == $(this).attr('title')) {
				$(this).val('');
			}
		});
	});

	$('#primary-search-form select').change(function(){
		// Clear all subsequent select boxes:
		$( 'select[name="' + $(this).attr('name') + '"] ~ select').val('');

		// Prepare the data for sending to our ajax handler:
		
		if( $(this).parent().get(0).tagName == 'TD' ){
			// Table:
			var product_type = $(this).parents('tbody:first').attr('id');
		} else{
			// Non-table:
			var product_type = $(this).parent().attr('id');
		}

		switch(product_type){
			case 'form-motors':
				// horsepower,rpm,voltage,enclosure
				var send = {
					product: "motor",
					horsepower: $("select[name=motor-hp]").val(),
					rpm: $("select[name=motor-rpm]").val(),
					voltage: $("select[name=motor-voltage]").val(),
					enclosure: $("select[name=motor-enclosure]").val(),
					construction_materials: $("select[name=motor-construction_materials]").val()
				};
				break;
			case 'form-rars':
				// ratio,max_hp,frame,construction_materials
				var send = {
					product: "reducer",
					ratio: $("select[name=rars-ratio]").val(),
					frame: $("select[name=rars-frame]").val(),
					construction_materials: $("select[name=rars-construction_materials]").val()
				};
				break;
			case 'form-helical-gearmotors':
				// horsepower,rpm,construction_materials,enclosure
				var send = {
					product: "helical_gearmotor",
					horsepower: $("select[name=helicals-gearmotor-horsepower]").val(),
					construction_materials: $("select[name=helicals-gearmotor-construction_materials]").val(),
					enclosure: $("select[name=helicals-gearmotor-enclosure]").val()
				};
				break;
			case 'form-helical-reducers':
				// max_input_hp,input_frame,construction_materials,nominal_output_rating
				var send = {
					product: "helical_reducer",
					input_frame: $("select[name=helicals-reducer-input_frame]").val(),
					construction_materials: $("select[name=helicals-reducer-construction_materials]").val(),
					ratio: $("select[name=helicals-reducer-ratio]").val()
				};
				break;
		}

		// Send and process the request:
		$.getJSON('/admin/ajax/search_options.php', send, function(result){
			if(result != null){
				$.each(result, function(key, value){
					if(send.product == 'reducer'){
						send.product = 'rars';
					}

					if(send.product == 'helical_gearmotor'){
						send.product = 'helicals-gearmotor';
					}

					if(send.product == 'helical_reducer'){
						send.product = 'helicals-reducer';
					}

					$('select[name=' + send.product + '-' + key + ']').removeOption(/./);
					$('select[name=' + send.product + '-' + key + ']').addOption(value, false);
				});
			}
		});
	});

	initialize_search_form();
});

function initialize_search_form(){
	// if the form product changes...
	$('#form-product').change(function(){
		// Hide all subforms:
		if( $('#form-product').parent().get(0).tagName !== 'TD' ){
			$('.subform').slideUp('fast');
		} else{
			$('.subform').hide();
		}

		// Save the current values of the product type and model number:
		var saved_prodtype_index = $('#form-product')[0].selectedIndex;
		var saved_model_number = $('#primary-search-model_number').val();

		// Clear the form:
		$('#primary-search-form').clearForm();

		// Restore the values we saved earlier:
		$('#form-product')[0].selectedIndex = saved_prodtype_index;
		$('#primary-search-model_number').val(saved_model_number);

		// If the product isn't empty...
		if($(this).val() != ''){
			// Display the proper product:
			switch($(this).val()){
				case 'motors':
					if($('#form-product').parent().get(0).tagName !== 'TD'){
						$('#form-motors').slideDown('slow');
					} else{
						if(navigator.appName.indexOf("Microsoft") > -1){
							$('#form-motors').css('display', 'block');
						} else{
							$('#form-motors').css('display', 'table-row-group');
						}
					}
					break;
				case 'rars':
					if($('#form-product').parent().get(0).tagName !== 'TD'){
						$('#form-rars').slideDown('slow');
					} else{
						$('#form-rars').css('display', 'table-row-group');
					}
					break;
				case 'helicals-gearmotor':
					if($('#form-product').parent().get(0).tagName !== 'TD'){
						$('#form-helical-gearmotors').slideDown('slow');
					} else{
						$('#form-helical-gearmotors').css('display', 'table-row-group');
					}
					break;
				case 'helicals-reducer':
					if($('#form-product').parent().get(0).tagName !== 'TD'){
						$('#form-helical-reducers').slideDown('slow');
					} else{
						$('#form-helical-reducers').css('display', 'table-row-group');
					}
					break;
			}
		}

		// Any text areas with default values, lets restore the defaults:
		$('.defaultText').each(function(){
			var defaultValue = $(this).attr('title');
			$(this).val(defaultValue);
		});
	});

	// Set up the form as it was when search was clicked if applicable:
	if( $('#form-product').length > 0 ){
		$('#form-product').selectOptions($.query()['form-product']);
		$('#form-product').change();
	
		switch($.query()['form-product']){
			case 'motors':
				// problem with the numbers:
				$('select[name=motor-hp]').selectOptions(urldecode($.query()['motor-hp']));
				$('select[name=motor-hp]').change();
	
				$('select[name=motor-rpm]').selectOptions(urldecode($.query()['motor-rpm']));
				$('select[name=motor-rpm]').change();
	
				$('select[name=motor-voltage]').selectOptions(urldecode($.query()['motor-voltage']));
				$('select[name=motor-voltage]').change();
	
				$('select[name=motor-enclosure]').selectOptions(urldecode($.query()['motor-enclosure']));
				$('select[name=motor-enclosure]').change();

				$('select[name=motor-construction_materials]').selectOptions(urldecode($.query()['motor-construction_materials']));
				$('select[name=motor-construction_materials]').change();
				break;
			case 'rars':
				$('select[name=rars-ratio]').selectOptions(urldecode($.query()['rars-ratio']));
				$('select[name=rars-ratio]').change();
	
				$('input[name=rars-max_hp]').val($.query()['rars-max_hp']);
	
				$('select[name=rars-frame]').selectOptions(urldecode($.query()['rars-frame']));
				$('select[name=rars-frame]').change();
	
				$('select[name=rars-construction_materials]').selectOptions(urldecode($.query()['rars-construction_materials']));
				$('select[name=rars-construction_materials]').change();

				//console.log( urldecode($.query()['rars-construction_materials']) );
				//console.log('Value: ' + $('select[name=rars-construction_materials]').val());
				break;
			case 'helicals-gearmotor':
				$('select[name=helicals-gearmotor-horsepower]').selectOptions(urldecode($.query()['helicals-gearmotor-horsepower']));
				$('select[name=helicals-gearmotor-horsepower]').change();
	
				$('input[name=helicals-gearmotor-output_rpm]').val($.query()['helicals-gearmotor-output_rpm']);
	
				$('select[name=helicals-gearmotor-construction_materials]').selectOptions(urldecode($.query()['helicals-gearmotor-construction_materials']));
				$('select[name=helicals-gearmotor-construction_materials]').change();
	
				$('select[name=helicals-gearmotor-enclosure]').selectOptions(urldecode($.query()['helicals-gearmotor-enclosure']));
				$('select[name=helicals-gearmotor-enclosure]').change();
				break;
			case 'helicals-reducer':
				$('input[name=helicals-reducer-max_input_hp]').val($.query()['helicals-reducer-max_input_hp']);
	
				$('select[name=helicals-reducer-input_frame]').selectOptions(urldecode($.query()['helicals-reducer-input_frame']));
				$('select[name=helicals-reducer-input_frame]').change();
	
				$('select[name=helicals-reducer-construction_materials]').selectOptions(urldecode($.query()['helicals-reducer-construction_materials']));
				$('select[name=helicals-reducer-construction_materials]').change();
	
				$('select[name=helicals-reducer-ratio]').selectOptions(urldecode($.query()['helicals-reducer-ratio']));
				$('select[name=helicals-reducer-ratio]').change();
				break;
		}
	}
}

