// Object to queue ajax requests 
var requestqueue                = {};
var firstload = true;
function filteredSearchOptions(index, abs_url, reset) {

    window.addEvent('domready', function() {
        main_form = $('main_options_form');
        firstload = true;
        last_click = false;
        reverse_index = $A(index);
        saved_index = $A(index);
        reverse_index.reverse();
        saved_options = new Array();
        if($('btn_clear')) { $('btn_clear').addEvent('click', function(e) { return runDistinctSearch(true); }); }
        if($('btn_search')) { $('btn_search').addEvent('click', function(e) { 
				// If this is a different manufacturer to the current 
				// dealer we need to show the sunwin theme
				var selectedManufacturer = $('manufacturer').options[$('manufacturer').selectedIndex].value;
                // alert(selectedManufacturer);
				// If this is not un the URL change the action
				if(window.location.toString().toLowerCase().indexOf(selectedManufacturer.toString().toLowerCase().replace(' ', '_')) === -1) {
					$('main_options_form').action = 'http://'+document.domain+'/referer/dealership/index.html';
				}
				return true; 
			}); 
		}
        if($('btn_search_group')) {
            $('btn_search_group').addEvent('click', function(e) {
                //$('stocked_by_dealership').selectedIndex = 0; //setProperty('value', '');
                $('stocked_by_dealership').options[$('stocked_by_dealership').selectedIndex].value = '';
				$('main_options_form').action = 'http://'+document.domain+'/referer/dealership/index.html';
                return true;
            });
        }
        if(!$('btn_search')) { return false; }

        function runDistinctSearch(reset) {     

            // url    = abs_url + ':getDistinctIndexJson';
            url    = abs_url + ':sunwinGetSearchOptions';
            myurl  = url;
            params = '';
            indexs = new Array();
            values = new Array();            
            optionsdiv = $('options');
            val = '';

            for(i=0;i<index.length; i++) {

                val = '';
                myid = index[i][1];
                mytitle = index[i][0];
                myval = index[i][2];
                // alert(myid + " - " + mytitle + " - " + myval);
    	        if($type(myval) == 'boolean' && myval == true) { indexs[indexs.length] = 'o.' + myid; } 
	    	    else { indexs[indexs.length] = myid; }

                if($(myid)) { var myel = myid; }
                if(!$(myel)) { continue; }               

                if(myid == 'condition') {
                    if($('condition_new').checked == true) val = 'new';
                    else if($('condition_used').checked == true) val = 'used';
                    else val = 'reset';                    
                    values[myel] = val;
                } else {

                    if(!$chk(reset) || reset == false) {
                        var val = $(myel).get('value');
                        values[myel] = val;
                        if(val == 'reset') { $(myel).set('value', 'reset'); }
                    } else {
                        var val = myval;
                        values[myel] = val;
                    }

                    if($(myel).get('tag') !== 'input') {
                        if($(myel)) {
                            $(myel).empty();
                            $(myel).options[0] = new Option('Updating...', '', true); 
                            $(myel).options[0].selected = true;
                        }
                    }

                    val = val.replace('+', '%2B');

                    if(val == 'reset') { val = 'reset'; }            
                    if(reset == true) { val = 'reset'; }

                }
                if(i== 0) { params += myid + '=' + escape(val); } 
                else { params += '&' + myid + '=' + escape(val); }
            };

            inds = indexs.join(',');
            parameters = 'dindex=' + inds + "&" + params + '&refresh=' + Math.random();

            // DAN - this is true every time???
            if(firstload) {
				firstload = false;
				parameters += '&firstload=true';
			}

            if(window.location.href.match('referer\/dealership')) {
                parameters = parameters + '&referer=dealership';
            }

            if(!$chk(requestqueue.jSonRequest)) {
                requestqueue.jSonRequest = new Request({
                    url:myurl, method:'get', link: 'chain',
                    onComplete: insertOptions
                });
            }

            requestqueue.jSonRequest.send(parameters); 
            firstload = false;
            return false;        
        }

        function insertOptions(jsonObj) {

            if(!$chk(jsonObj)) { return false; }
            var jsonObj = JSON.decode(jsonObj);

            optionsdiv = $('options');
            if(jsonObj['error']) { optionsdiv.set('html',jsonObj['error']); return false;  }

            var ct = new Date();
            var t = ct.getTime();
          
            index.each(function(item, ind) {
                el = $(item[1]);

                if(el && el.get('tag') == 'select') {
                    
                    el.removeEvents('change');
                    el.empty();

					// Clone a visual of the select.
					/*
                	var cloned_el = el.clone();
					var el_par = el.getParent('span');
					if(el_par) {
                		el_par.adopt(cloned_el);
                		el.setStyle('display', 'none');
                		cloned_el.setStyle('display', '');
					}
					*/
					

                    el.options[0] = new Option('All ' + item[0] + 's', '');
                    if(jsonObj[item[1]]) {
                        for(i=0; i<jsonObj[item[1]].length; i++) {
                            var myvalue = String(jsonObj[item[1]][i]);
                            var myvalue2 = String(values[item[1]]);

                            if(!$chk(myvalue2)) { myvalue2 = ''; }

                            var cont = myvalue.replace(/(\d+:)/ig, '');

							//cont = ucfirst(cont);
                            el.options[i+1] = new Option(cont,myvalue);

                            if(myvalue == myvalue2) {       
                                el.options[0].value = 'reset';        
                                //el.options[i+1].selected = true; 
                            } else if(myvalue.match(/(selected:)/ig)) {
                                el.options[0].value = 'reset';
                                el.options[i+1].value = myvalue.replace(/(selected:)/ig,'');
                                el.options[i+1].innerHTML = cont.replace(/(selected:)/ig,'');
                                el.options[i+1].selected = true;

                            }
                        }
                    }
                    
                    // Remove clone, restore select.
                	// if(cloned_el) { cloned_el.destroy(); }
                	// el.setStyle('display', '');
                    
                } else if(item[1] == 'condition') {
                    for(i=0; i<jsonObj[item[1]].length; i++) {
                        var myvalue = String(jsonObj[item[1]][i]);
                        if(myvalue.match(/(selected:)/ig)) {
                            myvalue = myvalue.replace(/(selected:)/ig,'');
							myvalue = myvalue.toLowerCase();
                            if($(item[1] + '_' + myvalue)) {
                            $(item[1] + '_' + myvalue).checked = true;
                            }
                        }
                    }
                }

                if($('stocked_by_dealership')) {
	                if($('stocked_by_dealership').selectedIndex != 0) {
	                    if($('btn_search_group')) { $('btn_search_group').setStyle('display', ''); }
	                } else {
	                    if($('btn_search_group')) { $('btn_search_group').setStyle('display', 'none'); }
	                }
                }

            });

            // Now hide any that have selectedIndex of 0

            if(saved_index[saved_index.length - 1][1] == 'condition') { saved_index.pop(); }
            var ind_length = saved_index.length;
            saved_index.each(function(el,el_index) {
                var sel_ind = false;
                var row_index = (el_index + 1);
                var next_id =false;
                var next_el = false; 
                var el_id = false;
                var ele = false;
                if($chk(el[1]) && $chk($(el[1]))) {
                    el_id = el[1];
                    ele = $(el[1]);
                    if(ele.get('tag') == 'select') {
                        if(el_index == '0' || el_index == '1') { 
                            ele.removeClass('disabled'); 
                            ele.addEvent('change', function(e) {
                                main_form.store('last_click',el_id);
                                runDistinctSearch(false);
                            });
                            if(el_index == '1') {
                                sel_ind =  ele.options.selectedIndex;
                                if($chk(saved_index[el_index + 1])) {
                                    next_id = saved_index[el_index + 1][1];
                                    next_label = saved_index[el_index + 1][0];
                                    if($chk(next_id)) {
                                        if($(next_id)) {
                                            if(sel_ind > 0) {
                                                $(next_id).removeClass('disabled');
                                                $(next_id).addEvent('change', function(e) {
                                                    main_form.store('last_click',el_id);
                                                    runDistinctSearch(false);
                                                });
                                            } else {
                                                $(next_id).addClass('disabled');
                                                var t_op = $(next_id).options[0];
                                                $(next_id).empty();
                                                $(next_id).options[0] = new Option(ucfirst("All " + next_label) + "s",'');
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            sel_ind = ele.options.selectedIndex;
                            if(!$chk(sel_ind)) { sel_ind = 0; }
                            if($chk(saved_index[el_index + 1])) {
                                next_id = saved_index[el_index + 1][1];
                                next_label = saved_index[el_index + 1][0];
                                if($chk(next_id)) {
                                    if($(next_id)) {
                                        if(el_index > 1 && el_index < 4) {
                                            if(el_index == 2) {
                                                if(sel_ind > 0) {
                                                    $(next_id).removeClass('disabled');
                                                    $(next_id).addEvent('change', function(e) {
                                                        main_form.store('last_click',el_id);
                                                        runDistinctSearch(false);
                                                    });
                                                } else {
                                                    $(next_id).addClass('disabled');
                                                    // Remove all but the first option.
                                                    var t_op = $(next_id).options[0];
                                                    $(next_id).empty();
                                                    $(next_id).options[0] = new Option(ucfirst("All " + next_label) + "s",'');
                                                }
                                            }
                                        } else {
                                            ele.removeClass('disabled');
                                            ele.addEvent('change', function(e) {
                                                main_form.store('last_click',el_id);
                                                runDistinctSearch(false);
                                            });
                                            // Last Item.
                                            if(row_index == (ind_length - 1)) {
                                                $(next_id).removeClass('disabled');
                                                $(next_id).addEvent('change', function(e) {
                                                    main_form.store('last_click',el_id);
                                                    runDistinctSearch(false);
                                                });
                                            }
                                        }
                                    }
                                }   
                            }
                        }
                    }
                }
            });

            // Update the result count information
            if($('resultcount')) {
                if(jsonObj.totalresults == 1) {
                    $('resultcount').innerHTML = jsonObj.totalresults + " result found" 
                } else {
                    $('resultcount').innerHTML = jsonObj.totalresults + " results found"
                }
            }

            // Do we need to display the advanced options
            if(jsonObj.usingadvanced == true && $('advanced_options')) {
                $('advanced_options').style.display = 'block';
            }

            return false;
        }

        function ucfirst(theWord) { 
            var w = theWord.replace(/^(.)/, function (d){ 
                return d.toUpperCase(); 
            });
            return w; 
        }

        // Off we go...
        runDistinctSearch(true);

    });
}
