/**
    * common forms scripts
    *
    * @project openCSP
    * @package common
    *
    * @author     Peter Krebs <pitlinz@users.sourceforge.net>
    * @license    http://opensource.org/licenses/gpl-license.php GNU Public License
    *
    * @since pk-07-02-26
    *
    **/

var ocspAjax_debug_mode   = false;
var ocspAjax_debug_form   = false;
var ocspAjax_debug_popup  = false; // if true a new window is opened with the output

var ocspAjax_functions    = new Array();

var ocspAjax_requests     = new Array();
var ocspAjax_request_type = "get";


/**
  * alerts the text if ocspAjax_debug_mode
  *
  * @param string text
  */
function ocspAjax_debug(text) {
    if (ocspAjax_debug_mode) alert(text);
}

/**
  * shows an error msg
  *
  * @param string msg
  */

function ocspAjax_showErrMsg(msg)
{
    if (!document.getElementById('ocspAjax_divError'))
    {
    	this.errorDiv = document.createElement('DIV');
        this.errorDiv.id='ocspAjax_divError';
                
        document.body.appendChild(this.errorDiv);
    }    
    document.getElementById('ocspAjax_divError').innerHTML+="<div align=\"left\"><pre>"+msg+"</pre></div>";
}

/**
  * splits a long text into lines of 30 chars each
  * and alerts the result
  *
  * @param string text
  */
function ocspAjax_debugLong(text) {
    if (text.length < 20) {
        alert(text);
    }

    i=0;str_txt='';
    while(i < text.length) {
        str_part=text.substr(i,20);
        if (!str_part.indexOf("\n")) {
            str_txt=str_txt+str_part+"\n";
        }
        else {
            str_txt=str_txt+str_part;
        }
        i=i+20;
    }
    alert(str_txt);
}

// -----------------------------------------------
// functions
//

function ocspAjax_funcArg(argName,argValue) {
    this.argName    =argName;
    this.argValue   =argValue;
}

function ocspAjax_funcObject(phpObjId,func_name,target_id,uri) {
    this.phpObjId           =phpObjId;
    this.func_name          =func_name;
    this.target_id          =target_id;
    this.uri                =uri;
    this.requestType        =ocspAjax_request_type;
    this.failure_redirect   ="";
    this.args               =new Array();
    this.debug              =false;

    /**
      * @param string argName
      * @param mixed argValue
      *
      * return boolean
      */
    this.setFuncArg = function(argName,argValue,debug)
    {
        if (debug) alert('adding funcArg ('+argName+','+argValue+')\n to '+this.func_name);
        if (!argName || (argName == '') || (argName=='')) return false;

        var i=0;
        while (i < this.args.length)
        {
            if (!this.args[i] ||  (!this.args[i].argName) || (this.args[i].argName==argName))
            {
            	if (argValue && (argValue != ''))
            	{
	                this.args[i].argValue=argValue;
	                return true;
            	} else {
            		this.args[i]=null;
            	}
            }
            i++;
        }
        if (argValue && (argValue != ''))
        {
            this.args[this.args.length]=new ocspAjax_funcArg(argName,argValue);
            return true;
        }
        return false;
    }

    /**
      * @param string reqUri
      */
    this.setRequestUri = function(reqUri)
    {
        this.uri=reqUri;
    }

    this.doDebug = function()
    {
        var dbgTxt = 'Debug Function: '+this.func_name+'\n'+this.args.length+' Args:';
        var i=0;
        while (i < this.args.length)
        {
            dbgTxt = dbgTxt + '\n'+this.args[i].argName+' => '+this.args[i].argValue;
            i++;
        }

        alert(dbgTxt);
    }
}

/**
  * @param string func_name
  *
  * @return ocspAjax_funcObject
  */
function ocspAjax_get_funcObj(func_name) {
    var i=0;
    while ((ocspAjax_functions.length > 0) && (i <= ocspAjax_functions.length)) {
        if ((ocspAjax_functions[i]) && (ocspAjax_functions[i].func_name==func_name)) {
            return ocspAjax_functions[i]
        }
        i++;
    }
    return null;
}

/**
  * overwrites existing function objects or generates a new function object
  *
  * @param string phpObjId
  * @param string func_name
  * @param string target_id
  * @param string uri
  *
  * @return ocspAjax_funcObject
  */
