function AutoComplete(searchinput, resultsarea, category) {
    this.Category = category;
    this.URL = 'http://' + document.location.host + '/auto_c.aspx';
    this.MaxResults = 10;
    this.ClockID = 0;
    this.ClockTick = 250;
    this.ProductIdInput = 'hdnProdId';

    this.searchInput = searchinput;
    this.resultsArea = resultsarea;
    this.selected = -1;
    this.overResults = false;
    this.minChars = 1;
    this.cache = new Object();
    this.firstSelected = false;
    this.saveSearched = "";
    this.firstClick = true;
    this.lastSearchNone = false;
    this.clearOnFocus = true;
    this.updateOnUniqueResult = false;
    this.showEmptyResults = false;
    if (searchinput)
        searchinput.setAttribute("resultsHidden", 0);

    this.controlPrefix = "";

    if (this.searchInput != null && this.resultsArea != null) {
        this.init();
    }
}


AutoComplete.prototype.init = function() {
    var ac = this;
    var oldKD = this.searchInput.onkeydown;
    var oldKU = this.searchInput.onkeyup;
    var si = this.searchInput;

    this.searchInput.onkeydown = function(ev) {
        si.style.color = 'black';
        if (!ev)
            ev = window.event;
        ac.completeTxt(ev);

        if (typeof oldKD == 'function') {
            oldKD(ev);
        }

        return noenter(ev);
    };
    this.searchInput.onkeyup = function(ev) {
        si.setAttribute("resultsHidden", 0);

        if (typeof oldKU == 'function')
            oldKU(ev);
    };
    this.searchInput.onblur = function(ev) {
        if (!ac.overResults)
            ac.hideResults();
    };
    this.searchInput.onclick = function(ev) {
        if (ac.firstClick) {
            this.style.color = 'black';
            if (ac.clearOnFocus)
                this.value = '';
            ac.firstClick = false;
        }
    };
    this.resultsArea.onmouseover = function(ev) {
        ac.overResults = true;
        return true;
    };
    this.resultsArea.onmouseout = function(ev) {
        ac.overResults = false;
        return true;
    };
};


AutoComplete.prototype.completeTxt = function(ev) {
    var keynum;
    var charMin = '0'.charCodeAt(0);
    var charMax = 'z'.charCodeAt(0);
    if (window.event) // IE
    {
        keynum = ev.keyCode;
    }
    else if (ev.which) // Netscape/Firefox/Opera
    {
        keynum = ev.which;
    }
    //alert(keynum);

    /*
    alert(String.fromCharCode(95));
    */
    if ((charMin <= keynum && keynum <= charMax) || keynum == 32 || keynum == 8) {
        //disablesubmit();
        closeCategories();
        this.KillClock();
        this.StartClock();
    }
    else {
        switch (keynum) {
            /*
            case 8: //backspace
            {	
            this.KillClock();
            var searched = this.searchInput.value;
            searched = searched.substring(0,searched.length-1);
            this.getFromCache(searched);
            break;    
            }
            */ 
            case 38: //up arrow
                this.goUp();
                break;
            case 40: //down arrow 
                this.goDown();
                break;
            case 13: //enter
                {
                    this.searchInput.setAttribute("resultsHidden", 0);
                    if (-1 == this.selected)
                        this.hideResults();
                    else if (!this.select(this.resultsArea.childNodes[this.selected]))
                        this.hideResults();
                    break;
                }
        }
    }
};

AutoComplete.prototype.UpdateClock = function() {
    var searched = this.searchInput.value;

    if (this.ClockID) {
        clearTimeout(this.ClockID);
        this.ClockID = 0;
    }
    if (searched.length >= this.minChars)//disregard less than 3 characters
    {
        if (this.lastSearchNone == false || searched.indexOf(this.saveSearched) == -1)//avoid searching addditions to a failed search
        {
            if (!this.getFromCache(searched))
                this.callback();
        }
    }
    else if (this.saveSearched.indexOf(searched) != 0 || searched.length == 0)//hide only if not first letters of last searched
        this.hideResults();
};

AutoComplete.prototype.StartClock = function() {
    var ac = this;
    this.ClockID = setTimeout(function() { ac.UpdateClock(); }, this.ClockTick);
};

AutoComplete.prototype.KillClock = function() {
    if (this.ClockID) {
        clearTimeout(this.ClockID);
        this.ClockID = 0;
    }
};

AutoComplete.prototype.callback = function() {
    var ac = this;
    this.saveSearched = this.searchInput.value;

    var query = '?q=' + escape(this.saveSearched);
    if (undefined != this.Category && null != this.Category)
        query += '&c=' + escape(this.Category);

    var myAjax = new Ajax.Request(
		this.URL + query,
		{
		    method: 'get',
		    onSuccess: function(oHttp) { ac.statechange(oHttp) }
		});
};

AutoComplete.prototype.populateResults = function(resultsArray) {
    var i = 0;
    var ac = this;

    this.lastSearchNone = false;
    for (i = 0; i < resultsArray.length; i++) {
        thisId = resultsArray[i].id;
        newDiv = document.createElement("div");
        newA = document.createElement("a");

        newA.innerHTML = resultsArray[i].name;
        newA.href = '#' + resultsArray[i].id;
        newA.className = 'completeresult';
        newA.onclick = function() { return false; };

        newDiv.appendChild(newA);
        newDiv.id = 'o' + thisId;
        newDiv.onmouseover = function() { ac.highlight(this); };
        newDiv.onclick = function() { ac.select(this); return false; };
        if (i == 0) {
            if (this.firstSelected) {
                newDiv.className = 'acselected';
                this.selected = 0;
            }
        }
        this.resultsArea.appendChild(newDiv);
    }
    if (resultsArray.length == 1 && this.updateOnUniqueResult && resultsArray[0].name.toLowerCase() == $F(this.searchInput).toLowerCase())
        $(this.ProductIdInput).value = resultsArray[0].id;

    this.showResults();

    if (this.resultsArea.childNodes.length == 1) {
        this.highlight(this.resultsArea.firstChild);
    }
};

