var oSuggestionsDiv = null;
var bSuggestionArrowNext = false;
var bSuggestionArrowPrev = false;
var strSuggestionLastWriten = null;
var iSuggestionSelectedRowIndex = null;

function hwCallback() {}
hwCallback.prototype = {

    result_error_display: function(warningText) {
        showHide_page_element("loading_img_sManufSupp","none");
        showHide_page_element("loading_img_Categories","none");
        showHide_page_element("loading_img_undergroups","none");
        showHide_page_element("loading_img_identicalGroups","none");
        showHide_page_element("loading_img_undergroupFeatures","none");

        showHide_page_element("div_manufacturers_container","block");
        showHide_page_element("div_Categories_container","block");
        showHide_page_element("div_undergroups_container","block");
        showHide_page_element("div_identicalGroups_container","block");
        showHide_page_element("div_undergroupFeatures_container","block");

        alert(warningText);
    },

    set_manufacturers_list: function(arrayManufacurers) {

        if(typeof(arrayManufacurers) == "string") {
            this.result_error_display(arrayManufacurers);
            return -1;
        }

        var index = 1;
        var index2 = 0;
        var licznik = 0;
        var manSupp= document.forms["form_group_features"]["sManufSupp"];

        for (prop in arrayManufacurers) {
            if(prop == '______array') { continue; }
            licznik++;
        }licznik++;

        manSupp.options.length = 1;
        manSupp.options.length = licznik;
        
        wbManSupp = 0;
        var optGroupForFilter = null;
        var optGroupForFilterIndex = null;
        for (var prop in arrayManufacurers) {
            if(prop == '______array') { continue; }
            
            if(prop == -1) { // index -1 oznacza że to optGroup
                manSupp.options[index] = new Option(arrayManufacurers[prop], prop);
                manSupp.options[index].style.fontWeight = 'bold';
                manSupp.options[index].style.fontStyle = 'italic';
                optGroupForFilterIndex = index;
            }else{
                manSupp.options[index] = new Option(arrayManufacurers[prop], prop);
            }
            if (prop == CHECKED_JS_MANUFACTURER_SUPPLIER) {
                manSupp.options[index].selected = true;
            }
            index++;
        }
                
        showHide_page_element("loading_img_sManufSupp","none");
        showHide_page_element("div_manufacturers_container","block");
    },
    
    set_categories_list: function(groupsList) {
        
        if(typeof(groupsList) == "string") {
            this.result_error_display(groupsList);
            return -1;
        }

        showHide_page_element("loading_img_Categories","none");
        showHide_page_element("div_Categories_container","block");

        select_displayCat(groupsList,'form_group_features','GR','UGR','IGR');
        remoteHW_advSearch.set_subcategories_list(CHECKED_JS_GROUP,CHECKED_JS_MANUFACTURER_SUPPLIER);
    },
    
    set_subcategories_list: function(subCategories) {
    
        if(typeof(subCategories) == "string") {
            this.result_error_display(subCategories);
            return -1;
        }

        showHide_page_element("loading_img_undergroups","none");
        showHide_page_element("div_undergroups_container","block");

        select_display_sCat(subCategories,'form_group_features','UGR','IGR');
        do_set_identical_groups_list_by_manufacturer();
    },
    
    set_identical_groups_list_by_manufacturer: function(array_identicalGroups) {
    
        if(typeof(array_identicalGroups) == "string") {
            this.result_error_display(array_identicalGroups);
            return -1;
        }

        select_grupyIdentyczne(array_identicalGroups,'form_group_features','UGR','IGR');

        showHide_page_element("loading_img_identicalGroups","none");
        showHide_page_element("div_identicalGroups_container","block");
    },

    
    set_undergroup_features_list: function(featuresList) {

        if(typeof(featuresList) == "string") {
            this.result_error_display(featuresList);
            return -1;
        }
        // PAGE_LANGUAGE - Zmienna globalna, w której 
        // przechowywana jest informacja co do aktualnego języka strony

        var tabHeadersExists = false;
        var tabFootExists = false;
        if(theTable_FEATURES_Body != null) {
            clearTable(theTable_FEATURES_Body, tabHeadersExists, tabFootExists);
        }
        
        var apRow = new Array();
        if (typeof(featuresList.info) == "string") {
            apRow.push('<b class="miniWarning">' + featuresList.info + '</b>'); 
            appendRow(theTable_FEATURES_Body, apRow);

            // Ustawienie parametrów wizualnych tabeli
            features_HTML_Table_style(theTable_FEATURES_Body,true);

            showHide_page_element("loading_img_undergroupFeatures","none");
            showHide_page_element("div_undergroupFeatures_container","block");
            return -1;
        }
        
        for (var ii = 0; ii < featuresList.length; ii++) {
            
            var id_feature = featuresList[ii]["ID_FEATURE"];
               
            if(featuresList[ii]["FEATURES_VALUES"].length == 0) {
                continue;
            }
                 
            var select_feature = '';
            var checked_feature = '';
            var oSearchForm = document.form_group_features;
            select_feature = '<select name="s_features_'+id_feature+'" style="width:auto;" name="select_feature_value" onchange="check_feature_for_search(this.form,this,'+id_feature+'); do_feature_selecting(this.form,this,'+id_feature+');">';
            select_feature+= '<option value="-1">--</option>';
            
            for(var jj = 0; jj < featuresList[ii]["FEATURES_VALUES"].length; jj++) {
                
                /* Żeby można było rozpoznac z jakich kolumn
                   s± warto¶ci wprowadzono skrótowe oznaczenia: 
                   int - feature_value_int;
                   flt - feature_value_float;
                   plt - feature_value_text_pl;
                   ent - feature_value_text_en; */
                var feature_value = "";
                var feature_value_innerHTML = "";
                var features_values = featuresList[ii]["FEATURES_VALUES"][jj];
                if (features_values["FEATURE_VALUE_INT"] != 0) {
                    feature_value_innerHTML = features_values["FEATURE_VALUE_INT"];
                    feature_value = 'int_' + features_values["FEATURE_VALUE_INT"];
                }   
                else if (features_values["FEATURE_VALUE_FLOAT"] != 0) {
                    feature_value_innerHTML = features_values["FEATURE_VALUE_FLOAT"];
                    feature_value = 'flt_'+features_values["FEATURE_VALUE_FLOAT"];
                }                                                  
                else if (features_values["FEATURE_VALUE_TEXT"] != 0) {
                    if (PAGE_LANGUAGE == 'PL') {
                        feature_value_innerHTML = features_values["FEATURE_VALUE_PL"];
                    }
                    else if (PAGE_LANGUAGE == 'UK') {
                        feature_value_innerHTML = features_values["FEATURE_VALUE_EN"];
                    }
                    feature_value = 'txt_'+features_values["FEATURE_VALUE_TEXT"];
                }else{
                    continue;
                }
                
                var selected = "";
                var IS_PRESENT = false;
                var SELECTED_FEATURE_VALUE = '';
                for(prop in SELECTED_FEATURES_ARRAY) {
                    if(SELECTED_FEATURES_ARRAY[prop][0] == id_feature) {
                        SELECTED_FEATURE_VALUE = SELECTED_FEATURES_ARRAY[prop][1];
                        IS_PRESENT = true;
                        break;
                    }
                }

                if (JS_Undergroup_features.length > 0) {

                    if (!IS_PRESENT && JS_Undergroup_features[id_feature] == feature_value) {
                        selected = 'selected="selected"';
                        checked_feature = 'checked';
                        oSearchForm.elements['s_features_'+id_feature]
                    }
                }
                if (IS_PRESENT && SELECTED_FEATURE_VALUE == feature_value) {
                    selected = 'selected="selected"';
                    checked_feature = 'checked';
                }

                select_feature+= '<option title="'+feature_value_innerHTML+'" value="'+feature_value+'" '+selected+'}>&nbsp;'+feature_value_innerHTML+'&nbsp;['+features_values["PROD_WITH_VALUE"]+']</option>';
            }
            select_feature+= '</select>';
            
            var features_checkbox = '';
            features_checkbox = '<input type="checkbox" disabled="disabled" '+checked_feature+' name="ch_for_search_'+id_feature+'" value="'+id_feature+'" />';
            
            var feature_name = "";
            if (PAGE_LANGUAGE == 'PL') {
                feature_name = featuresList[ii]["FEATURE_NAME_PL"];
            }
            else if (PAGE_LANGUAGE == 'UK') {
                feature_name = featuresList[ii]["FEATURE_NAME_EN"];
            }
            
            apRow.push(select_feature); 
            apRow.push(features_checkbox); 
            apRow.push(feature_name); 
            
            var whichFeature = ii + 1;
            if(whichFeature != 1 && whichFeature % 3 == 0) {
                appendRow(theTable_FEATURES_Body, apRow);
                var apRow = new Array();
            }
        }
        var whichFeature = ii;
        if(whichFeature % 3 != 0) {
            appendRow(theTable_FEATURES_Body, apRow);
        }
        
        // Ustawienie parametrów wizualnych tabeli
        features_HTML_Table_style(theTable_FEATURES_Body);
        
        if(featuresList.length > 0) {
            document.getElementById("table-features-list").style.display = "block";
        }else{
            document.getElementById("table-features-list").style.display = "none";
        }
        
        showHide_page_element("loading_img_undergroupFeatures","none");
        showHide_page_element("div_undergroupFeatures_container","block");
    },
    
    get_suggestions: function(suggestionsList) {
        if(typeof(suggestionsList) == "string") {
            this.result_error_display(suggestionsList);
            return -1;
        }
        var oBaseKeywordsSearch = document.getElementById('base_keywords_search');
        var aElemXY = YAHOO.util.Dom.getXY(oBaseKeywordsSearch);
        
        if(oSuggestionsDiv === null) {
        
            oSuggestionsDiv = document.createElement('div');
            oSuggestionsDiv.id = 'div-suggestions-list';
            oSuggestionsDiv.style.position = 'absolute';
            oSuggestionsDiv.style.left = aElemXY[0]+'px';
            oSuggestionsDiv.style.top = (aElemXY[1]+18)+'px';
            oSuggestionsDiv.style.width = oBaseKeywordsSearch.clientWidth+'px';
            oSuggestionsDiv.style.zIndex = 1000;
            document.body.appendChild(oSuggestionsDiv);
        }
        
        if(suggestionsList.length == 0) {
            oSuggestionsDiv.innerHTML = '';
            oSuggestionsDiv.style.display = 'none';
            return false;
        }else{
            var strContent = '<table id="search-suggestions-table" cellspacing="0">';
            for(prop in suggestionsList) {
                //alert('aElemXY: '+aElemXY[0]+' '+aElemXY[1]);
                strContent += '<tr onmouseover="setSelectedRowForSuggestions(null);resetSelectedRowForSuggestions();this.className = \'row-selected\';" onmouseout="this.className = \'\';" onclick="selectSuggestion(\''+escape(suggestionsList[prop])+'\')"><td>'+suggestionsList[prop]+'</td></tr>';
            }
            strContent += '<tr><td style="text-align:right;"><a class="normal" href="javascript: //nop;" onclick="closeSuggestionsDiv();">'+__oPCT_LANG.CLOSE+'</a></td></tr>';
            strContent += '</table>';
            oSuggestionsDiv.innerHTML = strContent;
            oSuggestionsDiv.style.display = 'block';
        }
    }
}