function ocspAjax_register_function(phpObjId,func_name,target_id,uri) {
    ocspAjax_debug("ocspAjax_register_function(phpObjId,func_name) called..");
    obj_func=ocspAjax_get_funcObj(func_name);
    if (obj_func) // function already registered
    {
        obj_func.phpObjId=phpObjId;
        obj_func.target_id=target_id;
        obj_func.uri=uri;
        return obj_func;
    }

    // generate a new function object
    i=ocspAjax_functions.length;
    ocspAjax_functions[i]=new ocspAjax_funcObject(phpObjId,func_name,target_id,uri);
    return ocspAjax_functions[i];
}

function ocspAjax_func_setRequestType(func_name,rqt) {
    obj_func=ocspAjax_get_funcObj(func_name);
    if (obj_func)
    {
        obj_func.requestType=rqt;
        return true;
    } else {
        return false;
    }
}

function ocspAjax_func_setArg(func_name,argName,argValue) {
    obj_func=ocspAjax_get_funcObj(func_name);
    if (obj_func)
    {
        return obj_func.setFuncArg(argName,argValue);
    } else {
        return false;
    }
}


// -----------------------------------------------
// ajax requests
//

/**
 * generates a request objects 
 * 
 * clears the error div
 * 
 * @return object the request objects
 */
function ocspAjax_init_object() {
    ocspAjax_debug("ocspAjax_init_object() called..")

	if (document.getElementById('ocspAjax_divError'))
	{
		document.getElementById('ocspAjax_divError').innerHTML="";
	}

    var reqObj;

    try {
        reqObj = new XMLHttpRequest();
        return reqObj;
    } catch(e) {
        var msxmlhttp = new Array(
            'Msxml2.XMLHTTP.5.0',
            'Msxml2.XMLHTTP.4.0',
            'Msxml2.XMLHTTP.3.0',
            'Msxml2.XMLHTTP',
            'Microsoft.XMLHTTP'
        );

        for (var i = 0; i < msxmlhttp.length; i++) {
            try {
                reqObj = new ActiveXObject(msxmlhttp[i]);
                return reqObj;
            } catch (e) {
                reqObj = null;
            }
        }
    }

    if (!reqObj)
        ocspAjax_debug("Could not create connection object.");
    return reqObj;
}

function ocspAjax_cancel() {
    for (var i = 0; i < ocspAjax_requests.length; i++)
        ocspAjax_requests[i].abort();
}

/**
  * returns the uri of a function
  *
  * @param string func_name
  * @param string args
  *
  * @return string
  */
function ocspAjax_getfuncUri(func_name,args)
{
    var obj_func;
    var str_ret='';

    ocspAjax_debug("ocspAjax_getfuncUri(" + func_name + ")");
    obj_func=ocspAjax_get_funcObj(func_name);
    if (obj_func) {
        str_ret=obj_func.uri;

        if (str_ret.indexOf("?") == -1)
            { str_ret += "?oaxfn=" + escape(func_name); }
        else
            { str_ret += "&oaxfn=" + escape(func_name); }

        str_ret += "&oaxid=" + escape(obj_func.target_id);
        str_ret += "&oaxrnd=" + new Date().getTime();
        str_ret += "&phpObjId=" + obj_func.phpObjId;

        if ((typeof(args) != 'undefined') && (args) && (args.length > 0))
        {
            for (i = 0; i < args.length; i++)
            {
                //alert(i+' type: '+typeof(args[i]));
                str_ret += "&"+args[i].argName +"=" + escape(args[i].argValue);
            }
        }

        for (i = 0; i < obj_func.args.length; i++)
        {
            if (ocspAjax_debug_mode) alert("uri: adding "+obj_func.args[i].argName +" value: "+ obj_func.args[i].argValue);
            str_ret += "&" + escape("oaxArg["+obj_func.args[i].argName +"]") + "=" + escape(obj_func.args[i].argValue);
        }

        str_ret +="&"+ocsp_session_name+'='+ocsp_session_id;
    }
    if (ocspAjax_debug_mode) ocspAjax_debugLong(str_ret);
    return str_ret;
}

/**
  * open the request an process the result
  *
  * @param string request_type
  * @param string uri
  * @param string post_data
  * @param string target_id
  *
  * @return boolean
  */