AutoComplete.prototype.showResults = function() {
    this.resultsArea.className = "showresults";
};

AutoComplete.prototype.saveInCache = function(resultsArray) {
    if (typeof this.cache[this.saveSearched] == 'undefined')
        this.cache[this.saveSearched] = resultsArray;
};

AutoComplete.prototype.getFromCache = function(searched) {
    if (typeof this.cache[searched] != 'undefined') {
        this.resultsArea.innerHTML = "";
        this.hideResults();
        if (this.cache[searched].length > 0)
            this.populateResults(this.cache[searched]);
        else
            this.lastSearchNone = true;
        this.saveSearched = searched;
        return true;
    }
    return false;
};

AutoComplete.prototype.statechange = function(oHttp) {
    var res = oHttp.responseText;
    var iend = res.lastIndexOf('}');
    res = res.substring(0, iend + 1);
    res = res.replace(/\n\r/gi, ' ').replace(/\n/gi, ' ').replace(/\r/gi, ' ');

    var resultMap;
    var ac = this;

    this.resultsArea.innerHTML = "";
    this.hideResults();
    //res != "{\"Products\":[]}"
    if (res != "") {
        resultMap = eval('(' + res + ')');
    }
    if (resultMap.Products.length > 0)
        this.populateResults(resultMap.Products);
    else {
        this.lastSearchNone = true;
        if (this.showEmptyResults) {
            var newDiv = document.createElement("div");
            newDiv.id = 'o0';
            newDiv.style.color = '#FF0000';
            newDiv.innerHTML = 'No matches found.';
            this.resultsArea.appendChild(newDiv);
            this.showResults();
        }
    }
    this.saveInCache(resultMap.Products);

    return true;
};

AutoComplete.prototype.select = function(resultNode) {
    var name = "";
    if (typeof resultNode.firstChild.innerText != 'undefined')
        name = resultNode.firstChild.innerText;
    else
        name = resultNode.firstChild.text;

    var id = resultNode.id.substring(1);
    this.searchInput.value = name;
    //this.searchInput.disabled = true;

    var hdnProdId = document.getElementById(this.ProductIdInput);
    if (hdnProdId != null) {
        hdnProdId.value = id;
        if (typeof hdnProdId.fire != 'undefined')
            hdnProdId.fire('prd:productChange', id);
    }
    //enablesubmit();

    this.hideResults();
};

AutoComplete.prototype.goDown = function() {
    var resultNodes = this.resultsArea.childNodes;
    if (resultNodes.length > 0 && this.selected < resultNodes.length - 1) {
        var nodeObj = resultNodes[++this.selected];
        this.highlight(nodeObj);
    }
};

AutoComplete.prototype.highlight = function(resultNode) {
    for (var i = 0; i < this.resultsArea.childNodes.length; i++) {
        var nodeObj = this.resultsArea.childNodes[i];
        if (nodeObj == resultNode) {
            this.selected = i;
            nodeObj.className = "acselected";

        }
        else if (nodeObj.className == "acselected")
            nodeObj.className = "";
    }
};

AutoComplete.prototype.goUp = function() {
    var resultNodes = this.resultsArea.childNodes;
    if (resultNodes.length > 0 && this.selected > 0) {
        var nodeObj = resultNodes[--this.selected];
        this.highlight(nodeObj);
    }
};

AutoComplete.prototype.hideResults = function() {
    if (this.searchInput && this.selected != -1)
        this.searchInput.setAttribute("resultsHidden", 1);
    this.resultsArea.className = "noresults";
    this.selected = -1;
    this.overResults = false;
};

function createcomplete(category) {
    var inputsearch = document.getElementById('inputsearch');
    var resultarea = document.getElementById('acresultsdiv');

    var MyCompleter = new AutoComplete(inputsearch, resultarea, category);

    var hdnProdId = document.getElementById('hdnProdId');
    if (hdnProdId != null && hdnProdId.value != "" && hdnProdId.value != "0" && hdnProdId.value != "-1") {
        MyCompleter.searchInput.onclick = function() { };
        MyCompleter.searchInput.style.color = 'black';
        MyCompleter.firstClick = false;
    }
}

function createcompleteRNR(category) {
    var inputsearch = document.getElementById('inputsearchRnrThread');
    var resultarea = document.getElementById('acresultsdivRnrThread');

    var MyCompleter = new AutoComplete(inputsearch, resultarea, category);

    var hdnProdId = document.getElementById('hdnProdIdRnrThread');
    if (hdnProdId != null && hdnProdId.value != "" && hdnProdId.value != "0" && hdnProdId.value != "-1") {
        MyCompleter.searchInput.onclick = function() { };
        MyCompleter.searchInput.style.color = 'black';
        MyCompleter.firstClick = false;
    }
}


function trimText(s, l) {
    var il = s.length;
    if (il <= l) return s;

    var isp = (s.charAt(l) == ' ');
    var ts = s.substr(0, l);

    if (isp) return ts + '...';

    var ilsp = ts.lastIndexOf(' ');
    if (ilsp == -1 || ilsp == 0) return ts + '...';

    return ts.substring(0, ilsp) + '...';
}