// Utworzenie obiektu zdalnego ***************************
var ohwCallback = new hwCallback();
var remoteHW_advSearch = new documentcallback(ohwCallback);


function closeSuggestionsDiv() {
    var oDiv = document.getElementById('div-suggestions-list');
    if(oDiv !== null) {
        document.getElementById('div-suggestions-list').style.display = 'none';
    }
}
function do_get_suggestions(strText, e, keyCode) {
    if(e != undefined) {
        if(e.keyCode != 38 && e.keyCode != 40) {
            strSuggestionLastWriten = document.getElementById('base_keywords_search').value;
            resetSelectedRowForSuggestions();
        }else{
            bSuggestionArrowNext = (e.keyCode == 40) ? true : false;
            bSuggestionArrowPrev = (e.keyCode == 38) ? true : false;
            suggestionsDivNavigate();
            return false;
        }
    }
    if(!check_AJAX_State(remoteHW_advSearch, "do_get_suggestions('"+strText+"')")) {
        return false;
    }
    remoteHW_advSearch.get_suggestions(strText,document.getElementById('search_select_type').value);
}
function suggestionsDivNavigate() {
    // Dalsze operacje mają sens tylko wtedy gdy ten div jest widoczny        
    if(oSuggestionsDiv.style.display == 'block') {
        var oSearchSuggestionsTable = document.getElementById('search-suggestions-table');
        if(iSuggestionSelectedRowIndex === null && bSuggestionArrowNext) {
            iSuggestionSelectedRowIndex = 0;
        }
        else if(iSuggestionSelectedRowIndex === null && bSuggestionArrowPrev) {
            iSuggestionSelectedRowIndex = (oSearchSuggestionsTable.rows.length - 2);
        }
        else if(iSuggestionSelectedRowIndex !== null) {
            if(bSuggestionArrowNext) {
                iSuggestionSelectedRowIndex++;
                if(iSuggestionSelectedRowIndex > (oSearchSuggestionsTable.rows.length - 2)) {
                    iSuggestionSelectedRowIndex = null;  // jeśli wyszliśmy poza tabele to wracamy do punktu wyjściowego
                }
            }
            else if(bSuggestionArrowPrev) {
                if(iSuggestionSelectedRowIndex > 0) {
                    iSuggestionSelectedRowIndex--;
                }else{
                    iSuggestionSelectedRowIndex = null;
                }
            }
        }
        setSelectedRowForSuggestions(iSuggestionSelectedRowIndex);
    }else{
        return false;
    }
}
function selectSuggestion(strSuggestion) {
    var oBaseKeywordsSearch = document.getElementById('base_keywords_search');
    oBaseKeywordsSearch.value = unescape(strSuggestion);
    oSuggestionsDiv.style.display = 'none';
    
    document.getElementById('main_search_button').click();
}
function setSelectedRowForSuggestions(rowIndex) {
    var oBaseKeywordsSearch = document.getElementById('base_keywords_search');
    var oSearchSuggestionsTable = document.getElementById('search-suggestions-table');
    for(var ii = 0; ii < oSearchSuggestionsTable.rows.length; ii++) {
        oSearchSuggestionsTable.rows[ii].className = '';    // 'zerujemy' wszystkie wiersze jeżeli chodzi o styl
        if(ii == rowIndex) {
            oSearchSuggestionsTable.rows[ii].className = 'row-selected';
            oBaseKeywordsSearch.value = oSearchSuggestionsTable.rows[ii].cells[0].innerHTML;
        }
    }
    if(rowIndex === null) {
        oBaseKeywordsSearch.value = strSuggestionLastWriten;
    }
}
function resetSelectedRowForSuggestions() {
    bSuggestionArrowNext = false;
    bSuggestionArrowPrev = false;
    iSuggestionSelectedRowIndex = null;
}