function ocspAjax_do_request(request_type,uri,post_data,target_id)
{
    var x;

    x = ocspAjax_init_object();
    if (document.getElementById('ocspAjax_divError'))
    {
        document.getElementById('ocspAjax_divError').innerHTML="";
    }

    if (x == null) {
        if (ocspAjax_failure_redirect != "") {
            location.href = ocspAjax_failure_redirect;
            return false;
        } else {
            ocspAjax_debug("NULL ocspAjax object for user agent:\n" + navigator.userAgent);
            return false;
        }
    } else {
        if (ocspAjax_debug_popup) {
            alert('open popup: '+uri);
            openWindow('name',uri+'&oax_debug=1',800,600);
            return true;
        }

        x.open(request_type, uri, true);
        
        if (objDomLog=document.getElementById('ocsp_ajaxLog'))
        {
            objDomLog.innerHTML=objDomLog.innerHTML+'\n<strong>'+uri+'</strong>';
        }

        ocspAjax_requests[ocspAjax_requests.length] = x;

        if (request_type == "post") {
            x.setRequestHeader("Method", "post " + uri + " HTTP/1.1");
            x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            //ocspAjax_debug(post_data.replace(/&/g,"\n"));
            if (ocspAjax_debug_form) ocspAjax_debugLong('post data: '+post_data);
            x.send(post_data);
        } else {
            x.send(post_data);
        }

        x.onreadystatechange = function() {
            if (x.readyState != 4) return;

            ocspAjax_debug("received " + x.responseText);

            var status;
            var data;
            var txt = x.responseText.replace(/^\s*|\s*$/g,"");
            status = txt.charAt(0);
            data = txt.substring(2);

            if (objDomLog=document.getElementById('ocsp_ajaxLog'))
            {
                txtLog=txt.replace(/\</g,'&lt;');
                txtLog=txtLog.replace(/\>/g,'&gt;');
                txtLog=txtLog.replace(/\\n/g,'\n');
                objDomLog.innerHTML=objDomLog.innerHTML+'\n<pre>'+txtLog+'</pre>';
            }

            if (status == "") {
                // let's just assume this is a pre-response bailout and let it slide for now
            } else if (status == "-")
                alert("Error: " + data);
            else {
                if (target_id != "")
                    document.getElementById(target_id).innerHTML = eval(data);
                else {
                    if (ocspAjax_debug_mode)
                    {
                        alert('ajax call debug debug');
                        eval(data);
                    } else {
                        try {
                            eval(data);
                        } catch (e) {
                            ocspAjax_showErrMsg("Caught error " + e + ": Could not eval " + data );
                        }
                    }
                }
            }
        }
    }

    ocspAjax_debug(" waiting..");
    delete x;
    return true;
}

function ocspAjax_do_call(func_name, args) {
    var funcObj;
    var i, n;
    var post_data;
    var uri;
    var requestType;
    var target_id;

    ocspAjax_debug("ocspAjax_do_call(" + func_name + ")");
    funcObj=ocspAjax_get_funcObj(func_name);
    if (funcObj) {

        uri=funcObj.uri;
        request_type=funcObj.requestType;
        target_id = funcObj.target_id;

        ocspAjax_debug("in ocspAjax_do_call().." + request_type + "/" + target_id);
        if (typeof(request_type) == "undefined" || request_type == "")
            request_type = "get";

        if (request_type == "get") {
            uri=ocspAjax_getfuncUri(func_name,args);
            post_data = null;
        } else if (request_type == "post") {
            post_data = "oaxfn=" + escape(func_name);
            post_data += "&oaxid=" + escape(target_id);
            post_data += "&oaxrnd=" + new Date().getTime();
            post_data += "&phpObjId=" + escape(funcObj.phpObjId);

            for (i = 0; i < args.length; i++) post_data = post_data + "&" + args[i].argName + "=" + escape(args[i].argValue);
            for (i = 0; i < funcObj.args.length; i++) post_data += "&oaxArg["+funcObj.args[i].argName +"]=" + escape(funcObj.args[i].argValue);
        } else {
            alert("Illegal request type: " + request_type);
        }

        return ocspAjax_do_request(request_type,uri,post_data,target_id);
    }
}