function HtmlDecode(s) {
    var ra = [[/&amp;/g, "&"], [/&quot;/g, "\""], [/&lt;/g, "<"], [/&gt;/g, ">"]];

    var i = 0;
    for (; i < ra.length; i++)
        s = s.replace(ra[i][0], ra[i][1]);

    return s;
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

//addLoadEvent(createcomplete());

/***********************************
category select boxes
***********************************/

var g_isFirstChange = true;
var g_CARS_CATEGORY_ID = 231;
var g_MOTOS_CATEGORY_ID = 391;
var G_BRANDID = 0;
var G_BRANDNAME = null;

function updatelist(categorylist) {
    var previousSelection = document.getElementById('hdnctgid').value;
    var isVisible = (document.getElementById('categoy_selection').style.display == 'block');


    var theSelected = -1;

    //if(isVisible)disablesubmit();
    var categoryindex = categorylist[categorylist.selectedIndex].value;
    var targetlist;
    var subarray;
    var isCars = false;
    var isMotos = false;
    var startFrom = 0;
    var ctgid = parseInt(categoryindex);

    if (ctgid == g_CARS_CATEGORY_ID) {
        isCars = true;
        startFrom = 1;
        previousSelection = document.getElementById('hdnMake').value;
        document.getElementById('ctgid').style.display = 'none';
        if ($('notcars_sub') != null) {
            $('notcars_sub').style.display = 'none';
        }
        document.getElementById('car_details_sub').style.display = 'block';
        targetlist = document.getElementById('sel_make');
        document.getElementById('subcategories_header').innerHTML = 'Select Car';
        document.getElementById('brands_header').innerHTML = '';
        subarray = _g_cars_h;
    }
    else if (ctgid == g_MOTOS_CATEGORY_ID) {
        isMotos = true;
        startFrom = 1;
        previousSelection = document.getElementById('hdnMake').value;
        document.getElementById('ctgid').style.display = 'none';
        if ($('notcars_sub') != null) {
            $('notcars_sub').style.display = 'none';
        }
        document.getElementById('car_details_sub').style.display = 'block';
        targetlist = document.getElementById('sel_make');
        document.getElementById('subcategories_header').innerHTML = 'Select Motorcycle';
        document.getElementById('brands_header').innerHTML = '';
        subarray = _g_motos_h;
    }
    else {
        document.getElementById('ctgid').style.display = 'block';
        if ($('notcars_sub') != null) {
            $('notcars_sub').style.display = 'block';
        }
        document.getElementById('car_details_sub').style.display = 'none';
        document.getElementById('subcategories_header').innerHTML = 'Subcategories';
        document.getElementById('brands_header').innerHTML = 'Brands';
        targetlist = document.getElementById('ctgid');
        subarray = _g_c_c[categoryindex.toString()];
    }
    deleteOptions(targetlist);

    if (isCars || isMotos) {
        addOption(targetlist, 0, 'Select Make...');
    }
    if (subarray != null && -1 != subarray[0]) {
        for (i = 0; i < subarray.length; i++) {
            var subcategoryval = subarray[i];

            var subcategoryname;

            if (isCars) {
                subcategoryname = _g_car_make_name[subcategoryval.toString()];
            }
            else if (isMotos) {
                subcategoryname = _g_moto_make_name[subcategoryval.toString()];
            }
            else {
                subcategoryname = _g_ctg[subcategoryval.toString()];
            }

            addOption(targetlist, subcategoryval, subcategoryname);
            if (g_isFirstChange && previousSelection == subcategoryval.toString()) {
                theSelected = i + startFrom;
            }
        }
        if (subarray.length == 1) {
            targetlist.selectedIndex = 0;
            //if(isVisible)enablesubmit();
        }
        if (theSelected > -1) {
            targetlist.selectedIndex = theSelected;
            //if(isVisible)enablesubmit();
        }
        if (isCars || isMotos) {
            if (targetlist.selectedIndex == -1) {
                targetlist.selectedIndex = 0;
            }
            carsSelectChange(targetlist);
        }
        else {
            catSelectChange(targetlist);
        }
    }
    else {
        addOption(targetlist, categoryindex, "ALL");
        targetlist.selectedIndex = 0;
        catSelectChange(targetlist);
        //if(isVisible)enablesubmit();
    }

    g_isFirstChange = false;
}


function carsSelectChange(list) {
    switch (list.id) {
        case 'sel_make':
            {
                for (var i = 0; i < list.length; i++) {
                    list[i].value = list[i].value.replace("Cars", "");
                }
                populateChildList(list, document.getElementById('sel_model'), 'Model');
                //carsSelectChange(document.getElementById('sel_model'));
                break;
            }
        case 'sel_model':
            {
                populateChildList(list, document.getElementById('sel_year'), 'Year');
                break;
            }

    }
}
function catSelectChange(list) {
    if (list.value == 231) {
        updatelist(list);
    } else {
        populateBrandList(list, document.getElementById('brdid'), 'Brand');
    }
}

function populateBrandList(parentList, childList, childName) {
    deleteOptions(childList);

    if (parentList.selectedIndex < 0) {
        childList.disabled = true;
        return;
    }

    var ajxURL = 'http://' + document.location.host + '/a_hp_sl.aspx';
    var parentIndex = parentList[parentList.selectedIndex].value;
    var previousSelection = '0';

    if (g_isFirstChange) // check previous selction from before repost
    {
        var prev = document.getElementById('hdn' + childName);
        if (prev != null) {
            previousSelection = prev.value.toString();
        }
    }

    var query = '?ctgid=' + escape(parentIndex) + '&getbrand=1';

    var myAjax = new Ajax.Request(
		ajxURL + query,
		{
		    method: 'get',
		    onSuccess: function(oHttp) { gotAjxBrandList(oHttp, childList, previousSelection, childName) }
		});


}
function gotAjxBrandList(oHttp, childList, previousSelection, childName) {
    var res = oHttp.responseText;
    var iend = res.lastIndexOf('}');
    res = res.substring(0, iend + 1);
    res = res.replace(/\n\r/gi, ' ').replace(/\n/gi, ' ').replace(/\r/gi, ' ');

    var resultMap;

    if (res != "") {
        resultMap = eval('(' + res + ')');
    }


    resultMap = resultMap.Brands;

    if (objectLength(resultMap) <= 0)
    { return; }

    var theSelected = -1;
    var i = 0;

    if (G_BRANDID > 0 && G_BRANDNAME != null) {
        addOption(childList, G_BRANDID, G_BRANDNAME);
        theSelected = i;
        i++;
    }
    for (var item in resultMap) {

        if (typeof (resultMap[item]) == "string") {
            addOption(childList, item, resultMap[item]);

            if (previousSelection != "" && previousSelection == item) {
                theSelected = i;
            }
            i++;
        }
        else if (typeof (resultMap[item]) == "number") {
            addOption(childList, resultMap[item], resultMap[item]);

            if (previousSelection != "" && previousSelection == resultMap[item].toString) {
                theSelected = i;
            }
            i++;
        }

    }

    addOption(childList, -2, "None of the Above");
    i++;

    childList.selectedIndex = theSelected;

    if (i == 1) {

        childList.selectedIndex = 0;
    }

    childList.disabled = false;

}
function populateChildList(parentList, childList, childName) {
    deleteOptions(childList);

    if (parentList.selectedIndex <= 0) {
        if (childList != null) {
            childList.disabled = true;
        }
        return;
    }

    var ajxURL = 'http://' + document.location.host + '/a_hp_sl.aspx';
    var parentIndex = parentList[parentList.selectedIndex].value;
    var previousSelection = '0';

    if (g_isFirstChange) // check previous selction from before repost
    {
        var prev = document.getElementById('hdn' + childName);
        if (prev != null) {
            previousSelection = prev.value.toString();
        }
    }

    addOption(childList, 0, 'Select ' + childName + '...');

    var categorylist = $('sel_cat');
    var query = '?ctgid=' + categorylist[categorylist.selectedIndex].value;
    if (childName == 'Model') {
        query += '&brdid=' + escape(parentIndex);
    }
    else {
        var makesel = document.getElementById('sel_make');

        query += '&brdid=' + escape(makesel[makesel.selectedIndex].value);
        query += '&fmlid=' + escape(parentIndex);

    }

    var myAjax = new Ajax.Request(
		ajxURL + query,
		{
		    method: 'get',
		    onSuccess: function(oHttp) { gotAjxCarsList(oHttp, childList, previousSelection, childName) }
		});


}
function objectLength(ob) {
    if (ob == null)
        return 0;
    var i = 0;
    for (var item in ob) {
        i++
    }
    return i;
}
function gotAjxCarsList(oHttp, childList, previousSelection, childName) {
    var res = oHttp.responseText;
    var iend = res.lastIndexOf('}');
    res = res.substring(0, iend + 1);
    res = res.replace(/\n\r/gi, ' ').replace(/\n/gi, ' ').replace(/\r/gi, ' ');

    var resultMap;

    if (res != "") {
        resultMap = eval('(' + res + ')');
    }

    if (childName == "Model") {
        resultMap = resultMap.Families;
    }
    else {
        resultMap = resultMap.Years;
    }
    //alert(resultMap["739"]);
    if (objectLength(resultMap) <= 0)
    { return; }

    var theSelected = -1;
    var i = 0;
    for (var item in resultMap) {

        if (childName == "Model" && typeof (resultMap[item]) == "string") {
            addOption(childList, item, resultMap[item]);
            i++;
            if (previousSelection != "" && previousSelection == item) {
                theSelected = i;
            }
        }
        else if (typeof (resultMap[item]) == "number") {
            addOption(childList, resultMap[item], resultMap[item]);
            i++;
            if (previousSelection != "" && previousSelection == resultMap[item].toString) {
                theSelected = i;
            }
        }

    }

    if (theSelected > 0) {
        childList.selectedIndex = theSelected;
    }
    else {
        childList.selectedIndex = 0;
    }

    childList.disabled = false;

    if (childName == "Model") {
        carsSelectChange(document.getElementById('sel_model'));
    }

}

/*
function populateChildList(parentList, childList, childName, array1, array2)
{	
deleteOptions(childList);
	
if(parentList.selectedIndex <= 0)
{
childList.disabled = true;	
return;			
}
var parentIndex = parentList[parentList.selectedIndex].value;	
var subarray = array1[parentIndex.toString()];	
var previousSelection = '0';
var theSelected = -1;
	
if(g_isFirstChange) // check previous selction from before repost
{
var prev = document.getElementById('hdn' + childName);
if(prev != null)
{
previousSelection = prev.value.toString();
}
}

addOption(childList, 0, 'Select ' + childName + '...');

if(subarray != null) 
{
for(i=0;i<subarray.length;i++)
{
var subcategoryval =  subarray[i];
									
var subcategoryname = array2[subcategoryval.toString()];
			
addOption(childList,subcategoryval,subcategoryname);
			
if(previousSelection != '0' && previousSelection == subcategoryval.toString())
{
theSelected = i + 1;
}			
			
}
if(subarray.length == 1)
{
childList.selectedIndex = 1;
}
if(theSelected > 0)
{
childList.selectedIndex = theSelected;
}
		
childList.disabled = false;				
}
	
}
*/
function addOption(select, val, txt) {
    select.options[select.length] = new Option(txt, val);
}

function deleteOptions(targetlist) {
    if (targetlist != null) {
        targetlist.selectedIndex = -1;
        while (targetlist.length > 0) {
            targetlist[targetlist.length - 1] = null;

        }
    }
}

function enablesubmit() {
    if (document.getElementById('sub_getGS') != null)
        document.getElementById('sub_getGS').disabled = false;

}
function disablesubmit() {
    document.getElementById('sub_getGS').disabled = true;
}

function keyboardFormControl(e, el) {
    var keynum;

    if (window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }

    if (keynum == 13)//return
    {
        if (document.getElementById('sel_cat').selectedIndex != -1) {
            document.getElementById('ctgid').focus();
        }
        //enablesubmit();
        return false;
    }
    else if (keynum == 39)//right arrow
    {
        if (el.id == 'sel_cat') {
            document.getElementById('ctgid').focus();

        }
        else {
            //enablesubmit();
        }
        return false;
    }
    else if (keynum == 37)//left arrow
    {
        if (el.id == 'ctgid') {
            document.getElementById('sel_cat').focus();
            el.selectedIndex = -1;
            //disablesubmit();
        }
        return false;

    }
    return true;
}

function setCarMakeMode(selctgid) {
    var what = (selctgid == g_CARS_CATEGORY_ID ? 'Car' : 'Motorcycle');

    var categories_list = document.getElementById('categories_list');
    if (categories_list != null)
        categories_list.style.display = 'none';
    var cat_header_wrap = document.getElementById('cat_header_wrap');
    if (cat_header_wrap != null)
        cat_header_wrap.style.display = 'none';
    var choose_title = document.getElementById('choose_title');
    if (choose_title != null)
        choose_title.innerHTML = 'Select Your ' + what + ':';
    var subcategories_list = document.getElementById('subcategories_list');
    if (subcategories_list != null)
        subcategories_list.className = 'subcategories_list_cars';
    var categoy_selection = document.getElementById('categoy_selection');
    if (categoy_selection != null)
        categoy_selection.className = 'categoy_selection_cars';
}

function initSelectBox() {
    var mainSelect = document.getElementById('sel_cat');
    var theSelected = -1;
    var i = -1;

    var previousSelection = document.getElementById('hdnTopctgid').value;
    var isel = document.getElementById('hdnctgid').value;
    if (isel == "-1" || isel == "0") isel = "";
    for (var item in _g_c_c) {
        if (typeof (_g_ctg[item]) == 'string') {
            addOption(mainSelect, item, _g_ctg[item]);
            i++;

            if (previousSelection != "" && previousSelection == item) {
                theSelected = i;
            }
            else if (previousSelection == "" && isel != "") {

                if (gIsParent(isel, item)) {
                    theSelected = i;
                }
            }

        }
    }
    //mainSelect.focus();

    if (theSelected == -1) {
        g_isFirstChange = false;
    }
    else {
        mainSelect.selectedIndex = theSelected;
        updatelist(mainSelect);
        var selctgid = mainSelect[mainSelect.selectedIndex].value;

        if (previousSelection == "" && (selctgid == g_CARS_CATEGORY_ID || selctgid == g_MOTOS_CATEGORY_ID)) // not repost from choosing a category -> arrived with cars category from outside
        {
            if (document.getElementById('hdnMake').value != '0')// arrived with make
            {
                setCarMakeMode(selctgid);
            }
        }

    }
    /*
    if(isel != "" && isel != "0" && document.getElementById('hdnProdId').value == "")
    {
    openCategories();
    }
    */
    var hdnProdId = document.getElementById('hdnProdId');
    if (hdnProdId != null) {
        if (previousSelection != "" && (hdnProdId.value == "" || hdnProdId.value == "0")) {
            openCategories();
        }
    }
}

function gIsParent(v, V) {
    if (v == V) return true;
    var arr = _g_c_c[V.toString()];
    if (arr == null) return false;

    var i = 0, iL = arr.length;

    for (; i < iL; i++) {
        if (arr[i] == v)
            return true;
    }

    return false;
}



function openCategories() {
    var categoy_selection = document.getElementById('categoy_selection');
    if (categoy_selection != null) {
        categoy_selection.style.display = 'block';
    }
    var open_categories = document.getElementById('open_categories');
    if (open_categories != null) {
        open_categories.style.display = 'none';
    } 
    var inputsearch = document.getElementById('inputsearch');
    if (inputsearch != null) {
        inputsearch.value = '';
    }
    var hdnProdId = document.getElementById('hdnProdId');
    if (hdnProdId != null) {
        hdnProdId.value = '';
    }
    //disablesubmit();

    //if(document.getElementById('ctgid').selectedIndex != -1)enablesubmit();
}
function closeCategories() {
    var cs = document.getElementById('categoy_selection');
    var oc = document.getElementById('open_categories');

    if (cs != null) {
        cs.style.display = 'none';
    }
    if (oc != null) {
        oc.style.display = 'block';
    }

}

function noenter(ev) {
    var keynum;
    if (window.event) // IE
    {
        keynum = ev.keyCode;
    }
    else if (ev.which) // Netscape/Firefox/Opera
    {
        keynum = ev.which;
    }
    return !(keynum == 13);
}



/********************************

For SearchBox drop-down

*******************************/

AutoCompleteSearch.prototype = new AutoComplete();
AutoCompleteSearch.prototype.constructor = AutoCompleteSearch;
function AutoCompleteSearch(searchinput, resultsarea, category, resultswrap, prodid, brandid, urlprefix, eraseOnFocus, controlPrefix, searchforproducts) {
    this.Category = category;
    this.searchInput = searchinput;
    this.resultsArea = resultsarea;
    this.resultsWrap = resultswrap;
    this.prodId = prodid;
    this.brandId = brandid;
    this.urlPrefix = urlprefix;

	this.searchForProds = (0 == this.prodId && 0 == this.brandId && 0 == this.Category);
	if(typeof searchforproducts != 'undefined')
	{
		if(searchforproducts != null)
		{
			this.searchForProds = searchforproducts;
		}
	}
    

    this.overResultsw = false;
    this.optionsStartIndex = 2;
    this.selectedw = this.optionsStartIndex - 1;
    this.eraseOnFocus = eraseOnFocus;


    if (controlPrefix == undefined)
        controlPrefix = "";
    this.controlPrefix = controlPrefix;

    if (this.searchInput != null && this.resultsArea != null && this.resultsWrap != null) {
        this.init();
        this.initw();
    }
}

AutoCompleteSearch.prototype.initw = function() {
    var ac = this;
    var oldKD = this.searchInput.onkeydown;

    this.searchInput.onkeydown = function(ev) {
        ac.searchInput.style.color = 'black';
        if (!ev)
            ev = window.event;
        //setTimeout(function(){ac.completeTxt(ev)},1);      
        //return noenter(ev);
        return ac.completeTxt(ev);
    };
    this.searchInput.onblur = function(ev) {
        if (!ac.overResults && !ac.overResultsw) {
            ac.hideResults();
            ac.hideDropdown();
        }
    };

    this.resultsWrap.onmouseover = function(ev) {
        ac.overResultsw = true;
        return true;
    };
    this.resultsWrap.onmouseout = function(ev) {
        ac.overResultsw = false;
        return true;
    };
    var ac = this;
    for (var i = this.optionsStartIndex; i < this.resultsWrap.childNodes.length; i++) {
        var nodeObj = this.resultsWrap.childNodes[i];
        nodeObj.onmouseover = function() { ac.highlightw(this); };
        nodeObj.onclick = function() { ac.selectw(this); return false; };
    }
};
AutoCompleteSearch.prototype.showDropdown = function() {
    this.resultsWrap.className = "showresultsw";

    var ua = navigator.userAgent.toLowerCase();
    var isIE = (ua.indexOf("msie") != -1);

    if (isIE && false) {
        var prdnav = $('prdnav')
        if (null != prdnav) {
            prdnav.style.visibility = 'hidden';
        }
        var theadtop = $('theadtop')
        if (null != theadtop) {
            theadtop.style.zIndex = -1;
        }
        var indrss = $('indrss')
        if (null != indrss) {
            indrss.style.zIndex = -1;
        }
        var ifrm = $('google_ads_frame1');
        if (null != ifrm) {
            //ifrm.style.zIndex = -1;
            ifrm.style.display = 'none';
        }
    }

};
AutoCompleteSearch.prototype.hideDropdown = function() {
    this.resultsWrap.className = "noresultsw";

    var ua = navigator.userAgent.toLowerCase();
    var isIE = (ua.indexOf("msie") != -1);

    if (isIE) {
        var prdnav = $('prdnav')
        if (null != prdnav) {
            prdnav.style.visibility = 'visible';
        }
        var theadtop = $('theadtop')
        if (null != theadtop) {
            theadtop.style.zIndex = 0;
        }
        var indrss = $('indrss')
        if (null != indrss) {
            indrss.style.zIndex = 0;
        }
        var ifrm = $('google_ads_frame1');
        if (null != ifrm) {
            //ifrm.style.zIndex = 0;
            ifrm.style.display = 'block';
        }
    }
};
AutoCompleteSearch.prototype.showResults = function() {
    this.resultsArea.className = "showresults";

    var ttl = $i(this.controlPrefix + 'searchacdivtitle');
    if (ttl != null) {
        ttl.innerHTML = 'Choose a suggestion... or finish typing and press Enter';
    }
};
AutoCompleteSearch.prototype.isShowResults = function() {
    return this.resultsArea.className == "showresults";
};
AutoCompleteSearch.prototype.hideResults = function() {
    this.resultsArea.className = "noresults";
    this.selected = -1;
    this.overResults = false;

    var ttl = $i(this.controlPrefix + 'searchacdivtitle');
    if (ttl != null) {
        ttl.innerHTML = 'Search the entire site... or choose an option below';
    }

};

AutoCompleteSearch.prototype.UpdateClock = function() {
    var searched = this.searchInput.value;

    if (this.ClockID) {
        clearTimeout(this.ClockID);
        this.ClockID = 0;
    }
    if (searched.length >= this.minChars)//disregard less than 3 characters
    {
        this.showDropdown();
        if (this.lastSearchNone == false || searched.indexOf(this.saveSearched) == -1)//avoid searching addditions to a failed search
        {
            if (!this.getFromCache(searched))
                this.callback();
        }
    }
    else if (this.saveSearched.indexOf(searched) != 0 || searched.length == 0)//hide only if not first letters of last searched
    {
        this.hideDropdown();
        this.hideResults();
    }
};

AutoCompleteSearch.prototype.goUp = function() {
    var resultNodesw = this.resultsWrap.childNodes;

    if (resultNodesw.length > 0 && this.selectedw > this.optionsStartIndex) {
        var nodeObj = resultNodesw[--this.selectedw];
        this.highlightw(nodeObj);
    }
    else {
        if (resultNodesw.length > 0 && this.selectedw == this.optionsStartIndex && this.isShowResults()) {
            --this.selectedw;
        }
        var resultNodes = this.resultsArea.childNodes;
        if (resultNodes.length > 0 && this.selected > 0) {
            if (resultNodesw.length > 0 && this.selectedw > this.optionsStartIndex) {
                var nodeObj = resultNodesw[--this.selectedw];
                this.highlightw(nodeObj);
            }
            var nodeObj = resultNodes[--this.selected];
            this.highlight(nodeObj);
        }
    }
};
AutoCompleteSearch.prototype.goDown = function() {
    var resultNodes = this.resultsArea.childNodes;
    if (resultNodes.length > 0 && this.selected < resultNodes.length - 1) {
        var nodeObj = resultNodes[++this.selected];
        this.highlight(nodeObj);
    }
    else {
        var resultNodesw = this.resultsWrap.childNodes;
        if (resultNodes.length > 0 && this.selected == resultNodes.length - 1 && resultNodesw.length > this.optionsStartIndex) {
            ++this.selected;
        }

        if (resultNodesw.length > 0 && this.selectedw < resultNodesw.length - 1) {
            var nodeObj = resultNodesw[++this.selectedw];
            this.highlightw(nodeObj);
        }

    }
};

AutoCompleteSearch.prototype.highlight = function(resultNode) {
    for (var i = 0; i < this.resultsArea.childNodes.length; i++) {
        var nodeObj = this.resultsArea.childNodes[i];
        if (nodeObj == resultNode) {
            this.selected = i;
            nodeObj.className = "acselected";

        }
        else if (nodeObj.className == "acselected")
            nodeObj.className = "";
    }
    for (var i = this.optionsStartIndex; i < this.resultsWrap.childNodes.length; i++) {
        var nodeObj = this.resultsWrap.childNodes[i];

        if (nodeObj.className == "acselected")
            nodeObj.className = "";
    }
};
AutoCompleteSearch.prototype.highlightw = function(resultNode) {
    for (var i = this.optionsStartIndex; i < this.resultsWrap.childNodes.length; i++) {
        var nodeObj = this.resultsWrap.childNodes[i];
        if (nodeObj == resultNode && (i >= this.optionsStartIndex)) {
            this.selectedw = i;
            nodeObj.className = "acselected";

        }
        else if (nodeObj.className == "acselected")
            nodeObj.className = "";
    }
    for (var i = 0; i < this.resultsArea.childNodes.length; i++) {
        var nodeObj = this.resultsArea.childNodes[i];
        if (nodeObj.className == "acselected")
            nodeObj.className = "";
    }
};

AutoCompleteSearch.prototype.select = function(resultNode) {
    var name = "";
    /*
    if(typeof resultNode.firstChild.innerText != 'undefined')
    name = resultNode.firstChild.innerText;
    else
    name = resultNode.firstChild.text;
    */
    name = resultNode.firstChild.name;

    this.searchInput.value = name;
    //this.searchInput.disabled = true;
    /*
    var id = resultNode.id.substring(1);
    var hdnProdId = document.getElementById('hdnProdId');
    if(hdnProdId != null)
    {
    hdnProdId.value = id;
    }
    */
    //enablesubmit();

    this.hideResults();
    this.hideDropdown();

    logSearchEvent(5351);
    location.href = resultNode.firstChild.href;
    //this.submit();
};

AutoCompleteSearch.prototype.selectw = function(resultNode) {
    //alert(resultNode.id);
    this.hideResults();
    this.hideDropdown();
    var controlPrefix = this.controlPrefix;
    var ac = this;

    switch (resultNode.id.substring(controlPrefix.length)) {
        case 'searchweb':
            {
                //var target='http://www.google.com/search?q=' + escape(this.searchInput.value);
                var foo = function() {
					
                    logSearchEvent(5355);
					
                    SubmitGForm(controlPrefix);
                    /*
                    var tgt='http://www.google.com/cse?cx=partner-pub-8183356113384228:3nccpq-il5y&q=' + escape(ac.searchInput.value);
                    window.open(tgt,'google','height=600,width=800,toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes');
                    */
                };
                setTimeout(foo, 1);
                return false;
                break;
            }
        case 'searchfixyaweb':
            {
                var foo = function() {
                    //var target='http://www.google.com/search?q=site%3Afixya.com+' + escape(ac.searchInput.value);
                    var tgt = 'http://www.google.com/cse?cx=partner-pub-8183356113384228:3nccpq-il5y&q=site%3Afixya.com+' + escape(ac.searchInput.value);
                    window.open(tgt, 'google', 'height=600,width=800,toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes');
                };
                setTimeout(foo, 1);
                return false;
                break;
            }
        case 'searchsol':
            {
                if (_validSearch(controlPrefix)) {
                    var frm = $i(controlPrefix + 'frmSearch');
                    if (frm != null) {
                        logSearchEvent(5356);
                        frm.method = 'get';
                        frm.action = this.urlPrefix + 'SearchInGroup.aspx';
                        this.submit();
                    }
                }
                return false;
                break;
            }
        case 'searchprd':
            {
                if (_validSearch(controlPrefix)) {
                    var frm = $i(controlPrefix + 'frmSearch');
                    if (frm != null) {
                        logSearchEvent(5354);
                        frm.method = 'get';
                        frm.action = this.urlPrefix + 'ProductSearch.aspx';
                        this.submit();
                    }
                }
                return false;
                break;
            }
        case 'searchinprd':
            {
                if (_validSearch(controlPrefix)) {
                    var frm = $i(controlPrefix + 'frmSearch');
                    var hdn = $i(controlPrefix + 'hdncustom');
                    if (frm != null && hdn != null) {
                        logSearchEvent(5357);
                        frm.method = 'get';
                        frm.action = this.urlPrefix + 'InnerSearch.aspx';
                        hdn.name = 'prdid';
                        hdn.value = this.prodId;
                        this.submit();
                    }
                }
                return false;
                break;
            }
        case 'searchinbrd':
            {
                if (_validSearch(controlPrefix)) {
                    var frm = $i(controlPrefix + 'frmSearch');
                    var hdn = $i(controlPrefix + 'hdncustom');
                    if (frm != null && hdn != null) {
                        logSearchEvent(5358);
                        frm.method = 'get';
                        frm.action = this.urlPrefix + 'search.aspx';
                        hdn.name = 'brdid';
                        hdn.value = this.brandId;
                        this.submit();
                    }
                }
                return false;
                break;
            }
        case 'searchincat':
            {
                if (_validSearch(controlPrefix)) {
                    var frm = $i(controlPrefix + 'frmSearch');
                    var hdn = $i(controlPrefix + 'hdncustom');
                    if (frm != null && hdn != null) {
                        logSearchEvent(5358);
                        frm.method = 'get';
                        frm.action = this.urlPrefix + 'search.aspx';
                        hdn.name = 'ctgid';
                        hdn.value = this.Category;
                        this.submit();
                    }
                }
                return false;
                break;
            }
        case 'searchall':
            {
                if (_validSearch(controlPrefix)) {
                    var frm = $i(controlPrefix + 'frmSearch');
                    var hdn = $i(controlPrefix + 'hdncustom');
                    if (frm != null) {
                        logSearchEvent(5358);
                        frm.method = 'get';
                        frm.action = this.urlPrefix + 'search.aspx';
                        hdn.name = 'cstm';
                        hdn.value = '';
                        this.submit();
                    }
                }
                return false;
                break;
            }
    }

};

AutoCompleteSearch.prototype.submit = function() {
    var frm = $i(this.controlPrefix + 'frmSearch');

    if (frm != null) {
        frm.submit();
    }

}
AutoCompleteSearch.prototype.completeTxt = function(ev) {
    var keynum;
    var charMin = '0'.charCodeAt(0);
    var charMax = 'z'.charCodeAt(0);
    if (window.event) // IE
    {
        keynum = ev.keyCode;
    }
    else if (ev.which) // Netscape/Firefox/Opera
    {
        keynum = ev.which;
    }

    if ((charMin <= keynum && keynum <= charMax) || keynum == 32 || keynum == 8) {
        if (this.searchForProds) {
            this.KillClock();
            this.StartClock();
        }
        else {
            this.showDropdown();
        }
    }
    else {
        switch (keynum) {
            /*
            case 8: //backspace
            {	
            this.KillClock();
            var searched = this.searchInput.value;
            searched = searched.substring(0,searched.length-1);
            this.getFromCache(searched);
            break;    
            }
            */ 
            case 38: //up arrow
                this.goUp();
                break;
            case 40: //down arrow 
                this.goDown();
                break;
            case 13: //enter
                {
                    if (-1 == this.selected && (this.optionsStartIndex - 1) == this.selectedw) {
                        this.hideResults();
                        this.hideDropdown();
                        return true;
                    }
                    else {
                        if (this.selectedw >= this.optionsStartIndex) {
                            return (this.selectw(this.resultsWrap.childNodes[this.selectedw]));
                        }
                        else {
                            this.select(this.resultsArea.childNodes[this.selected]);
                            return false;
                        }

                    }
                    break;
                }
        }
    }
    return true;
};
AutoCompleteSearch.prototype.populateResults = function(resultsArray) {
    var i = 0;
    var ac = this;

    this.lastSearchNone = false;
    for (i = 0; i < resultsArray.length; i++) {
        thisId = resultsArray[i].id;
        newDiv = document.createElement("div");
        newA = document.createElement("a");

        newA.innerHTML = '>> ' + resultsArray[i].name; //.substring...
        newA.name = resultsArray[i].name;
        newA.href = resultsArray[i].url;
        newA.className = 'completeresult';
        newA.onclick = function() { return false; };

        newDiv.appendChild(newA);
        newDiv.id = 'o' + thisId;
        newDiv.onmouseover = function() { ac.highlight(this); };
        newDiv.onclick = function() { ac.select(this); return false; };

        this.resultsArea.appendChild(newDiv);
    }

    this.showResults();
};
// searchcomplete(category, prodid, brandid, UrlPrefix[,eraseOnFocus])
function searchcomplete(category, prodid, brandid, UrlPrefix, eraseOnFocus, controlPrefix) {
    if (controlPrefix == undefined || controlPrefix == true)
        controlPrefix = "";

    var inputsearch = document.getElementById(controlPrefix + 'txt');
    var resultarea = document.getElementById(controlPrefix + 'searchacdiv');
    var resultwrap = document.getElementById(controlPrefix + 'searchacdivw');
    var MyCompleterS = new AutoCompleteSearch(inputsearch, resultarea, category, resultwrap, prodid, brandid, UrlPrefix, eraseOnFocus, controlPrefix);

    if (arguments.length > 4)
        MyCompleterS.firstClick = !arguments[4];
}

function searchcompleteglobal(category, prodid, brandid, UrlPrefix, eraseOnFocus, controlPrefix, searchforproducts) {
    if (controlPrefix == undefined || controlPrefix == true)
        controlPrefix = "";

    var inputsearch = document.getElementById(controlPrefix + 'txt');
    var resultarea = document.getElementById(controlPrefix + 'searchacdiv');
    var resultwrap = document.getElementById(controlPrefix + 'searchacdivw');
    var MyCompleterS = new AutoCompleteSearch(inputsearch, resultarea, category, resultwrap, prodid, brandid, UrlPrefix, eraseOnFocus, controlPrefix, searchforproducts);

    if (arguments.length > 4)
        MyCompleterS.firstClick = !arguments[4];
}

function logSearchEvent(e) {
    if (typeof logEvent != 'undefined') {
        logEvent(e);
    }
}
/********************************

For RNR Search drop-down

*******************************/

AutoCompleteSearchRnr.prototype = new AutoCompleteSearch();
AutoCompleteSearchRnr.prototype.constructor = AutoCompleteSearchRnr;
function AutoCompleteSearchRnr(searchinput, resultsarea, category, resultswrap, prodid, brandid, urlprefix, eraseOnFocus, controlPrefix) {
    this.URL = 'http://' + document.location.host + '/rnr/auto_c_rnr.aspx';
    this.Category = category;
    this.searchInput = searchinput;
    this.resultsArea = resultsarea;
    this.resultsWrap = resultswrap;
    this.prodId = prodid;
    this.brandId = brandid;
    this.urlPrefix = urlprefix;

    this.searchForProds = (0 == this.prodId && 0 == this.brandId && 0 == this.Category);

    this.overResultsw = false;
    this.optionsStartIndex = 2;
    this.selectedw = this.optionsStartIndex - 1;
    this.controlPrefix = controlPrefix;
    if (this.searchInput != null && this.resultsArea != null && this.resultsWrap != null) {
        this.init();
        this.initw();
    }
}

function searchcompleteRnr(category, prodid, brandid, UrlPrefix, eraseOnFocus, controlPrefix) {

    if (controlPrefix == undefined || controlPrefix == true)
        controlPrefix = "";
        
    var inputsearch = document.getElementById('txt');
    var resultarea = document.getElementById('searchacdiv');
    var resultwrap = document.getElementById('searchacdivw');

    var MyCompleterS = new AutoCompleteSearchRnr(inputsearch, resultarea, category, resultwrap, prodid, brandid, UrlPrefix, eraseOnFocus, controlPrefix);
    if (arguments.length > 4)
        MyCompleterS.firstClick = !arguments[4];
}
