var AJAXRequestArray = new Array();
var FormName='';
var iCount=0;
var bQueue=false;

function fAJAXQueue( sTargetID , sURL , sPost , sWait , sError )
{
    
    var me = new Object();

    me.TargetID = sTargetID;
    me.URL = sURL;
    me.Post = sPost;
    me.Wait = sWait;
    me.Error = sError;
    me.Complete = false;
        
	AJAXRequestArray[AJAXRequestArray.length]=me;
    

}

function fProcessAJAXQueue()
{


    var x=0; 
    var len=AJAXRequestArray.length;
    
    for (x=0; x<len; x++) 
    { 

        if (AJAXRequestArray[x].Complete == false) {
		
		//alert('get ' + AJAXRequestArray[x].Post + ' from the queue ');
	
		// Oct 24.2008 use EVAl to run java commands if no TagetID
		if (AJAXRequestArray[x].TargetID == '') {
	
			//alert(AJAXRequestArray[x].Post);
	    		eval(AJAXRequestArray[x].Post);
	       		AJAXRequestArray[x].Complete = true;

		}
		else {
			bQueue=true;
           	 	fAJAXRequest( AJAXRequestArray[x].TargetID, AJAXRequestArray[x].URL, AJAXRequestArray[x].Post, AJAXRequestArray[x].Wait, AJAXRequestArray[x].Error); 
			bQueue=false;
	       		AJAXRequestArray[x].Complete = true;

			// EXIT THE LOOP because ONCHANGE will grab the next item in the queue
     			x=len+1;

	    	}



        }

    }   
    
    //fProcessAJAXQueue();
}

//fAJAXRequest
//
// client function for use in scripts
//
// parameters:
//
// sTargetID		= HTML ID of target DIV in which to dump returned data
// sURL				= URL to send request to
// sPost			= POST data to send, if "" then GET request is made (NOTE: GET may cache, this is a feature, not a bug!)
// sWait			= Text to display in target DIV whilst request is being made, "" = dont change current content
// sError			= Text to display in target DIV if error occurs, "" = dont change current content
//
function fAJAXRequest( sTargetID , sURL , sPost , sWait , sError )
{

//window.alert(sPost);

	// Oct 24.2008 use EVAl to run java commands if no TagetID
	if (sTargetID == '') {

		eval(sPost);

	}
	else	{

		var e = document.getElementById( sTargetID );
	
		if( e )
		{
			if( sWait != "" )
				e.innerHTML = sWait;		
				
			new oAJAXRequest( e , sURL , sPost , sError, bQueue );
		}
	}
}


// THE FOLLOWING ARE THE BACK END FUNCTIONS


// AJAX object state and response tracker function
//
// my server-scripts will always send back the first line as "200\n" if succesfull
//
// parameters:
//
// hAJAXRequest		= handle to request object
//
function fAJAXStateChange( hAJAXRequest, bIsQueued )
{


	if( hAJAXRequest && hAJAXRequest.mRequest && hAJAXRequest.mRequest.readyState == 4 )
	{
		var s = hAJAXRequest.mRequest.responseText;
		var mdiv = document.getElementById(hAJAXRequest.mhTarget.id);

		//alert ( hAJAXRequest.mhTarget.innerHTML );
		//alert( s.substring(4) );

		if( hAJAXRequest.mRequest.status == "200" && s.substr(0,3) == "200" )
		{
			hAJAXRequest.mhTarget.innerHTML = s.substring(4);
			
			// Because we exit the Queue we need to get the next request from the queue
			// this is not so good, because it goes to the queue everytime
			if (bIsQueued==true)
				fProcessAJAXQueue(); // go get the next one !!!
		}
		else
		if( hAJAXRequest.msError != "" )
		{
			hAJAXRequest.mhTarget.innerHTML = hAJAXRequest.msError;		
		}
	}
}

