/**
* This file will be included by output/default/utils.js
*/

/**
* @var integer nAjaxTransfers	Number of active AJAX requests at this time
*/
var nAjaxTransfers = 0;

/**
* It is an array of URLs AJAX has requested yet.
* Keys= 	DIV IDs
* Values= 	URLS
* @var array arrDivUrls
*/
var arrDivUrls = new Array();

function showdiv(myid)
{
	document.getElementById("details"+myid).style["visibility"]="visible";
	document.getElementById("details"+myid).style["width"]="468px";
	document.getElementById("details"+myid).style["padding"]="5px";
	document.getElementById("details"+myid).style["border"]="1px solid #AAAAAA";
}

function closediv(myid)
{
	document.getElementById("details"+myid).style["visibility"]="hidden";
}

function ajaxLoad(strDiv, strQuery, strJSFunction) {
    ajaxLoad(strDiv, strQuery, strJSFunction, false);
}

/**
* Request a HTML section and put it into a DIV.
* During active AJAX requests show the DIV with id="div_transfergif".
*
* @param String strDiv			ID of the DIV, where you want to put the HTML response into
* @param String strQuery		URL parameters. You request allways the index.php
* @param String strJSFunction	JS function, which should be called afterwards
* @param String showErrMsg		Show alerts in case of errors?
*/
function ajaxLoad(strDiv, strQuery, strJSFunction, showErrMsg) {
    try {
        var divDebug = document.getElementById("debuglineLog");
        var req = (window.XMLHttpRequest)
                        ? new XMLHttpRequest():
                          ((window.ActiveXObject)
                            ?new ActiveXObject("Microsoft.XMLHTTP"):false);
        // alert(strQuery.replace(/&/, " ").replace(/&/, " ").replace(/&/, " ").replace(/&/, " "));
        arrDivUrls[strDiv] = strQuery;
        echo("ajaxLoad URL: filedetail.php");
    	echo("ajaxLoad("+strDiv+","+(strQuery.length<250? strQuery: strQuery.substr(0,250) +"...")+")");
        req.open("POST","filedetail.php", true);
        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        req.setRequestHeader("Content-length", strQuery.length);
        req.setRequestHeader("Connection", "close");
        req.onreadystatechange = function() {
            if (req.readyState==4) {
                if (req.status==200 || req.statusText=="OK") {
                    if (document.getElementById(strDiv) && document.getElementById(strDiv).innerHTML != null) {
                        var nDebugPos = req.responseText.indexOf("<div name='ajaxDebug'>");
                        var nErrPos = req.responseText.indexOf("<div name='ajaxError'>");
                        if (nDebugPos>0) {
                            echo(req.responseText.substr(nDebugPos));
                            document.getElementById(strDiv).innerHTML = req.responseText.substr(0, nDebugPos);
                            if (divDebug && nErrPos>0) alert(req.responseText.substr(nErrPos));
                        } else document.getElementById(strDiv).innerHTML = req.responseText;
                    } else {
                        if (showErrMsg) alert ("bad div " + strDiv);
                    }
                    nAjaxTransfers -= 1;
                    if (nAjaxTransfers==0) document.getElementById("div_transfergif").style.visibility="hidden";
                    if (strJSFunction) {setTimeout(strJSFunction, 10);}

                } else {
                    if(showErrMsg) alert ("error"+req.statusText);
                }
            }
        }
        req.send(strQuery);
        nAjaxTransfers += 1;
        if (nAjaxTransfers==1) document.getElementById("div_transfergif").style.visibility="visible";
    } catch (e) { alert("ajaxLoad:"+e); }
}
function echo(txt) {
    var divDebug = document.getElementById("debuglineLog");
	if (divDebug) {
	    divDebug.innerHTML += txt+"<BR />";
	};
}

/**
 * This function returns the values of a select box.
 * If select box is a multi select box, then return the values as comma separated values.
 * If fOnlySelected is true, then return all option values.
 * @param Element el				Select box element
 * @param boolean fOnlySelected		true: return only selected option only, false: return all option values
 * @return String Comma separated option values.
 */
function selBoxValues(el, fOnlySelected) {
    if (fOnlySelected==null) fOnlySelected = true;
    if (typeof(el)=="string") {
        var arr = document.getElementsByName(el);
        if (arr && arr.length==1) {elObj = arr[0];}
        else {
            elObj = document.getElementById(el);
            if (!elObj) alert(el + " not found");
        }
    } else elObj = el;
    if (elObj==null) return alert("wrong selBoxValues(el="+el+", "+elObj+")");

    var r = "";
    var l = elObj.options.length;
    for (i=0;i<l;i++) {
        if (!fOnlySelected || elObj.options[i].selected) {
            r+=(r!=""?",":"")+elObj.options[i].value;
        }
    }
    return r;
}

/**
 * Only string manipulation!
 * Function removes <strParamName>=.*& in string <strUrlParams>
 * and add <strParamName>=<strParamName> at the end.
 * e.g: addOrReplaceQueryParam( "abs=12&de=german&en=engl&", "de", "GER");
 *       = "abs=12&en=engl&de=GER&"
 * @param String strUrlParams 	URL parameter string
 * @param String strParamName	This paramater should get a new value
 * @param String strParamValue	The new value
 * @return String
 */
