///////////////////////////////////
/// INPUT SUGGESTION FUNCTIONS ////
///////////////////////////////////
var previous_value  = null;
var searching       = null;

function searchPapers() {
    if (searching!=null) {
        clearTimeout(searching);
    }

    searching = setTimeout("preformAJAXSearch();", 600);
}

function preformAJAXSearch() {
    sendRequest('ajax_select_search.php', 'm=search', 'papersSearched', 'GET', 'An error occured while trying to preform search. Please inform admin staff.')
}

function papersSearched(request){
    var num_papers  = request.responseXML.getElementsByTagName('elements')[0].firstChild.data;
    var select      = document.getElementById('paper_name');

    while (select.options.length > 0) {
        select.options[0] = null;
    }

    for (i=0; i<num_papers; i++){
        paper_name  = request.responseXML.getElementsByTagName('paper_name')[i].firstChild.data;
        paper_id    = request.responseXML.getElementsByTagName('paper_id')[i].firstChild.data;
        paper_title = request.responseXML.getElementsByTagName('paper_title')[i].firstChild.data;
        market_code = request.responseXML.getElementsByTagName('market_code')[i].firstChild.data;
        paper_price = request.responseXML.getElementsByTagName('paper_price')[i].firstChild.data;
        currency    = request.responseXML.getElementsByTagName('currency')[i].firstChild.data;

        var option  = document.createElement("option");
        option.text = market_code+' - '+paper_name+' ('+paper_title+')';

        option.title    = currency;
        option.className= paper_price;
        option.value    = paper_id;

        try{
            //standards compliant; doesnt work in IE
            select.add(option, null);
        }catch(ex){
            //IE only
            select.add(option);
        }

        if (i == 0){
            setSelectedIndex(select, paper_id);
        }
    }
}

function setSelectedIndex(list, value){
    for (var intI = 0; intI < list.options.length; intI++) {
        if (list.options[intI].value == value) {
            list.options[intI].selected = true;
        }
    }
}

function setCurrencyAndCalculatePaperValue(){
    var select              = document.getElementById('paper_name');
    document.getElementById('currency').value = select.options[select.selectedIndex].title;

    var portfeil_price      = document.getElementById('portfeil_price');
    portfeil_price.value    = 0;

    var quantity            = document.getElementById('quantity');
    quantity                = quantity.value;

    if (quantity == "" || quantity < 0){
        quantity = 1;
        document.getElementById('quantity').value = 1;
    }

    var paper_price         = select.options[select.selectedIndex].className;
    portfeil_price.value    = parseFloat(quantity)*parseFloat(paper_price);
}