// AJAX object
//
// parameters:
//
// hTarget			= handle to target div (or whatever) we want to dump the returned HTML in
// sURL				= url to make request to
// sPost			= POST form data to send (leave as "" to make GET request)
// sError			= HTML to put in target div if request failed
//
// members:
//
// mRequest			= browser's own request object
// mhTarget			= hTarget
// msError			= sError
//
function oAJAXRequest(hTarget , sURL , sPost , sError, bIsQueued )
{

	//window.alert(sPost);

	if (sPost.substr(0,11)=='POSTGRIDROW') {

		//window.alert(sPost);

		var FormName=fFormName(sPost);
		if ( (formIsDirty(FormName)==true) || (bDirty==true) ) 
			sPost=sPost + fFormFields(FormName);
		else
			sPost='';

		//bDirty=false;

		//window.alert(sPost);

	}

	var me = this;
	this.mRequest	= null;
	this.mhTarget	= hTarget;
	this.msError	= sError;

	//do NOT use try{}catch as it is not supported in very old browsers and the script will not compile
	if( window.XMLHttpRequest )	//FF,NS,OP,IE7
	{
		this.mRequest = new XMLHttpRequest();
	}
	else
	if( window.ActiveXObject )	//IE5 & 6
	{
		this.mRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
	}

	if( this.mRequest )
	{
		if( sPost != "" )
		{
			this.mRequest.open( 'POST', sURL , true );
			this.mRequest.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			this.mRequest.onreadystatechange = function(){ fAJAXStateChange(me, bIsQueued); };
			this.mRequest.send( sPost );	
		}
		else
		{
			this.mRequest.open( 'GET', sURL , true );
			this.mRequest.onreadystatechange = function(){ fAJAXStateChange(me. bIsQueued); };
			this.mRequest.send( null );	
		}
	}
}	

function fFormName (sPost) {

	//var FormName=''
	if (sPost.indexOf('&')>0)
		FormName = sPost.substr(12,sPost.indexOf('&')-12);
	else
		FormName = sPost.substr(12,25);


	if (FormName.indexOf('NEXT') > 0 ) {

		var thisRowName = 'tr' + FormName.replace(/\D/g,'');
		var thisRow = parent.window.document.getElementById(thisRowName);
		var table = parent.window.document.getElementById('dataGrid');
		var tbody = table.getElementsByTagName("tbody")[0];	

		var nextRow = table.rows[thisRow.rowIndex-1]; // row already moved
		var nextForm = nextRow.getElementsByTagName("form")[0];
        bDirty = true; 
		FormName = nextForm.id;

	}


	if (FormName.indexOf('PREV') > 0 ) {

		var thisRowName = 'tr' + FormName.replace(/\D/g,'');
		var thisRow = parent.window.document.getElementById(thisRowName);
		var table = parent.window.document.getElementById('dataGrid');
		var tbody = table.getElementsByTagName("tbody")[0];	

		var nextRow = table.rows[thisRow.rowIndex+1]; // row already moved
		var nextForm = nextRow.getElementsByTagName("form")[0];
        bDirty = true;
		FormName = nextForm.id;

	}


	return FormName;
}

function fFormFields (FormName) {


	//window.alert(FormName);

	var Fields='';
	var Form = parent.window.document.forms[FormName];

	for (i=0; i < Form.elements.length; i++){
		if(Form.elements[i].value != ""){
			//alert(Form.elements[i].name);
			//alert(Form.elements[i].type);
			//alert(Form.elements[i].value);
			//if ( (Form.elements[i].type)!=button) && (Form.elements[i].type!=submit) )
			if (Form.elements[i].type!='button' && Form.elements[i].type!='submit')
				//window.alert(Form.elements[i].name);
				Fields = Fields + '&' + Form.elements[i].name + '=' + encodeURI(Form.elements[i].value);

		}
	
	}

	return Fields;
}

function fCheckOnhand(iQty, iOnhand) {
	if (iQty > iOnhand) {
		alert('The quantity entered exceeds the total quantity of items we have on hand.\nPlease enter a lesser quantity to continue.');
		return false;
	}
}

function fResizeSmartList() {
	
	//window.alert(parent.frames['ifSmartList'].document.body.scrollHeight);

	var iH=parent.frames['ifSmartList'].document.body.scrollHeight;
	var iW=parent.frames['ifSmartList'].document.body.scrollWidth;

	//window.alert(iH);

	if (iH > 200) 
		parent.window.document.getElementById('ifSmartList').style.height =iH + 5;
	else
		parent.window.document.getElementById('ifSmartList').style.height =200;

	if (iW > 750) 
		parent.window.document.getElementById('ifSmartList').style.width =iW + 5;
	else
		parent.window.document.getElementById('ifSmartList').style.width =755;

	}

	//window.alert(parent.window.document.getElementById('ifSmartList').style.height);


function AjaxFormField_onchange(strControl) 
{


	//AjaxFormField_onchange("frmGeneric550_frmGeneric550fix10_standard__fee")
	
	var RowName = 'tr' + strControl.substr(10,strControl.indexOf('_')-10);

	//window.alert(RowName);

	//window.alert(strControl);
	bDirty=true;

        parent.window.document.getElementById(RowName).bgColor='#d3d3d3';

}	