function addOrReplaceQueryParam(strUrlParams, strParamName, strParamValue) {
    var nPos = strUrlParams.indexOf( strParamName );
    if (nPos>-1) {
        var strRight = strUrlParams.substr( nPos+1 );
        var strLeft = nPos==0? "": strUrlParams.substr(0, nPos-1);
        var nPos2 = strRight.indexOf( '&' );
        if (nPos2>0) strRight = strRight.substr( nPos2 );
        strUrlParams = strLeft + strRight;
    }
    return strUrlParams
            + (strUrlParams.lastIndexOf("&")!=strUrlParams.length-1? "&" : "")
            + strParamName + "=" + escape(strParamValue) + "&";
}

/**
* Selected option in <el> will be used to reload DIV with <divId>.
* The value of the option is the parameter for the DIV.
*
* Example:
* 	We have:
*		* select box Object objSelect,
*		* selected value is '7'
*		* div element with ID 'divId'
*		* div was filled by ajaxLoad(divId, 'a=1&b=2&c=3&e=4");
*	After execution of
*		connectDivElement(objSelect, divId, 'c');
*	The div section will be filled by
* 		ajaxLoad(divId, 'a=1&b=2&e=4&preselection=&c=7");
*
* @param select <el>                HTML "select" object, which was just modified.
* @param String <divId>				ID of DIV which should be reloaded.
* @param String <strDivParamName>	URL of DIV should contains this parameter and value is selectionbox value.
*/
function connectDivElement(el, divId, strDivParamName) {
    var query = arrDivUrls[divId];
    if (!query) {
        alert("Old div '"+divId +"' URL string not defined. Was div not loaded by ajaxLoad?")
        return;
    }
    var ids = selBoxValues(el);
    if (!ids || ids=="") return;

	var arrParamReplace = new Array();
	arrParamReplace[strDivParamName] = ids;
	arrParamReplace["preselection"] = "";
    refreshElement(divId, arrParamReplace );
}

/**
* This function reloads a DIV section, which was load by ajaxLoad() earlier,
* This function modifies the URL query string before requesting data.
* It exchange the values of the URL query.
* 'arrParams' is an array. Keys are the parameter names and the values are the changed parameter values.
*
* Example:
* 	We have:
*		* div element with ID 'divId'
*		* div was filled by ajaxLoad(divId, 'a=1&b=2&c=3&e=4");
*	After execution of
*       refreshElement('divId', {b:8, c:9});
*	The div section will be filled by
* 		ajaxLoad('divId', 'a=1&b=8&c=9&e=4");
*
*
* In case of the Div element'elementId' contains a select box,
* then the function replaces the content of the select box with
* a "loading..." option during the server communication.
*
* @param elementId  Name of DIV section
* @param arrParams	Array of parameter, which should be replaced in the URL
*/
function refreshElement(elementId, arrParams) {
    var query = arrDivUrls[elementId];
    if (!query) {
        alert("refreshElement('" +elementId+"'): Element was not filled by ajaxLoad()!")
        return;
    }

    newquery = query;
    if (arrParams) {
    	for(var strParamName in arrParams) {
    		newquery = addOrReplaceQueryParam(newquery, strParamName, arrParams[strParamName]);
   		}
    }

    // search first select box and insert as first option a "loading..."
    var el = document.getElementById(elementId);
    for(var i=0; i<el.childNodes.length; i++) {
    	var t = el.childNodes[i].type;
        if (t && t.indexOf("select")!=-1) {
        	try {
            	el.childNodes[i].options[0] = new Option("loading...", "", false, false);
            	el.childNodes[i].length=1;
        	} catch (a) {;}
        	break;
        }
    }

    if (newquery!="") {
    	ajaxLoad(elementId, newquery);
    } else alert ("refreshElement("+elementId+" bad parameter.");
}

/**
* Form to URL Query.
* This function will go through the complete form,
* searches for input fields, check boxes and select boxed
* and will create an String in the URL Format: <name>=<value>&....&<name>=<value>.
* @param Element	formElement
* @return String
*/
function buildQuery(formElement) {
    var q = "";
    for(var i=0; i<formElement.length; i++) {
        var e = formElement.elements[i];
        if (e.name && e.name!="" && !e.disabled) {
            var v = "";
            if ("hidden/text".indexOf(e.type)!=-1) v = e.value;
            else if ("hidden/password".indexOf(e.type)!=-1) v = e.value;
            else if ("textarea".indexOf(e.type)!=-1) v = e.value;
            else if ("select-one".indexOf(e.type)!=-1) v = selBoxValues(e);
            else if ("checkbox".indexOf(e.type)!=-1) v = e.checked? e.value: "" ;
            //else alert(e.type);
            if (v!="") q += (q!=""?"&":"") + e.name + "=" + encodeURI(v);
        }
    }
    return q;
}