function do_set_manufacturers_list(groupNumber) {
    if(!check_AJAX_State(remoteHW_advSearch, "do_set_manufacturers_list("+groupNumber+")")) {
        return false;
    }

    CHECKED_JS_GROUP = groupNumber;
    var subCategories = new Array();
    if(parseInt(groupNumber) > 0) {
        subCategories = JS_grStruct[groupNumber].aUGR;
    }
    
    showHide_page_element("loading_img_sManufSupp","block");
    showHide_page_element("div_manufacturers_container","none");
    remoteHW_advSearch.set_manufacturers_list(groupNumber);
    
    if(theTable_FEATURES_Body != null) {
        // Czyszczenie i ukrywanie bloku pokazującego cechy produktów
        clearTable(theTable_FEATURES_Body, false, false);
    }
    document.getElementById("table-features-list").style.display = "none";

    if(CHECKED_JS_MANUFACTURER_SUPPLIER != 0){
        do_set_subcategories_list_by_manufacturer();
    }else{
        select_display_sCat(subCategories,'form_group_features','UGR','IGR');
    }
}

function do_set_categories_list(manufSupp_number) {
    if(!check_AJAX_State(remoteHW_advSearch, "do_set_categories_list("+manufSupp_number+")")) {
        return false;
    }

    if(theTable_FEATURES_Body != null) {
        // Czyszczenie i ukrywanie bloku pokazującego cechy produktów
        clearTable(theTable_FEATURES_Body, false, false);
    }
    document.getElementById("table-features-list").style.display = "none";

    CHECKED_JS_MANUFACTURER_SUPPLIER = manufSupp_number;

    showHide_page_element("loading_img_Categories","block");
    showHide_page_element("loading_img_undergroups","block");
    showHide_page_element("loading_img_identicalGroups","block");

    showHide_page_element("div_Categories_container","none");
    showHide_page_element("div_undergroups_container","none");
    showHide_page_element("div_identicalGroups_container","none");

    remoteHW_advSearch.set_categories_list(manufSupp_number);
}