function fPopulateHoldDelay(oForm) {

    // Dec 11.2008
    // optional parameter oForm
    // sent when swapping sort order of two grid rows

//alert('PopulaetHoldDelay: FormName=' + FormName + ', oForm=' + oForm);


	iCount=0;

    if (typeof oForm != "undefined" && oForm != "") {
		fDisableUpdate(true);
		// Dec 17.2008
		// 100 in csae dev is long enough, at 400 the 2nd form is already in the HOLD
		setTimeout("fPopulateHold('" + oForm + "')",100);
	}
    else        
	    if (formIsDirty(FormName)==true) {
		    fDisableUpdate(true);
		    setTimeout("fPopulateHold('')",400);
	    }
}

function fPopulateHold(oForm) {

    // Dec 11.2008
    // optional parameter oForm
    // sent when swapping sort order of two grid rows
    
    var   strFormName = FormName;
    
    if (typeof oForm != "undefined" && oForm != "")
        strFormName = oForm;

//alert('PopulateHold: FormName=' + FormName + ', oForm=' + oForm + ', strFormName=' + strFormName);
    
	var RowName = 'tr' + strFormName.replace(/\D/g,'');


	var HoldForm = parent.window.document.forms[strFormName + 'HOLD'];
	var Form = parent.window.document.forms[strFormName];

	iCount = iCount + 1;	

	//window.alert(HoldForm.elements.length);
	

	//if (typeof HoldForm != "undefined")
	if (HoldForm!=null) {
		//txtHOLDError
		if (HoldForm.txtHOLDError!=null)
			window.alert(HoldForm.txtHOLDError.value);
		else	
			for (i=0; i < HoldForm.elements.length; i++){
				if(HoldForm.elements[i].value != ""){
					if (HoldForm.elements[i].type!='button' && HoldForm.elements[i].type!='submit')
						if (Form.elements[HoldForm.elements[i].name].value != HoldForm.elements[i].value)
							Form.elements[HoldForm.elements[i].name].value = HoldForm.elements[i].value;
				}
	
			}

       	parent.window.document.getElementById(RowName).bgColor='white';

//alert(strFormName + " has been refresh");

	    fDisableUpdate(false);
	}
	
	else
		if (iCount<5)
			setTimeout("fPopulateHold('" + strFormName + "')",800);
		else	{
			

			window.alert("error refreshing "+ strFormName);
			fDisableUpdate(false);
			}

}

function fDisableUpdate(bToggle)	{

	for (i=0; i < parent.window.document.forms.length; i++) {
		if (typeof parent.window.document.forms[i].btnSubmitAjax!="undefined")	{	
			//parent.window.document.forms[i].btnSubmitAjax.value=bToggle;
			parent.window.document.forms[i].btnSubmitAjax.disabled=bToggle;
		}
	}		
}


function fMoveSortDateRowDown(ThisRow) {   

	var table = parent.window.document.getElementById('dataGrid');
	var tbody = table.getElementsByTagName("tbody")[0];	
	var thisForm = ThisRow.getElementsByTagName("form")[0];
	var thisFormName = thisForm.id;

	var NextRow = table.rows[ThisRow.rowIndex+1];
	var nextForm = NextRow.getElementsByTagName("form")[0];

//window.alert(thisForm.elements.length);
//alert(ThisRow.bgColor);

//	if ( formIsDirty(thisFormName) != true  )  {

//  Dec 16.2008
//  the up/down link cannot be disabled like a button
//  so this will at least provide an error message,
//  but there are queued events that will still attempt to proceed so this is a poor solution until we can disable the entire up/down link
    if (ThisRow.bgColor=='#d3d3d3' || NextRow.bgColor=='#d3d3d3') 
        alert('Sorry, refresh is in progress.');
    else    {

		var thisDate = thisForm.elements['sort__date'].value;
		var thismmmDate = thisForm.elements['mmmsort__date'].value;
		var thisddDate = thisForm.elements['ddsort__date'].value;
		var thisyyDate = thisForm.elements['yysort__date'].value;
	
		thisForm.elements['mmmsort__date'].value = nextForm.elements['mmmsort__date'].value;
		thisForm.elements['ddsort__date'].value = nextForm.elements['ddsort__date'].value;
		thisForm.elements['yysort__date'].value = nextForm.elements['yysort__date'].value;
		thisForm.elements['sort__date'].value = nextForm.elements['sort__date'].value;

		nextForm.elements['mmmsort__date'].value = thismmmDate;
		nextForm.elements['ddsort__date'].value = thisddDate;
		nextForm.elements['yysort__date'].value = thisyyDate;
		nextForm.elements['sort__date'].value = thisDate;

		tbody.removeChild(NextRow);
		tbody.insertBefore(NextRow,ThisRow);


        bDirty=true;

        ThisRow.bgColor='#d3d3d3';
        NextRow.bgColor='#d3d3d3';
        
	}

}


