/**
 * Livesearch functionality for SDP Cataloger
 *
 * The function that you need to use from this file is livesearchUpdate() with
 * correct parameter values.
 *
 * In order to use the livesearch functionality, the xhtml code must look like
 * this:
 * <input id="searchInput" type="text" onkepress="return livesearchUpdate(event,
 *                                                                'order_product_name',
 *                                                                'search_li_',
 *                                                                'livesearch',
 *                                                                '?page=sdpcataloger/sdpcataloger_products_page&action=search',
 *                                                                order_item_searching,
 *                                                                order_item_received_result,
 *                                                                order_item_submit,
 *                                                                order_item_clear)" />
 * <div id="livesearch_1" class="livesearch"></div>
 *
 * Note that the action in '?page=sdpcataloger/sdpcataloger_products_page&action=search'
 * must return xhtml code that will be directly inserted in the empty div
 * with id "livesearch_1" in this example.
 */

var livesearchXmlHttp;

var livesearchLiPrefix = '';
var livesearchMenucontainerId = '';
var livesearchSearchingCb = '';
var livesearchResultReceivedCb = '';
var livesearchSubmitCb = '';
var livesearchClearCb = '';
var livesearchLiSelected = -1;


/**
 * Change the selected item in the livesearch results list
 *
 * @return true if the selection has been changed or false otherwise
 */
function livesearchChangeSelection(oldId, newId) {
	var liElement = document.getElementById(livesearchLiPrefix+newId);
    if (!liElement) return false;

    var oldLiElement = document.getElementById(livesearchLiPrefix+oldId);
    if (oldLiElement){
        oldLiElement.setAttribute("class", "");
        oldLiElement.style.backgroundColor = 'transparent';
    }
    liElement.setAttribute("class", "selected");
    liElement.style.backgroundColor = '#99c2c0';

	return true;
}

function livesearchClearResult(){
    var liElement = document.getElementById(livesearchMenucontainerId);
    if (liElement) {
        liElement.innerHTML = '';
    }
    livesearchLiSelected = -1;
}

/**
 *  Return the result of this function on the 'onkeypress' event of the search input box.
 *  Ex. onkeypress="return livesearchUpdate(...);"
 */
function livesearchUpdate(event, searchInputId, liPrefix, menuContainerId, searchUrl, searchingCb, resultReceivedCb, submitCb, clearCb){
    livesearchLiPrefix = liPrefix;
    livesearchMenucontainerId = menuContainerId;
    livesearchSearchingCb = searchingCb;
    livesearchResultReceivedCb = resultReceivedCb;
    livesearchSubmitCb = submitCb;
    livesearchClearCb = clearCb;

    var searchInput = document.getElementById(searchInputId);
    if (!searchInput) return true;

    var searchStr = searchInput.value;

    var keynum = (event.which) ? event.which : event.keyCode;
    var keychar = String.fromCharCode(keynum);

    // Since we're working at onkeydown we're one letter behind
    // so we need to manually append it if it's alphanumeric
    var alphanumtest = /[a-zA-Z0-9_\-\+]/;
    if (alphanumtest.test(keychar)){
        searchStr += keychar;
    }

    // Backspace
    if (keynum == 8) {
        if (searchStr.length > 0){
            searchStr = searchStr.substring(0, searchStr.length-1);
        }
    }

    // On empty string clear the search and stop
    if (searchStr.length == 0){
        if (clearCb){ clearCb(); }
        livesearchClearResult();
        return true;
    }

    menuContainer = document.getElementById(menuContainerId);
    if (!menuContainer) return true;

    // Handle arrow keys
    
	var offset = 0;
	if (keynum == 13){                     // Enter
        if (submitCb) { submitCb(); }
        
        // Trap the Enter key
        event.cancelBubble = true;
        event.returnValue = false;
        if (event.stopPropagation) event.stopPropagation();

        livesearchClearResult();
		return false;
	} else if (keynum == 27) {             // Escape
        if (clearCb){ clearCb(); }
        livesearchClearResult();
        return true;
	} else if (keynum == 40) {             // Down arrow
		offset = 1;
    } else if (keynum == 38) {             // Up arrow
        offset = -1;
	}

    if (offset != 0){
        oldlivesearchLiSelected = livesearchLiSelected;
        livesearchLiSelected += offset;

        if (livesearchChangeSelection(oldlivesearchLiSelected, livesearchLiSelected) == false){
            livesearchLiSelected -= offset;
        }
        return true;
    }
    livesearchLiSelected = -1;
    // End handle arrow keys. From here on, treat alphanumeric characters.

    livesearchXmlHttp= livesearchGetXmlHttpObject();

    // Check if the browser supports livesearch
    if (livesearchXmlHttp == null) {
        alert ("Browser does not support HTTP Request")
        return true;
    }

    // Build the query string
    var query = searchUrl + "&q=" + searchStr + "&sid=" + Math.random();

    // Make the call
    livesearchXmlHttp.onreadystatechange = livesearchResult;
    livesearchXmlHttp.open("GET",query,true);
    livesearchXmlHttp.send(null);
    if (livesearchSearchingCb) {
        livesearchSearchingCb();
    }

    return true;
}

function livesearchResult() {
    if (livesearchXmlHttp.readyState==4 || livesearchXmlHttp.readyState=="complete") {
         document.getElementById(livesearchMenucontainerId).innerHTML = livesearchXmlHttp.responseText;
         if (livesearchResultReceivedCb){
             livesearchResultReceivedCb();
         }
         // Reset selection index on successful retrieval
         livesearchLiSelected = -1;
    }
}

/**
 * @return the XML DOM object of the result. This means the result must be
 * an XML.
 */
function doSyncAjaxRequest(url){
    if (window.XMLHttpRequest) {
        xhttp=new XMLHttpRequest();
    } else // Internet Explorer 5/6
    {
        xhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET",url,false);
    xhttp.send("");
    xmlDoc=xhttp.responseXML;
    return xmlDoc;
}

function livesearchGetXmlHttpObject()
{
    var livesearchXmlHttp = null;
    try {
        // Firefox, Opera 8.0+, Safari
        livesearchXmlHttp = new XMLHttpRequest();
    } catch ( e ) {
        // Internet Explorer
        try {
            livesearchXmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch ( e ) {
            livesearchXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return livesearchXmlHttp;
}

function clickSelect(liClicked) {
    if (livesearchChangeSelection(livesearchLiSelected, liClicked) != false){
		livesearchLiSelected = liClicked;
	}

    if (livesearchLiSelected > -1) {
        if (livesearchSubmitCb) { livesearchSubmitCb(); }
    }

    livesearchClearResult();
    return false;
}

/* Relation drop-down */
function checkNewName(selObj){
    index = selObj.selectedIndex;
    if (selObj.options[index].value == "0") {
        document.getElementById('new_relation_name').style.display = 'inline';
    } else {
        document.getElementById('new_relation_name').style.display = 'none';
    }
}