/**
  * calls an ajax function and adds form fields
  *
  * @param string func_name
  * @param form aForm
  *
  */
function ocspAjax_do_callFormArgs(func_name, aForm) {
    arrArgs=new Array();
    for (i =0; i < aForm.elements.length; i++)
    {
        if (aForm.elements[i].name != '')
        {
            argValue='';
            switch(aForm.elements[i].type)
            {
                case "text":
                case "hidden":
                case "textarea":
                case "select-one":
                    argValue=aForm.elements[i].value;
                    break;
                case "checkbox":
                    argValue=(aForm.elements[i].checked ? 1 : 0);
                    break;
                case radio:
                    alert('checking radio '+aForm.elements[i].name)
                    var j=0;
                    while ((argValue=='') && (j < aForm.elements[i].length))
                    {
                        if (aForm.elements[i][j].checked)
                        {
                            alert('checked value: '+j+' ('+aForm.elements[i][j].value+')');
                            argValue=aForm.elements[i][j].value;
                        }
                        j++
                    }
                    break;
                default:
                    alert("ocspAjax_do_callFormArgs:\n"+aForm.elements[i].name+" Type: "+aForm.elements[i].type+" not implemented");
            }
            arrArgs[i]=new ocspAjax_funcArg(aForm.elements[i].name,argValue);
        }
    }

    return ocspAjax_do_call(func_name, arrArgs);
}

function ocspAjax_getFormElem(elem)
{
    str_ret = '';
    o_reg_phpArr=/\[\]$/;

    if ((elem.name != '') && (elem.name != 'undefined'))
    {
        switch(elem.type)
        {
            case "text":
            case "hidden":
            case "textarea":
            case "select-one":
                //alert("text: \n"+elem.name+"="+elem.value+"\n"+encodeURIComponent(elem.name)+"="+encodeURIComponent(elem.value));
                str_ret +="&"+encodeURIComponent(elem.name)+"="+encodeURIComponent(elem.value);
                break;
            case "checkbox":
                str_ret +="&"+encodeURIComponent(elem.name)+"=";
                if (elem.checked)
                {
                   str_ret +=encodeURIComponent(elem.value);
                }
                break;
            case "radio":
                if (elem.checked)
                {
                    str_ret +="&"+encodeURIComponent(elem.name);
                    str_ret += "="+encodeURIComponent(elem.value);
                }

                /*
                if (elem.length > 0) {
                    var bFound=false;
                    var i=0;
                    while(!bFound && i < elem.length)
                    {
                        if (elem[i].checked)
                        {
                            str_ret += "="+encodeURIComponent(elem.value);
                            bFound=true;
                        }
                        i++;
                    }
                } else if (elem.value != 'undefined') {
                    str_ret += "="+encodeURIComponent(elem.value);
                }
                */

                break;
            case "select-multiple":
                is_phpArr=o_reg.text(elem.name);
                if (!is_phpArr)
                {
                    str_ret +="&"+encodeURIComponent(elem.name)+"=";
                }
                for (i=0; i < elem.length; i++)
                {
                    if (elem.options[i].selected)
                    {
                        if (is_phpArr)
                        {
                            str_ret +="&"+encodeURIComponent(elem.name)+"=";
                            str_ret +=encodeURIComponent(elem.options[i].value);
                        } else {
                            str_ret +=encodeURIComponent(elem.options[i].value+";");
                        }
                    }
                }
            default:
                str_ret +="&"+encodeURIComponent(elem.name)+"=";
                try {
                    str_ret += encodeURIComponent(elem.value);
                } catch(e) {
                    alert("Caught error " + e + " in ocspAjax_getFormElem(aForm,"+func_name+")\n"+elem.name+" Type:"+elem.type);
                }
        }
    }
    return str_ret;
}

/**
  * submit a form
  *
  * @param form aForm
  * @param string func_name
  *
  * @return boolean always false to avoid sending the form
  *
  */
