
/**
* 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 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;        
        strTradebitURL=tradebitURL();
        echo("ajaxLoad URL: "+strTradebitURL+"<a href=\""+strTradebitURL+"/ajax.php?"+strQuery+"\">/ajax.php</a>");
    	echo("ajaxLoad("+strDiv+","+(strQuery.length<250? strQuery: strQuery.substr(0,250) +"...")+")");
        req.open("POST",strTradebitURL+"/ajax.php", true);
        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
        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'>");
                        try {
                            document.getElementById(strDiv).ajaxErr = nErrPos>0? req.responseText.substr(nErrPos): '';
                        } catch(e) {;} 
                        
                        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 />";
	};
}
function setServerPath(str) {
	document.serverPath=str;
}
function tradebitURL() {
	if (document.serverPath) return document.serverPath;
    var strPosiblePathPart = "/tradebit.com";
    var str = window.location.pathname;
    var pos = str.indexOf(strPosiblePathPart);
    if (pos>=0) str = str.substr(0, pos + strPosiblePathPart.length);
    else str = ""; 
    if (window.location.port==80 || window.location.port==443) strPort=':80'; else strPort='';
    fSslBecauseOfPwd = false;
    return (fSslBecauseOfPwd? 'https:': window.location.protocol) + "//" + window.location.host + strPort + str;    
}

/**
 * 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+'=')==0)
    		 ? 0
    		 : (strUrlParams.indexOf( '&'+strParamName+'=')>-1? strUrlParams.indexOf( '&'+strParamName+'=')+1: 0);
    
    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 + (nPos2>0?strRight:'');
    }
    return strUrlParams
            + (strUrlParams.lastIndexOf("&")!=strUrlParams.length-1? "&" : "")
            + strParamName + "=" + encodeURIComponent(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 );
}

function connectFormWithSpan(formId, divId) {
	var formElement=document.getElementById(formId);
	var arrParamReplace = new Array();
	var v;
    for(var i=0; i<formElement.length; i++) {
        var e = formElement.elements[i];
        if (e.name && e.name!="" && !e.disabled) {
            v = null;
            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 if ("radio".indexOf(e.type)!=-1 && e.checked) v = e.value;
            else if ("file".indexOf(e.type)!=-1) v = e.value? e.value: "" ;
            //else alert(e.type);
            if (v!=null) arrParamReplace[e.name]=v;
        }
    }
    var query = arrDivUrls[divId];
    if (!query) {
        alert("Old div '"+divId +"' URL string not defined. Was div not loaded by ajaxLoad?")
        return;
    }

    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 if ("radio".indexOf(e.type)!=-1 && e.checked) v = e.value;
            else if ("file".indexOf(e.type)!=-1) v = e.value? e.value: "" ;
            //else alert(e.type);
            if (v!="") q += (q!=""?"&":"") + e.name + "=" + encodeURIComponent(v);
        }
    }
    if (q!="") q += "&umlaut=" + encodeURIComponent("äüß");
    return q;
}

/**
* Category navigation bar for Tradebit (left side)
*/
function fgrpFolder(id)
{
	var el = document.getElementById('side_'+id);
	var pl = document.getElementById('submenu_'+id);
	if (!el) return alert('side_'+id);
	if (!pl) return alert("submenu_"+id);
	if (el.style.display=="none") {
		el.style.display="block";
		pl.className = 'show';
		if ( (typeof ajaxLoad == 'function')
			 && (el.innerHTML.search(/li/i)<0) ) {
			el.innerHTML='<li><a href="#">loading</a></li>';
			ajaxLoad('side_'+id, "ajaxtask=catnavSubfilegroups&parentId="+id, "", true)
		}
	} else {
    	el.style.display="none";
		pl.className = 'ul';
	}
}

/**
 * An error occoured in PHP and the Error Class knows, which form element(s) was (were) invalid and mark it with a style attribute.
 * eg requestParamFailedMark(new Array('product-name','product-desc'), 'border', '1px solid #FF0000') { 
 * @param arrNames
 * @param strStyleAttr
 * @param strStyleValue
 */
function requestParamFailedMark(arrNames, strStyleAttr, strStyleValue) {
	var arrForms=document.getElementsByTagName('form');
	var f, j, i, b, e, fFirst=true;
	for (i=0; i<arrForms.length; i++){
		f=arrForms[i];
		//alert (f.id+ ' form');
		for (j=0; j<f.elements.length; j++) {
			e=f.elements[j];
			if (e.name && e.name!="" && !e.disabled && e.type!="hidden") {
				//alert (f.elements[j].name+ ' elment in '+f.id);
				for (b=0; b<arrNames.length; b++) {
					if (e.name==arrNames[b]) {
    					e.style[strStyleAttr]=strStyleValue;
    					if (fFirst) { try{ e.focus();} catch(e) {;}; fFirst=false;}
					}
				}
			}
		}
	}
}	
function w(a) {document.write(a);};
function a(a,b) {w("<a h"+"re"+"f=\""+a+"\" "+b+">");};
function ac() {w("<"+"/a"+">");}  
function addPost(elementA, str) {
	if (!document.getElementById('formAddPost')) { return document.getElementById("debuglineLog")? alert('form with id=formAddPost missing'): true; }
	if (!elementA.hrefOrg) {
		elementA.hrefOrg=elementA.href;
		elementA.href = 'javascript:;';
	}
	document.getElementById('formAddPost').action=elementA.hrefOrg;
	document.getElementById('inputPostData').value=str;
	document.getElementById('formAddPost').submit();
}
function submitSrch(formEl) {
	try {
		var fgrpId = ("select-one".indexOf(formEl.filtercat.type)!=-1)
		   ? selBoxValues(formEl.filtercat)
		   : formEl.filtercat.value;
		var str=formEl.elements['keywords'].value;
	  	str = encodeURI(str.toLowerCase().replace(/[\#\?\/\&\\\'\'*+\%,._;:\(\)\[\$\]=]/g, ' ')).replace(/[%]2[02]/g, ' ').replace(/[ ][ ]*/g, '+').replace(/[\+]$/g, '');
	  	var e = tradebitURL() + '/filesharing.php/search/0/'
				  + str
				  + (fgrpId? '/0/'+formEl.filtercat.value: '');
		window.location.href = e;
	} catch (e) { alert("ajaxLoad:"+e); }
	return false;
}
greyboxMyShow = function(caption, url, height, width, callback_fn) {
    var options = {
        caption: caption,
        height: height || 500,
        width: width || 500,
        fullscreen: false,
        overlay_click_close: true,
        show_loading: false,
        center_win: true,
        callback_fn: callback_fn
    };
    var win = new GB_Window(options);
    return win.show(url);
}