/*
hack to enable text editor to pick this up.
<script type="text/javascript">
*/

 
  
  

/**************************** Class phpRequest ****************************/

/* class phpRequest { */
function phpRequest(server_url) {
    
    /* vars */
    
    this.parms              = new Array();
    this.server             = server_url;
    
    /* methods */
    
    this.execute            = phpRequest_execute;
    this.executeGet         = phpRequest_executeGet;   // simple Get (returns httpxmlreq. object)
    this.getXML             = phpRequest_getXML;
    this.executeGetWithCallback = phpRequest_executeGetWithCallback;
    
    this.getFullURL         = phpRequest_getFullURL;
   
    this.openIn             = phpRequest_openIn;
    this.openNewWindow      = phpRequest_openNewWindow;
   
    this.add                = phpRequest_add;
    this.get                = phpRequest_get;
    this.postForm           = phpRequest_postForm;

    this._getQueryVariable   = phpRequest__getQueryVariable;
    this.getQueryVariable    = phpRequest_getQueryVariable;
    this.getOptionalQueryVariable = phpRequest_getOptionalQueryVariable;
    
    this.mysqlDate          = phpRequest_mysqlDate;
    this.debugURL           = phpRequest_debugURL;
    this.lock               = phpRequest_lock;
    this.unlock             = phpRequest_unlock;
    
    /* form util stufff */
    this.assignFromDocument = phpRequest_assignFromDocument;
    this.replaceWithLabel   = phpRequest_replaceWithLabel;
    this.disableForm        = phpRequest_disableForm;
    this.assert             = phpRequest_assert;
    this.getDateAsInt       = phpRequest_getDateAsInt;
    
    
    this.callback	    = null;
    
    /*
    var add = this.getOptionalQueryVariable('PHPSESSID');
    if (add) {
        this.add('PHPSESSID', this.getQueryVariable('PHPSESSID'));
    }
    */
}
    
    
    
    function phpRequest_add(name, value) {
        var add     = new Object();
        add.name    = name;
        add.value   = value;
	for (var i=0;i<this.parms.length;i++) {
            if (this.parms[i].name == name) {
		 this.parms[i].value = value;
		 return;
	     }
	}
        this.parms[this.parms.length] = add;
        
    }
    
    function phpRequest_get(name) {
        for (var i=0;i<this.parms.length;i++) {
            if (this.parms[i].name == name) {
                return this.parms[i].value;
            }
        }
        return null;
        
    }
    
    function phpRequest_getQueryVariable(variable) {
       return this._getQueryVariable(variable,true)
    }
    function phpRequest_getOptionalQueryVariable(variable) {
       return this._getQueryVariable(variable,false)
    }

    function phpRequest__getQueryVariable(variable,warn) {
      
        var query = window.location.search.substring(1);
      
        if (!query) {
            return;
        }
      
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        } 
        if  (warn) {
             alert('Query Variable ' + variable + ' not found');
        } 
        return 0;
    }
    
    /**
    * execute a POST request and return the textural answer
    *
    * 
    *
    * @return   string   data returned.
    * @access   private
    */
    function phpRequest_execute() {
        var targetURL = this.server;
        var httpRequest = false;
        if(window.XMLHttpRequest) {
			try {
				httpRequest = new XMLHttpRequest();
			} catch(e) {
				alert("Error creating the connection!");
				return;
			}
			// branch for IE/Windows ActiveX version
		} else if(window.ActiveXObject) {
			try {
				httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e) {
				try {
					httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
				} catch(e) {
					alert("Error creating the connection!");
					return;
				}
			}
		}
		
        
        try {
            var txt = "?1";
            for ( var i in this.parms ) {
                txt = txt + "&" + this.parms[i].name + '=' + escape(this.parms[i].value);
            }
            // httpRequest.open("GET", targetURL+txt, false, null, null);    
            // httpRequest.send('');
            
            httpRequest.open("POST", targetURL, false, null, null);    
            httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            httpRequest.send(txt);
        } catch ( e ) {
            alert("An error has occurred calling the external site: " + e);
            return false;
        } 
        var response = false;
        switch ( httpRequest.readyState ) {
            case 1, 2, 3:
                alert("Bad Ready State: " + httpRequest.status);
                return false;
            break;
            
            case 4:
                if ( httpRequest.status != 200 ) {
                    alert("The server respond with a bad status code: " + httpRequest.status);
                    return false;
                } else {
                    response = httpRequest.responseText;
                }
            break;
        }
        return response;
    }
    /**
    * copy the data to a form, and submit it.
    *
    * @param    HTMLFormElement formobj   Form Element
    *
    * @return   none
    * @access   private
    */
    function phpRequest_postForm(formobj) 
    {
        

        for ( var i in this.parms ) {
                
            var inp = document.createElementNS('http://www.w3.org/1999/xhtml','html:input');
            inp.setAttribute('type','hidden');
            inp.setAttribute('name',this.parms[i].name );
            inp.setAttribute('value',this.parms[i].value );
            
            
            formobj.appendChild(inp);
        }
       
        formobj.submit();
    }
    /**
    * execute a GET request and return xml data.
    *
    * 
    *
    * @return   string   data returned.
    * @access   private
    */
    function phpRequest_getXML() {
        var httpRequest = this.executeGet();
        //alert(httpRequest.responseText);
        if (httpRequest != false) {
            //alert(httpRequest.responseXML);
            return httpRequest.responseXML;
        }
        return false;
    }
    
    
    /**
    * execute a GET request anc callback with data
    *
    * 
    *
    * @return   string   data returned.
    * @access   private
    */
    
    function phpRequest_executeGetWithCallback(callback, returntype, data) 
    {
        
       if(window.XMLHttpRequest) {
			try {
				httpRequest = new XMLHttpRequest();
			} catch(e) {
				alert("Error creating the connection!");
				return;
			}
			// branch for IE/Windows ActiveX version
		} else if(window.ActiveXObject) {
			try {
				httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e) {
				try {
					httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
				} catch(e) {
					alert("Error creating the connection!");
					return;
				}
			}
		}
		
        
        try {
            //alert(this.getFullURL());
            httpRequest.open("GET", this.getFullURL(), true, null, null);
            var _t = this;
            httpRequest.onreadystatechange = function (aEvt) {
                switch ( httpRequest.readyState ) {
                    case 1, 2, 3:
                        
                        /*alert("Bad Ready State: " +
                            '('+httpRequest.readyState+') ' + 
                            httpRequest.status + "\n"+_t.getFullURL());
                        //callback(false);
                        return null;
                        */
                        break;
                        
                        
                    case 4:
                        try {
                            if ( httpRequest.status != 200 ) {
                                alert("The server respond with a bad status code: " + httpRequest.status +"\n" + this.getFullURL());
                                callback(false,data);
                                return;
                            }
                        } catch(e) {
                            // try again??
                            // this is a kludge that appears to get around the errors that occur...
                            setTimeout( function() { 
                                _t.executeGetWithCallback(callback, returntype, data);
                                }, 1000);
                                
                            
                            return;
                        }
                    
                       
                        if (returntype == "xml") {
                            callback(httpRequest.responseXML,data);
                            return;
                        }
                        if (returntype == "text") {
                            callback(httpRequest.responseText,data);
                            return;
                        }
                        callback(httpRequest,data);
                        return;
                }
                 

		    };
		 
            httpRequest.send(null);
        } catch ( e ) {
            alert("An error has occurred calling the external site: " + e);
            return false;
        } 
     
    }
    
    
    
    /**
    * execute a GET request and return xml data.
    *
    * 
    *
    * @return   string   data returned.
    * @access   private
    */
    function phpRequest_executeGet() {
        
        if(window.XMLHttpRequest) {
			try {
				httpRequest = new XMLHttpRequest();
			} catch(e) {
				alert("Error creating the connection!");
				return;
			}
			// branch for IE/Windows ActiveX version
		} else if(window.ActiveXObject) {
			try {
				httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e) {
				try {
					httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
				} catch(e) {
					alert("Error creating the connection!");
					return;
				}
			}
		}
		
        
        try {
            httpRequest.open("GET", this.getFullURL(), false, null, null);    
            httpRequest.send(null);
        } catch ( e ) {
            alert("An error has occurred calling the external site: " + e);
            return false;
        } 
    
        switch ( httpRequest.readyState ) {
            case 1, 2, 3:
                alert("Bad Ready State: " + httpRequest.status + "\n"+this.getFullURL());
                return false;
                break;
            
            case 4:
                if ( httpRequest.status != 200 ) {
                    alert("The server respond with a bad status code: " + httpRequest.status +"\n" + this.getFullURL());
                    return false;
                }  
		return httpRequest;
                break;
        }
        return httpRequest;
    }
    
    
    
    
    function phpRequest_getFullURL() {
        var txt = "?1";
        for ( var i in this.parms ) {
            txt = txt + "&" + this.parms[i].name + '=' + escape(this.parms[i].value);
        }
        return this.server+txt;
    }
    
    /**
    * recursevly parse a document, extract the form values and add them to
    * the request 
    *
    * @param   node     (document to start the process..
    *
    * @return   none
    * @access   public
    */
  
    function phpRequest_assignFromDocument(node) 
    {
        if (node.attributes && (node.attributes['id'] || node.attributes['name'])) {
                 
        
            switch (node.nodeName.toLowerCase()) {
                case "textbox":     // standard text entries
                case "menulist":
                    this.add(node.attributes['id'].value,node.value);
                    return;
                case "checkbox":
		    
                    this.add(node.attributes['id'].value,node.checked ? 1 : 0);
                    return;
               
                case "datepicker": // a datapicker.
                    if (node.mTextBox.disabled) {
                        return;
                    }
                    this.add(node.attributes['id'].value,this.mysqlDate(node.value));
                    return;
                case "colorpicker":
                    this.add(node.getAttribute('id'),node.getAttribute('color'));
                    return;
                    
                case "description": // hidden elements? 
                    // h_* elements are hidden!
                    if ((node.attributes['id'].value[0] == 'h') && (node.attributes['id'].value[1] == '_')) {
                        this.add(node.attributes['id'].value.substr(2),node.value);
                        return;
                    }
                    //alert("got " + node.nodeName + ": id : " + node.attributes['id'].value);
                    // dont traverse children!
                    return;
                case "input":
                case "select":
                    if (!node.getAttribute('name')) {
                        return;
                    }
                    if (node.getAttribute("type") == "checkbox") {
                        this.add(node.getAttribute('name'),node.checked ? 1 : 0);
                        return;
                    }
                    this.add(node.getAttribute('name'),node.value);
                    
                    
                    return;
                    
		    
		
                //ignore:
                case "#text":
                case "target":
                case "script":
                case "#comment":
                    return;
                
                
            }
        }
        if (!node.childNodes) {
            return;
        }
        for(var i=0;i<node.childNodes.length;i++) {
            this.assignFromDocument(node.childNodes[i]);
        }
    }
    
    /**
    * convert a date string into a standard mysql insertable string.
    *
    * @param   string   string to convert.
    *
    */
    function phpRequest_mysqlDate(strDate) {
        if ( strDate != "" ) {
            var curYear = strDate.getYear() + 1900;
            var curMonth = strDate.getMonth() + 1;
            if ( curMonth < 10 ) {
                curMonth = "0" + curMonth;
            }
            var curDay = strDate.getDate();
            if ( curDay < 10 ) {
                curDay = "0" + curDay;
            }
            return curYear + "-" + curMonth + "-" + curDay;
        } else {
            return "1970-01-01";
        }
    }
    /**
    * debug the created url string.
    *
    */
    function phpRequest_debugURL() {
        txt = '';
        for ( var i in this.parms ) {
            txt = txt + "\n" + this.parms[i].name + '=' + escape(this.parms[i].value);
        }
        alert(txt);
    }
    
 
    function phpRequest_lock(name,id) {
        x = new phpRequest(baseurl + '/Locking/lock/' + name + '/' + id + '.flag');
        return x.execute();
    }
    
    function phpRequest_unlock(name,id) {
        x = new phpRequest(baseurl + '/Locking/unlock/' + name + '/' + id + '.flag');
        return x.execute();
    }




    /**
    * replace a tag with a label
    *
    * Used to 'freeze a form'
    * 
    * 
    * @param   XULElement       node to replace
    * @param   string           value to put in.
    * 
    *
    * @return   none
    * @access   public
    */
    function phpRequest_replaceWithLabel(node,value) 
    {
        var l = document.createElement('label');
        l.setAttribute('value',value);
        l.setAttribute('id',node.attributes['id']);
        node.parentNode.replaceChild(l,node);
    }
    
    
    /**
    * replace all form elements with labels
    *
    * eg. 'freeze a form'
    * 
    * 
    * @param   XULElement       eg. document.window
    *
    * @return   none
    * @access   public
    */
 
    function phpRequest_disableForm(node) 
    {
        if (node && node.attributes && node.attributes['id']) {
                 
	    //alert(node.attributes['id'].value);
            switch (node.nodeName) {
                case "textbox":     // standard text entries
                    this.replaceWithLabel(node,node.value);
                    return
                case "menulist":
                    this.replaceWithLabel(node,node.selectedItem.label);
                    return;
                case "checkbox":
                    this.replaceWithLabel(node,node.checked ? 'Y' : 'N');
                    
                    return;
                case "datepicker":
                    this.replaceWithLabel(node,node.value.toLocaleDateString() );
                    return;
                
               
                case "description": // hidden elements? 
               
                case "#text":
                case "target":
                case "script":
                case "#comment":
                    return;
                
                
            }
        }
	if (node) {
		for(var i=0;i<node.childNodes.length;i++) {
		    this.disableForm(node.childNodes[i]);
		}
	}
    }
    
    /**
    * Open the url in a new window (with title)
    *
    * just calls window.open with the url.
    * 
    * 
    * @param   string       title for window.
    *
    * @return   [window] should be the new window!
    * @access   public
    * @see      see also methods.....
    */
  
    
    function phpRequest_openNewWindow(title)
    {
        
        var ret = window.open(this.getFullURL(), title, "chrome,dialog,modal,centerscreen,resizable=1,width=100,height=100");
        ret.screenX = window.screenX + 100;
        ret.screenY = window.screenY + 100;
        return ret;
    }
    function phpRequest_openIn(frameObj) 
    {
        frameObj.setAttribute("src", this.getFullURL());
    }
    
    
    function phpRequest_assert(condition, message)
    {
        if (!condition) {
            throw message;
        }
        
    }
    function phpRequest_getDateAsInt(col) {
        var value = this.get(col)
        var ar = value.split('-');
        
        return Date.UTC(ar[0],ar[1],ar[2]);
    }
    
     



/* } end class phpRequest */

 