function ocspAjax_submitForm(aForm,func_name)
{
    try {
        str_uri=ocspAjax_getfuncUri(func_name,null);
        if (str_uri == '')
        {
            str_uri=aForm.action;
        }

        str_request=aForm.method;
        if (ocspAjax_debug_form) ocspAjax_debugLong("submitForm: method="+str_request+"\n uri: "+str_uri);

        if ((func_name != '') && (obj_func=ocspAjax_get_funcObj(func_name)))
        {
            target_id=obj_func.target_id;
        } else {
            target_id=aForm.target;
        }

        if ((str_request == 'get') || (str_request == ''))
        {
            var l=aForm.elements.length;
            for (i =0; i < l; i++)
            {
                str_uri += ocspAjax_getFormElem(aForm.elements[i]);
            }
            post_data=null;
            str_request="get";
        } else {
            post_data='';
            var l=aForm.elements.length;
            for (i =0; i < l; i++)
            {
                post_data += ocspAjax_getFormElem(aForm.elements[i]);
            }
            str_request="post";
        }
        request_done=ocspAjax_do_request(str_request,str_uri,post_data,target_id);
    } catch(e) {
        ocspAjax_debugLong("Caught error " + e + " in ocspAjax_submitForm(aForm,"+func_name+")");
    }

    return false;
}

/**
  * submit a form by calling a function
  *
  * @param form aForm
  * @param string func_name
  *
  * @return boolean always false to avoid sending the form
  *
  */
function ocspAjax_submitForm_toFunction(aForm,aFuncObj)
{
    str_request=aForm.method;

    if (!aFuncObj.uri)
    {
        alert(aFuncObj.name + ' has no uri set');
        return false;
    }

    str_uri=aFuncObj.uri;
    target_id=aFuncObj.target_id;

    if (str_uri.indexOf("?") == -1)
        { str_uri += "?oaxfn=" + escape(aFuncObj.func_name); }
    else
        { str_uri += "&oaxfn=" + escape(aFuncObj.func_name); }
    str_uri += "&oaxrnd=" + new Date().getTime();

    if ((str_request == 'get') || (str_request == ''))
    {
        for (i =0; i < aForm.elements.length; i++)
        {
            str_uri += ocspAjax_getFormElem(aForm.elements[i]);
        }
        post_data=null;
        str_request="get";
    } else {
        post_data='';
        for (i =0; i < aForm.elements.length; i++)
        {
            post_data += ocspAjax_getFormElem(aForm.elements[i]);
        }
        str_request="post";
    }

    for (i = 0; i < aFuncObj.args.length; i++)
    {
    	if (aFuncObj.args[i].argName)
    	{
            if (ocspAjax_debug_mode) alert("uri: adding "+aFuncObj.args[i].argName +" value: "+ aFuncObj.args[i].argValue);
            str_uri += "&" + escape("oaxArg["+aFuncObj.args[i].argName +"]") + "=";
            if (aFuncObj.args[i].argValue)
            {
                str_uri +=escape(aFuncObj.args[i].argValue);
            }
    	}
    }
    str_uri +="&"+ocsp_session_name+'='+ocsp_session_id;

    if (ocspAjax_debug_form) ocspAjax_debugLong("submitForm: method="+str_request+"\n uri: "+str_uri);
    request_done=ocspAjax_do_request(str_request,str_uri,post_data,target_id);
}


/**
  * functions for the returning script -----------------------------------------------
  */

/**
  * sets the innerHTML of a DOM object
  * @param string target_id
  * @param string aContent
  */
function ocspAjax_setIdHtml(target_id,aContent,displayMode) {
    if (obj_target=ocsp_getElem(target_id))
    {
        obj_target.innerHTML = aContent;

        if ((obj_target.style) && (obj_target.style.display == 'none'))
        {
            if (!displayMode) displayMode='block';
            obj_target.style.display=displayMode;
        }
    } else {
        alert(target_id+":\n"+aContent);
    }
}

function ocspAjax_addIdHtml(traget_id,aContent) 
{
    if (obj_target=ocsp_getElem(target_id))
    {
        obj_target.innerHTML = obj_target.innerHTML+aContent;
    }
}

/**
  * sets the innerHTML of a DOM object form a base64 encoded string
  * @param string target_id
  * @param string aContent
  */
function ocspAjax_setIdb64Html(traget_id,aContent,displayMode)
{
    ocspAjax_setIdHtml(traget_id,base64decode(aContent),displayMode);
}

/**
  * hides a target
  *
  * @param string target_id
  *
  */
function ocspAjax_hideTarget(target_id)
{
    if (obj_target=ocsp_getElem(target_id))
    {
        obj_target.style.display='none';
    }
}

	
