
// Response handler
var err_win; // need our window handle to be global as its call backs are in a different scope

/*
Usage of Ext AJAX code and response class. paste in Kate and it is formatted :)

Ext.Ajax.request({
    url: 'ajax.Backend.php',
    params: {'function': 'getEquipmentBookTable',
    'eid': x,
    'liststart':start
},
    success: function(transport, options) {
    resp = new Response(transport, options);
           if( resp.success() )
{
                retobj = resp.getReturnObject();
 
}
},
    failure:  function(){
    resp = new Response("", "function=getEquipmentTable");
    stopSpinner( 'eq_itemtable', 'content_body');
    resp.showError("Error: Our Server cannot be reached. Is server down? Please try again.");
}
});
    */

function Response(transport, post) {	
	this.success = function() { return (this.Code == 0 ) };
//	this.success = function() { return ((this.Code == 0 )||(this.Code == 1)) };
	this.fail = function() { return (this.Code == -1 ) };   
	this.warning = function() { return (this.Code == 1 ) };      	
   	
   	this.getJSON = function() { return this.JSON; }
   	this.getXML = function() { return this.XML; }
   	this.getCode = function() { return this.Code; }
   	this.getText = function() { return this.Text; }
   	this.getData = function() { return this.Data; }
   	this.getReturnObject = function() { return this.returnObject; }
   	
   	this.showPreParseError = function(text) {this._emailmore = false; this.Code = -1; this.Text = text; this.displayError();}
   	
	this._transport = transport;
	this._AJAXpost = post;
	this.response = transport.responseText;
	
	this.displayError = function() 
	{
	    // create the window on the first click and reuse on subsequent clicks
	    
	    /* say
	     The system will attempt to email the webmaster an error report." etc
	    */
	    if(!err_win){
	      err_win = new Ext.Window({
	          el:'error-win',
	          layout:'fit',
	          width:400,
	          height:250,
	          closeAction:'hide',
	          plain: true,
	          //items: new Ext.TabPanel({
	          //    el: 'error-tabs',
	          //    autoTabs:true,
	          //    activeTab:0,
	          //    deferredRender:false,
	          //    border:false
	          //}),
	          items: new Ext.TabPanel({
			       activeTab: 0,
					plain:true,
        			defaults:{autoScroll: true},

			       items:[{
			                title: 'Error Information',
			                html: "<b>Message:</b><br>"+this.getText()+"<br><b>Type:</b><br>"+this.getCode()
			            },{
			                title: 'Advanced Info...',
			                html:"<b>JSON:</b> "+this.getJSON()+"<br><b>Response Text:</b> "+this.response
            		   }]
		   	 }),

	
	          buttons: [/*{
	              text:'Email More Information To Webmaster...',
	              disabled:this._emailmore,
	              handler: function(){
	                  
	              }
	          },*/{
	              text: 'Close',
	              handler: function(){
	                  err_win.hide();
	              }
	          }]
	      });
	   }
	   err_win.show(this);
	   
	   /* TRY SEND AN EMAIL REPORT... we need a emailwebmaster.php in backend that sends error reports... would need a secret or something to prevent abuse
	   */
	}
	
	try 
	{
		this.responseObject = Ext.util.JSON.decode( '(' + this.response + ')');
	} 
	catch(err)
	{
		// there is a syntax error in the response!
		this.showPreParseError( "A Syntax Error exists in the JSON of the Wrapper Response object from the server. This maybe due to a fault in the server side code.");
		return;
	}
	var resp = this.responseObject;
	this.JSON = resp.json;
	this.Text = resp.text;
	this.Data = resp.data;
	this.XML = resp.xml;
	this.Code = resp.code;
   	
   	if( Boolean(typeof resp.debug != 'undefined' && resp.debug) )
		this._debug = resp.debug;
	else
		this._debug = false;
		
	if( !this._debug )
		this._emailmore = true; 
	else
		this._emailmore = false;
		
	// *****************	
	// Constructor code
	var retobj = null;
	if( this.JSON != "" ) 
	{
		try 
		{
			this.returnObject = Ext.util.JSON.decode( '(' + this.JSON + ')');
			retobj = this.returnObject;
		} 
		catch(err)
		{
			// there is a syntax error in the response!
			this.showPreParseError( "A Syntax Error exists in the JSON of the function return object contained in the Response object from the server. This maybe due to a fault in the server side code.");
			return;
		}
    } else
    	this.returnObject = null;
    	
   	// if error or warning+debugmode
   	if( (this.Code == -1) || ((this.Code == 1)&(this._debug)) )
   	{
   		this.displayError();
   	} 	
}