function do_set_subcategories_list_by_manufacturer() {
    if(!check_AJAX_State(remoteHW_advSearch, "do_set_subcategories_list_by_manufacturer()")) {
        return false;
    }

    showHide_page_element("loading_img_undergroups","block");
    showHide_page_element("loading_img_identicalGroups","block");

    showHide_page_element("div_undergroups_container","none");
    showHide_page_element("div_identicalGroups_container","none");

    remoteHW_advSearch.set_subcategories_list(CHECKED_JS_GROUP,CHECKED_JS_MANUFACTURER_SUPPLIER);
}


function do_set_identical_groups_list_by_manufacturer() {
    if(!check_AJAX_State(remoteHW_advSearch, "do_set_identical_groups_list_by_manufacturer()")) {
        return false;
    }

    showHide_page_element("loading_img_identicalGroups","block");
    showHide_page_element("div_identicalGroups_container","none");
    remoteHW_advSearch.set_identical_groups_list_by_manufacturer(CHECKED_JS_UNDERGROUP,CHECKED_JS_MANUFACTURER_SUPPLIER);
}

function do_set_identicalGroups_list(grNo, ugrNo) {
    if(!check_AJAX_State(remoteHW_advSearch, "do_set_identicalGroups_list("+grNo+","+ugrNo+")")) {
        return false;
    }

    CHECKED_JS_UNDERGROUP = ugrNo;
    
    if(CHECKED_JS_MANUFACTURER_SUPPLIER != 0) {
        do_set_identical_groups_list_by_manufacturer();
    }else{
        var aTempIGR = new Array();
        if(grNo !== 0 && ugrNo !== 0) {
            aTempIGR = JS_grStruct[grNo].aUGR[ugrNo].aIGR;
        }
        select_grupyIdentyczne(aTempIGR,'form_group_features','UGR','IGR');
    }
    do_set_undergroup_features_list(ugrNo)
}