function fMoveSortDateRowUp(ThisRow) {   

	var table = parent.window.document.getElementById('dataGrid');
	var tbody = table.getElementsByTagName("tbody")[0];	
	var thisForm = ThisRow.getElementsByTagName("form")[0];
	var thisFormName = thisForm.id;

	var NextRow = table.rows[ThisRow.rowIndex-1];
	var nextForm = NextRow.getElementsByTagName("form")[0];

//	if  ( formIsDirty(thisFormName) != true  ) {

//  Dec 16.2008
//  the up/down link cannot be disabled like a button
//  so this will at least provide an error message,
//  but there are queued events that will still attempt to proceed so this is a poor solution until we can disable the entire up/down link
    if (ThisRow.bgColor=='#d3d3d3' || NextRow.bgColor=='#d3d3d3') 
        alert('Sorry, refresh is in progress.');
    else    {


		var thisDate = thisForm.elements['sort__date'].value;
		var thismmmDate = thisForm.elements['mmmsort__date'].value;
		var thisddDate = thisForm.elements['ddsort__date'].value;
		var thisyyDate = thisForm.elements['yysort__date'].value;
	
		thisForm.elements['mmmsort__date'].value = nextForm.elements['mmmsort__date'].value;
		thisForm.elements['ddsort__date'].value = nextForm.elements['ddsort__date'].value;
		thisForm.elements['yysort__date'].value = nextForm.elements['yysort__date'].value;
		thisForm.elements['sort__date'].value = nextForm.elements['sort__date'].value;

		nextForm.elements['mmmsort__date'].value = thismmmDate;
		nextForm.elements['ddsort__date'].value = thisddDate;
		nextForm.elements['yysort__date'].value = thisyyDate;
		nextForm.elements['sort__date'].value = thisDate;

		tbody.removeChild(ThisRow);
		tbody.insertBefore(ThisRow,NextRow);

	    bDirty=true;

       ThisRow.bgColor='#d3d3d3';
       NextRow.bgColor='#d3d3d3';

	}


}
	




function fMoveSortTextRowDown(ThisRow) {   

	var table = parent.window.document.getElementById('dataGrid');
	var tbody = table.getElementsByTagName("tbody")[0];	
	var thisForm = ThisRow.getElementsByTagName("form")[0];
	var thisFormName = thisForm.id;



	var NextRow = table.rows[ThisRow.rowIndex+1];

	var nextForm = NextRow.getElementsByTagName("form")[0];

//window.alert(thisForm.elements.length);

//	if ( formIsDirty(thisFormName) != true  )  {

//  Dec 16.2008
//  the up/down link cannot be disabled like a button
//  so this will at least provide an error message,
//  but there are queued events that will still attempt to proceed so this is a poor solution until we can disable the entire up/down link
    if (ThisRow.bgColor=='#d3d3d3' || NextRow.bgColor=='#d3d3d3') 
        alert('Sorry, refresh is in progress.');
    else    {

		var thisSort = thisForm.elements['fix5_sort__seq'].value;
	
	
		thisForm.elements['fix5_sort__seq'].value = nextForm.elements['fix5_sort__seq'].value;

		nextForm.elements['fix5_sort__seq'].value = thisSort;

		tbody.removeChild(NextRow);
		tbody.insertBefore(NextRow,ThisRow);

        bDirty=true;

       ThisRow.bgColor='#d3d3d3';
       NextRow.bgColor='#d3d3d3';


    }

}


function fMoveSortTextRowUp(ThisRow,NextRow) {   

	var table = parent.window.document.getElementById('dataGrid');
	var tbody = table.getElementsByTagName("tbody")[0];	
	var thisForm = ThisRow.getElementsByTagName("form")[0];
	var thisFormName = thisForm.id;
	NextRow = table.rows[ThisRow.rowIndex-1];


	var nextForm = NextRow.getElementsByTagName("form")[0];

//	if  ( formIsDirty(thisFormName) != true  ) {


//  Dec 16.2008
//  the up/down link cannot be disabled like a button
//  so this will at least provide an error message,
//  but there are queued events that will still attempt to proceed so this is a poor solution until we can disable the entire up/down link
    if (ThisRow.bgColor=='#d3d3d3' || NextRow.bgColor=='#d3d3d3') 
        alert('Sorry, refresh is in progress.');
    else    {

    
		var thisSort = thisForm.elements['fix5_sort__seq'].value;
	
		thisForm.elements['fix5_sort__seq'].value = nextForm.elements['fix5_sort__seq'].value;

		nextForm.elements['fix5_sort__seq'].value = thisSort;

		tbody.removeChild(ThisRow);
		tbody.insertBefore(ThisRow,NextRow);

	    bDirty=true;

       ThisRow.bgColor='#d3d3d3';
       NextRow.bgColor='#d3d3d3';

	}



}