function startSpinner(name, parent)
{
    c = document.getElementById( "spinner_"+name );
    if( !c ) {
        d = document.createElement("div");
        d.style.backgroundImage = "url(./images/big-spinner.gif)";
        d.style.backgroundRepeat = "no-repeat";
		d.style.backgroundPosition = "center center";
        d.style.height="32px";
        d.style.position = "relative";
        d.id = "spinner_"+name;
        document.getElementById(parent).appendChild( d );
    }
}

function stopSpinner(name, parent)
{
    d = document.getElementById( "spinner_"+name );
    if( d ) {
        document.getElementById(parent).removeChild( d );
    }
}


function closeJobBox(name)
{
	document.getElementById(name).innerHTML = "";
	document.getElementById(name).style.marginTop = '';
	document.getElementById(name).style.marginBottom = '';
	document.getElementById(name).style.padding = '';
	document.getElementById(name).style.border = '';
}

function openJobBox(name)
{
	document.getElementById(name).style.marginTop = '15px';
	document.getElementById(name).style.marginBottom = '30px';
	document.getElementById(name).style.padding = '10px';
	document.getElementById(name).style.border = '1px solid #ccc';
}


function showErrorElement(e) {
    e.setStyle('background-color', '#cFF');  
    //e.scrollIntoView('signup_form_container');
}
/***************************************************************/

function getCheckedRadioValue( radios )
{
    for( i=0; i < radios.length; i++ )
    {
        if( radios[i].checked )
            return radios[i].value;
    }
    return false;
}

function outputError( errtext )
{
    if( errtext != "" ) {
        var el = document.getElementById("resultbox");
        el.className = "alert";
        el.innerHTML = "<div class=\"alert\"><p>" + errtext + "</p></div>";
    }
}
function outputMessage( text) 
{
    if( text != "" ) {
        var el = document.getElementById("resultbox");
        el.className = "message";
        el.innerHTML = "<div class=\"message\"><p>" + text + "</p></div>";
    }
}

function outputAdminError( errtext )
{
    if( errtext != "" ) {
        var el = document.getElementById("resultbox");
        el.className = "error";
        el.innerHTML = "<p class=\"error\">" + errtext + "</p>";
    }
}
function outputAdminMessage( text) 
{
    if( text != "" ) {
        var el = document.getElementById("resultbox");
        el.className = "success";
        el.innerHTML = "<p class=\"success\">" + text + "</p>";
    }
}

function addSelectOption(sel, text, value)
{
    var elOptNew = document.createElement('option');
    elOptNew.text = text;
    elOptNew.value = value;
    try {
    	sel.add(elOptNew, null); // standards compliant; doesn't work in IE
    }
    catch(ex) {
    	sel.add(elOptNew); // IE only
    }
}  

function clearSelect( sel )
{
    while (sel.length > 0)
    {
        sel.remove(sel.length - 1);
    }
}
  
function loadXML( text )
{
      // code for IE
    if (window.ActiveXObject) {
    	var doc=new ActiveXObject("Microsoft.XMLDOM");
    	doc.async="false";
    	doc.loadXML(text);
    } else {
    	// code for Mozilla, Firefox, Opera, etc.
    	var parser=new DOMParser();
    	var doc=parser.parseFromString(text,"text/xml");
    }
    
    // documentElement always represents the root node
    var x=doc.documentElement;
    return x;
}

function showHide(elname, callOnShow, callOnHide)
	{
    	el = document.getElementById(elname);
    	if (!el)
        	return;
    	if (el.style.display=="block") { // or use"visible/hidden"
        	el.style.display="none";
        	callOnHide();
        } else {
        	el.style.display="block";
        	callOnShow();
        }    
    }