function do_set_undergroup_features_list(undergroupNumber) {
    if(!check_AJAX_State(remoteHW_advSearch, "do_set_undergroup_features_list("+undergroupNumber+")")) {
        return false;
    }

    showHide_page_element("loading_img_undergroupFeatures","block");
    showHide_page_element("div_undergroupFeatures_container","none");
    remoteHW_advSearch.set_undergroup_features_list(undergroupNumber, CHECKED_JS_MANUFACTURER_SUPPLIER, SELECTED_FEATURES_ARRAY);
}


function do_feature_selecting(oForm, oSelect, id_feature) {
    var oUGR = oForm.UGR;

    showHide_page_element("loading_img_undergroupFeatures","block");
    showHide_page_element("div_undergroupFeatures_container","none");
    
    var is_present = false;
    for(prop in SELECTED_FEATURES_ARRAY) {
        if(SELECTED_FEATURES_ARRAY[prop][0] == id_feature) {
            is_present = true;
            SELECTED_FEATURES_ARRAY[prop][1] = oSelect.options[oSelect.selectedIndex].value;
            break;
        }
    }
    if(!is_present) {
        SELECTED_FEATURES_ARRAY.push(new Array(id_feature, oSelect.options[oSelect.selectedIndex].value));
    }
    remoteHW_advSearch.set_undergroup_features_list(oUGR.options[oUGR.selectedIndex].value, CHECKED_JS_MANUFACTURER_SUPPLIER, SELECTED_FEATURES_ARRAY);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Funkcje do obsługi formularza wyszukiwania zaawansowanego //////////////////////////////////////
function select_displayCat(aKategorie,formName,selectGroupName,selectUndergroupName,selectIdentGroupName){
    var index = 1;
    var licznik = 0;
    var katSel = document.forms[formName][selectGroupName];
    
    if(selectUndergroupName != null) {
        var pkatSel= document.forms[formName][selectUndergroupName];
        var iKatSel= document.forms[formName][selectIdentGroupName];
        pkatSel.options.length = 1;
        iKatSel.options.length = 1;
    }

    katSel.options.length = 1;
    for (var prop in aKategorie) {
        if(prop == '______array') { continue; }
        katSel.options[index] = new Option(aKategorie[prop].GRName + ' [' + aKategorie[prop].inGR + ']', prop);
        if (prop == CHECKED_JS_GROUP) {
            katSel.options[index].selected = true;
        }
        index++;
    }
}

function select_display_sCat(subCategories,formName,selectUndergroupName,selectIdentGroupName){
    var index = 1;
    var pkatSel= document.forms[formName][selectUndergroupName];
    var iKatSel= document.forms[formName][selectIdentGroupName];

    pkatSel.options.length = 1;
    iKatSel.options.length = 1;

    if(CHECKED_JS_GROUP == 0) {
        do_set_identicalGroups_list(0, 0);
        return -1;
    }
    
    pkatSel.options.length = 1;
    for (prop in subCategories) {
        pkatSel.options[index] = new Option(subCategories[prop].UGRName + ' [' + subCategories[prop].inUGR + ']', prop);
        if (prop == CHECKED_JS_UNDERGROUP) {
            pkatSel.options[index].selected = true;
            do_set_identicalGroups_list(CHECKED_JS_GROUP, CHECKED_JS_UNDERGROUP)
        }
        index++;
    }
}

function select_grupyIdentyczne(array_identicalGroups,form,selectUndergroupName,selectIdentGroupName) {

    SELECTED_FEATURES_ARRAY = new Array();
    var lista1 = document.forms[form][selectUndergroupName];
    var lista2 = document.forms[form][selectIdentGroupName];

    lista2.options.length = 1;
    if(lista1.selectedIndex == 0 || lista1.selectedIndex == -1) {
        return -1;
    }

    var index = 1;
    for (prop in array_identicalGroups) {
        //if(array_identicalGroups[prop][1] == 0) { continue; }
        lista2.options[index] = new Option(array_identicalGroups[prop].IGRName + ' [' + array_identicalGroups[prop].inIGR + ']', prop);
        if (prop == CHECKED_JS_IDENTICAL_GROUP) {
            lista2.options[index].selected = true;
        }
        index++;
    }
}


function features_HTML_Table_style(tableBody,no_features) {

    if(no_features) {
        tableBody.rows[0].cells[0].style.height = "40px";
        tableBody.rows[0].cells[0].style.textAlign = "center";
        tableBody.rows[0].cells[0].style.verticalAlign = "middle";
        return -1;
    }

    for (var i = 0; i < tableBody.rows.length; i++) {
        for (var j = 0; j < tableBody.rows[i].cells.length; j++) {
            tableBody.rows[i].cells[j].style.verticalAlign = "bottom"
            // more statements working with the cell
            if(j == 0 || j == 3 || j == 6) { 
                tableBody.rows[i].cells[j].style.width = "14%" 
                tableBody.rows[i].cells[j].style.textAlign = "right" 
            }
            else if (j == 1 || j == 4 || j == 7) {
                tableBody.rows[i].cells[j].style.width = "4%" 
                tableBody.rows[i].cells[j].style.textAlign = "center";
            }
            else if (j == 2 || j == 5 || j == 8) {
                if(j == 2 || j == 5) {
                    tableBody.rows[i].cells[j].style.width = "15%" 
                }else{
                    tableBody.rows[i].cells[j].style.width = "16%" 
                }
                tableBody.rows[i].cells[j].style.textAlign = "left";
                tableBody.rows[i].cells[j].style.fontStyle = "italic";
                
                var cell_innerHTML = tableBody.rows[i].cells[j].innerHTML;
                if ((i == 0 && tableBody.rows[i].cells.length < 9 && cell_innerHTML.length <= 200) || cell_innerHTML.length <= 20) {
                    tableBody.rows[i].cells[j].style.whiteSpace = "nowrap";
                }else{
                    tableBody.rows[i].cells[j].style.whiteSpace = "normal";
                }
            }
        }
    }
}