//Feb 11.2009
function fAddListener(ctlParent, ctlChild, lookupProc, required, action) {


	var parentSelEl = parent.window.document.getElementById(ctlParent);
    var tdEl = parent.window.document.getElementById('ajaxTD'+ctlChild);


	if (parentSelEl.addEventListener) { 
		parentSelEl.addEventListener('change', function() {fAJAXRequest(tdEl.id , 'scripts/AjaxContent.asp' , 'SELECTOPTIONS=REQ=' + required + '|P=' + lookupProc + '|K=' + ctlChild + '~' + parentSelEl.value , '&nbsp;&nbsp;<IMG src="scripts/graphics/indicator_white.gif">' , '');}, false); 
	} else if (parentSelEl.attachEvent) { 
		parentSelEl.attachEvent('onchange', function() {fAJAXRequest(tdEl.id , 'scripts/AjaxContent.asp' , 'SELECTOPTIONS=REQ=' + required + '|P=' + lookupProc + '|K=' + ctlChild + '~' + parentSelEl.value , '&nbsp;&nbsp;<IMG src="scripts/graphics/indicator_white.gif">' , '');} ); 
	} 

}


function fAddListener_debug(ctlParent, ctlChild, lookupProc, required, action) {


	var parentSelEl = parent.window.document.getElementById(ctlParent);
    var tdEl = parent.window.document.getElementById('ajaxTD'+ctlChild);


	if (parentSelEl.addEventListener) { 
		parentSelEl.addEventListener('change', function() {fAJAXRequest(tdEl.id , 'scripts/AjaxContent_d.asp' , 'SELECTOPTIONS=REQ=' + required + '|P=' + lookupProc + '|K=' + ctlChild + '~' + parentSelEl.value , '&nbsp;&nbsp;<IMG src="scripts/graphics/indicator_white.gif">' , '');}, false); 
	} else if (parentSelEl.attachEvent) { 
		parentSelEl.attachEvent('onchange', function() {fAJAXRequest(tdEl.id , 'scripts/AjaxContent_d.asp' , 'SELECTOPTIONS=REQ=' + required + '|P=' + lookupProc + '|K=' + ctlChild + '~' + parentSelEl.value , '&nbsp;&nbsp;<IMG src="scripts/graphics/indicator_white.gif">' , '');} ); 
	} 

}

function getOptionList(ctlParent, iNextCtl, required) {

    //var divEl = ctlParent.parentNode;
    
    var nextCtl = nextElement(ctlParent);    
    var nextCtlName = nextCtl.name;
    var tdEl = parent.window.document.getElementById('ajaxTD'+nextCtl.id);
    
	fAJAXRequest(tdEl.id , 'scripts/AjaxContent.asp' , 'SELECTOPTIONS=TAB=' + nextCtl.tabIndex + '|REQ=' + required + '|P=' + nextCtlName + '|K=' + nextCtlName + '~' + ctlParent.value , '&nbsp;&nbsp;<IMG src="scripts/graphics/indicator_white.gif">' , '');
}


function getOptionList_debug(ctlParent, iNextCtl, required) {

    //var divEl = ctlParent.parentNode;
    
    var nextCtl = nextElement(ctlParent);    
    var nextCtlName = nextCtl.name
    var tdEl = parent.window.document.getElementById('ajaxTD'+nextCtl.id);
    
	fAJAXRequest(tdEl.id , 'scripts/AjaxContent_d.asp' , 'SELECTOPTIONS=TAB=' + nextCtl.tabIndex + '|REQ=' + required + '|P=' + nextCtlName + '|K=' + nextCtlName + '~' + ctlParent.value , '&nbsp;&nbsp;<IMG src="scripts/graphics/indicator_white.gif">' , '');
}

function nextElement(el) {

    var f = el.form;
    var els = f.elements;
    var x, nextEl;
 
    for (var i=0, len=els.length; i<len; i++){
        x = els[i];


        if (x.tabIndex == el.tabIndex+1) {
    	    if (nextEl==null) {
                nextEl = x;
                i=len;
            }
        }

    }

return nextEl;

}

