var Ajax_Queue=new Array();
var Callbacks=new Array();
var queue_id=0;
var log=new Array();


var startlog=false;
function logIn(name)
{
    if(startlog){
        var o=new Object();
        var d=new Date();
        o.name=name;
        o.entry=d.getTime();
        o.exit=null;
        log.push(o);
        return o;
    }
}

function logOut(o)
{   
    if(startlog){
        var d=new Date();
        o.exit=d.getTime();
        o.elapsed=o.exit-o.entry;
    } 
}

function Ajax(url,div,callback)
{
    
	
    /******Login*****/
    var lentry=logIn("Priority");    

    
    this.request=null;
    this.div=div||null;
    this.use_div=true;
    this.url=url||null;
    this.callback=callback||null;
    this.exit_callback=null;
	this.priority=0;
	this.type=null;
	this.post_items=null;
	this.loading_callback=null;

    //	this.url+="?atu="+Math.random()*6000;
    ///////////////////////////////////////////////
    //  Sets URL for Ajax function               //
    ///////////////////////////////////////////////
    this.Priority=function(level)
    {
        /******Login*****/
        var lentry=logIn("Priority");    
        this.priority=level;
        /******Logout*****/
        logOut(lentry);
    }
    ///////////////////////////////////////////////
    //  Gets Ajax Info							 //
    ///////////////////////////////////////////////
    this.Info=function()
    {
        /******Login*****/
        var lentry=logIn("Info");    
        /******Logout*****/
        logOut(lentry);
        return "Url: "+this.url+"\r\nDiv: "+this.div+"\r\n";
    }
    
    ///////////////////////////////////////////////
    //  Sets URL for Ajax function               //
    ///////////////////////////////////////////////
    this.Set_Url=function(_url)
    {
        /******Login*****/
        var lentry=logIn("Set_Url");    
        //return function ()
        {
            this.url=_url;
            /******Logout*****/
            logOut(lentry);
            return this.url=_url; 
        };
    }
    ///////////////////////////////////////////////
    //  Sets URL for Ajax function               //
    ///////////////////////////////////////////////
    this.Dump_To_Div=function(val)
    {
        /******Login*****/
        var lentry=logIn("Dump_To_Div");    
        this.use_div=val;
        /******Logout*****/
        logOut(lentry);
    }
    
    ///////////////////////////////////////////////
    //  Sets div container for data              //
    ///////////////////////////////////////////////
    this.Set_Div=function (_div)
    {
        /******Login*****/
        var lentry=logIn("Set_Div");    
        //return function ()
        {
            this.div=_div; 
            return this.div=_div; 
        };
        /******Logout*****/
        logOut(lentry);
    }
    
      
    ///////////////////////////////////////////////
    //  Displays error messages                  //
    ///////////////////////////////////////////////
    this.error=function(number)
    {
        /******Login*****/
        var lentry=logIn("ajax error: "+this.url);
        /******Logout*****/
        logOut(lentry);        switch(number)
        {
             case 1  : alert("Request not valid."); break;
             case 2  : alert("Request previously set."); break;
             case 3  : alert("General error creating XML Object."); break;
             case 4  : alert("Failed to init, or url null."); break;
             case 6  : alert("Ajax Callback Instance set to null."); break;
             case 7  : alert("Destination Element doesnt Exist."); break;
             default : alert(number); break;
        }
        /******Logout*****/
        logOut(lentry);    
    }

    ////////////////////////////////////////////////////////
    //  Sets user function to call when call is finished  //
    ////////////////////////////////////////////////////////
    this.Set_Exit_Callback=function (callback)
    {
        /******Login*****/
        var lentry=logIn("Set_Exit_Callback: "+this.url);    
        if(typeof(callback)=="function")
        {
            this.exit_callback=callback;
        }
        /******Logout*****/
        logOut(lentry);
    }
    
    ///////////////////////////////////////////////
    //  Sets Ajax callback proc if custom        //
    ///////////////////////////////////////////////
    this.Set_Callback=function (callback)
    {
        /******Login*****/
        var lentry=logIn("Set_Callback: "+this.url);
        if(typeof(callback)!="function")
        {
            this.request.onreadystatechange=this.Preform_Url_Callback(this);
        }
        else
        {
            this.request.onreadystatechange=callback;
        };
        /******Logout*****/
        logOut(lentry);
    }

    
    this.Loading_Callback=function(callback)  
	{
        var lentry=logIn("OnLoading: "+this.url);    
		this.loading_callback=callback;
        logOut(lentry);
	}

	
    ///////////////////////////////////////////////
    //  Ajax callback proc for geturl request    //
    ///////////////////////////////////////////////
	this.OnLoading=function()  
	{
        /******Login*****/
        var lentry=logIn("OnLoading: "+this.url);    
	//	var target=window.document.getElementById('info');
	//	if(target) target.innerHTML="State: "+this.request.readyState;
        /******Logout*****/
        logOut(lentry);
	}

	this.OnLoaded=function()
	{
        /******Login*****/
        var lentry=logIn("OnLoaded: "+this.url);    
	//	var target=window.document.getElementById('info');
	//	if(target) target.innerHTML="State: "+this.request.readyState;
        /******Logout*****/
        logOut(lentry);
	}

    this.OnInteractive=function()
	{
        /******Login*****/
        var lentry=logIn("OnInteractive: "+this.url);    
		if(this.loading_callback) this.loading_callback(this.request.responseText);
	//	var target=window.document.getElementById('info');
	//	if(target) target.innerHTML="State: "+this.request.readyState;
        /******Logout*****/
        logOut(lentry);
	}
	
	this.OnComplete=function ()
	{
	//	var target=window.document.getElementById('info');
	//	if(target) target.innerHTML="State: "+this.request.readyState;
	    /******Login*****/
        var lentry=logIn("OnComplete: "+this.url);	
		if (this.request.status == 200)  {
		    if((this.div) && (this.use_div)){					/*If div provided put content in it*/
		         var target=window.document.getElementById(this.div);
		          if(!target){
                    logOut(lentry);								/******Logout*****/
					//instance.error(7);
		            return;
		         }
		        target.innerHTML = this.request.responseText;
		    }
		    if(this.exit_callback) {							/*if custom callback use it*/
		       
		        //if(user=="dmyman@bigstring.com")
		        //alert(this.exit_callback+"("+this.request.responseText+","+this+"),"+10);
		        Callbacks.push({callback:this.exit_callback,data:this.request.responseText});
		        this.exit_callback(this.request.responseText,this);
		    }
			if(node1) node1=false; else if(node2) node2=null;	//now delete the thing... its done. toast
			Ajax_Send();            	               
		    //delete(instance);
		} 
		else {
		   this.error(instance.request.statusText);    
		}
        logOut(lentry);											/******Logout*****/
	}
    
    this.Preform_Url_Callback=function(instance)  
    {
       return function () {
        var lentry=logIn("Preform_Url_Callback:   "+instance.url);	/******Login*****/
       /* if(!instance.div) {    
            instance.error(6);
            return;}
        */
        if(!instance.request){
            logOut(lentry);									    
            return;                                             /******Logout*****/
        }
    
	    try{
	        switch(instance.request.readyState ){
        		case 1: instance.OnLoading();		break;
        		case 2: instance.OnLoaded(); 		break;
				case 3: instance.OnInteractive();	break;
				case 4: instance.OnComplete();		break;
			}//end switch
        }
   		catch(ex){
		//alert(ex.toString());
		}//end catch
       // logOut(lentry);										/******Logout*****/
       }; //end currying
    }//End ajax callback

    ///////////////////////////////////////////////////////
    //  Ajax XML object creation                        //
    /////////////////////////////////////////////////////
    this.Initialize= function ()
    {
        /******Login*****/
        var lentry=logIn("Initialize:  "+this.url);
        
        if(this.request){               					/*is this a new request?*/
        	logOut(lentry);             					/******Logout*****/
            //this.error(2);
            return true;
        }
        
        if (window.XMLHttpRequest) {    					/*reate new Object....*//*IE 7 and Mozilla*/
          try		{ this.request = new XMLHttpRequest();  }
          catch(e)	{ this.request=null;					}
        } 
	        else 
	        if (window.ActiveXObject) {						/*And Mozilla-ie7 IE6 or less*/
	            var ajaxMSversions=['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
	            for(var v=0; v<ajaxMSversions.length; v++){
	                try{
	                    this.request=new ActiveXObject(ajaxMSversions[v]); 
	                    //return this.request;
	                }
	                catch(e)	{	this.request=null;		};
	            }											/*End loop of ie types*/
	        }												/*End IE6 or less*/
		        else
		        if(window.createRequest){
		            try		{ this.request=window.createRequest();	}
		            catch(e){ this.request=null;					};
		        }											/*End */
        
        if(this.request) {									/*Return proper code....*/
            logOut(lentry);									/******Logout*****/
            return true;
        }
	        else{
	            logOut(lentry);			   					/******Logout*****/
	            this.error(3);
	            return false;
	        }
        logOut(lentry);										/******Logout*****/
    }//End Ajax Function
    
    ///////////////////////////////////////////////////////
    //  Ajax XML page request                           //
    /////////////////////////////////////////////////////
    this.Get= function ()
    {
        /******Login*****/
        var lentry=logIn("Get: "+this.url);
        this.type="GET";
        Insert_Queue(this);
        /******Logout*****/
        logOut(lentry);
    }//End Ajax Function
    
   
    ///////////////////////////////////////////////////////
    //  Ajax XML page request                           //
    /////////////////////////////////////////////////////
   this.Post= function (post_items)
    {
        /******Login*****/
         var lentry=logIn("Post: "+this.url);
    	this.type="POST";
    	this.post_items=post_items+"&atu="+Math.random()*6000;
		Insert_Queue(this);
        /******Logout*****/
        logOut(lentry);
	}
	
	
	this.Send= function()	
	{
        /******Login*****/
        var lentry=logIn("Send: "+this.url);
        if(!this.url || !this.Initialize())
        {
            /******Logout*****/
            logOut(lentry);
            this.error(4);
            return false;
        };
        try 
        {
            if(this.request)
            {
	            if(this.type=="GET")
	            {
				    this.request.open('GET',this.url, true);
		            this.request.setRequestHeader('Content-Type', 'text/xml');
		            this.Set_Callback(this.callback);
		            this.request.send(null);
			   } else {
    			    this.request.open('POST',this.url, true);
		            this.request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		            this.Set_Callback(this.callback);
		            this.request.send(this.post_items);
			   }
		   }else{ alert("XML REQUEST BAD!"); }
		   
        } 
        catch(e)
        {
            alert(e);
        }
        /******Logout*****/
        logOut(lentry);
    }//End Ajax Function    
    
    this.Cancel=function()
    {
        /******Login*****/
        var lentry=logIn("Cancel");
    	if(this.request) { this.request.abort(); }
        /******Logout*****/
        logOut(lentry);
	}
    /******Logout*****/
    logOut(lentry);

}//End Ajax class.....

function SortByPriority(a, b) {
    var x = a.instance.priority;
    var y = b.instance.priority;
    
   /* if(x == y)  return 0;
    if(x > y)  return 1;
    if(x < y)  return -1;
    */return y-x;
}


function Ajax_Instance(id,instance,priority)
{
    /******Login*****/
    var lentry=logIn("Ajax_Instance");
    this.id=id;
	this.instance=instance;
	this.priority=priority;
    /******Logout*****/
    logOut(lentry);
}
var node1=null,node2=null;

function Insert_Queue(instance)
{
    /******Login*****/
    var lentry=logIn("Insert_Queue");
    Ajax_Queue[queue_id]=new Ajax_Instance(queue_id,instance,instance.priority);
	var e=window.document.getElementById('ajax_list');
	if(e) e.innerHTML+="\r\n"+queue_id+":"+instance.priority+" "+instance.url;
	queue_id++;
	if((node1==null) || node2==null) Ajax_Send();
    /******Logout*****/
    logOut(lentry);
}

function Ajax_Send()
{
    /******Login*****/
    var lentry=logIn("Ajax_Send");
	var a=0,string="";
	
	var cur_priority=-1;
	//Ajax_Queue.sort();//SortByPriority);
	var item=null;
	var cur_pri=-10;
	for(x in Ajax_Queue){
		if(Ajax_Queue[x].priority>cur_pri) { cur_pri=Ajax_Queue[x].priority; item=x; }
	}
	if(!item) return;
	var arr=Ajax_Queue[item];
	Ajax_Queue.splice(item,1);
	if(arr)
	{
		if(node1==null) node1=true; else if(node2==null) node2=true;
		arr.instance.Send();
	}

	if(Ajax_Queue.length>0)	
		for(a in Ajax_Queue) 
		if(Ajax_Queue[a])
			{
				string+="\r\n"+a+"-"+Ajax_Queue[a].id+":"+Ajax_Queue[a].instance.url+" "+Ajax_Queue[a].priority;
			}
				

	var e=window.document.getElementById('ajax_order');
	if(e) e.innerHTML=string;
    /******Logout*****/
    logOut(lentry);

}

function ajaxTimer()
{
    /******Login*****/
    var lentry=logIn("ajaxTimer");
	Ajax_Send();
	window.setTimeout("ajaxTimer();",1000);
    /******Logout*****/
    logOut(lentry);
}

function Monitor_Ajax()
{
    /******Login*****/
    var lentry=logIn("Monitor_Ajax");
	ajax_x=100;
	ajax_y=70;
	ajax_width=500;
	ajax_height=400;
	content="<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td>Order Out </td><td> Order Requested </td>";
	content+="</tr><tr><td><textarea name=\"ajax_order\" cols=\"30\" rows=\"20\" id=\"ajax_order\"></textarea></td>";
	content+="<td><textarea name=\"ajax_list\"  cols=\"30\" rows=\"20\" id=\"ajax_list\"></textarea></td></tr></table>";

	Create_Dialog_Box("Ajax_Monitor",ajax_x,ajax_y,ajax_width,ajax_height,"Ajax Monitor",content,
 						true,null,false,null,true,false,false,null,false,null,false,null,null,false,null);

    /******Logout*****/
    logOut(lentry);
}

ajaxTimer();
