//
// core_ajax.js - (C) 2007 The Whole Brain Group, LLC.
//

var boxVis = false;


/******************************************************************************/
/*                                                                            */
/* populateSwooshBox() makes a Swoosh Box visible, moves it to the proper x/y */
/*                     location, and makes an ajax call for content to stick  */
/*                     in the box.                                            */
/*                                                                            */
/* event      = JavaScript event object for the mouse down                    */
/* id         = name of the Swoosh Box to affect                              */
/* theQParams = the key/value pairs to send via POST.                         */
/* xLand      = the minimum number of pixels from the left edge of the window */
/* yLand      = the minimum number of pixels from the top edge of the window  */
/* headPad    = the number of pixels to allow for the page header/nav         */
/*                                                                            */
/******************************************************************************/
function populateSwooshBox(event, id, theQParams, xLand, yLand, headPad)
	{
	var el, x, y;
	el = document.getElementById(id);

	var theURL = theHost + siteFolder + 'ajax_' + swooshBoxes[id]['loc'].toLowerCase() + '.php';

	if (el.style.display == 'none' && !boxVis)
		{
		var paramsArray = theQParams.split('|');
		var theParams = '';
		
		theParams += 'loc=' + swooshBoxes[id]['loc'] + '&act=' + swooshBoxes[id]['act'];
		
		var fieldMax = 4;
		
		for (i = 0; i < fieldMax; i++)
			{
			var theVal = swooshBoxes[id]['param' + i];
			
			if (theVal != '')
				{
				theParams += '&' + swooshBoxes[id]['param' + i] + '=' + paramsArray[i];
				}
			}
		
			
		callAJAX(swooshBoxes[id]['loc'], swooshBoxes[id]['act'], theParams, theURL);
	
		var scrollX = 0;
		var scrollY = 0;
	
		if ( document.documentElement && document.documentElement.scrollLeft )
			{
			scrollX = document.documentElement.scrollLeft;
			}
		else if ( document.body && document.body.scrollLeft )
			{
			scrollX = document.body.scrollLeft;
			}
		else if ( window.pageXOffset )
			{
			scrollX = window.pageXOffset;
			}
		else if ( window.scrollX )
			{
			scrollX = window.scrollX;
			}
			
		if ( document.documentElement && document.documentElement.scrollTop )
			{
			scrollY = document.documentElement.scrollTop;
			}
		else if ( document.body && document.body.scrollTop )
			{
			scrollY = document.body.scrollTop;
			}
		else if ( window.pageYOffset )
			{
			scrollY = window.pageYOffset;
			}
		else if ( window.scrollY )
			{
			scrollY = window.scrollY;
			}

		if (window.event)
			{
			//this is for 
			xStart = window.event.clientX + scrollX;
			yStart = window.event.clientY + scrollY;
			}
		else
			{
			//this is for Firefox
			xStart = event.clientX + scrollX;
			yStart = event.clientY + scrollY;
			}
			
		//set margin from top of window
		//var xGap = 15;
		//var yGap = 25;
			
		//tweak margin to keep it off the header
		if (scrollY < headPad)
			{
			yLand = headPad - scrollY;
			}
		
		//x and y of end point
		var xEnd = scrollX + xLand;
		var yEnd = scrollY + yLand;
		
		//distance to travel from click point to end point
		var xDist = xEnd - xStart;
		var yDist = yEnd - yStart;
			
		el.style.left = xStart + 'px';
		el.style.top  = yStart + 'px';
		
		var theName = el.id + 'Form';
		
		//window.setTimeout(function(){
		//	appearSwooshBox(el, xDist, yDist); // takes forever!
		//	selectFirstUserInput(theName); // goes fast, but depends on appearSwooshBox		
		//},5000);
		
		appearSwooshBox(el, xDist, yDist);
		
		//alert('slow down');
		
		//Form.focusFirstElement(document[theName]);
		}
	}



/******************************************************************************/
/*                                                                            */
/* callAJAX() sends and receives ajax calls to Prototype. It's used all over. */
/*            The function takes these parameters:                            */
/*                                                                            */
/* theLoc =        the value of loc for this request.                         */
/* theAct =        the value of act for this request.                         */
/* theAJAXParams = the key/value pairs to send via POST.                      */
/* theURL        = the fully-formed url of the page that receives the request.*/
/*                                                                            */
/******************************************************************************/
function callAJAX(theLoc, theAct, theAJAXParams, theURL)
	{
	//new capability as of 7/2/08: pick theInputDivName and theResultJS out of theAJAXParams if they're present.
	//instructions for use in core_ajax.js for the function parseRespLoc().
	//dynDiv[0] = the response div
	//dynDiv[1] = the JavaScript to call
	//
	//note, if the value of dynDiv[0] is 'recID', then reset some stuff to just do the js part.
		
	if (writeRetrievedResp[theAct] == undefined)
		{
		//looks like we need to look for dynamic values
		var dynDiv = parseRespLoc(theAJAXParams);
		
		var theInputDivName = dynDiv[0];
		var theResultJS = dynDiv[1];
		var returnRecIDFlag = 0;
		
		if (theInputDivName == 'recID')
			{
			theInputDivName = '';
			returnRecIDFlag = 1;		
			}
		//else
		//	{
		//	alert ('callAJAX() in core_ajax.js says: Please look in site_ajax.js and define an instance for writeRetrievedResp[\'' + theAct + '\'] to specify what you want to do with the data/code being returned by the ajax_' + theLoc.toLowerCase() + '.php file.');
		//	return false;
		//	}
		}
	else
		{
		//proceed with the use of values in writeRetrievedResp
		var theParams = writeRetrievedResp[theAct];
		var theInputDivName = theParams['responsediv'];
		var returnRecIDFlag = theParams['returnRecID'];
		var theResultJS = theParams['resultJS'];
		}
	
	
//	if (theInputDivName == '' && theResultJS == '')
//		{
//		alert ('callAJAX() in core_ajax.js says: No response container or JavaScript action has been set for this ajax call. You need at least one or the other. Look in site_ajax.js where you have defined the instance for writeRetrievedResp[\'' + theAct + '\'] and make sure you have the first or third parameters filled in with valid values.');
//		}
//	else
//		{
		var myAjax = new Ajax.Request(theURL, {method: 'post', parameters: theAJAXParams, encoding: 'UTF-8', requestHeaders: ('Content-Type', 'application/x-www-form-urlencoded'), onSuccess: processResponse});
//		}
	
		
	function processResponse()
		{
		var theResponse = myAjax.transport.responseText;
		
		if (theInputDivName != '')
			{
			var theContainer = document.getElementById(theInputDivName);

//			if(theContainer == undefined)
//				{
//				alert('processResponse() in core_ajax.js says: The Div ID you specified for displaying the returned data/code does not exist on this page.  Please look in the site_ajax.js file where you defined writeRetrievedResp[\'' + theAct + '\'] and change the first param (' + theInputDivName + ') to refer to a Div ID that actually exists.\n\nAlternatively, you could add the code <div id="' + theInputDivName + '"></div> to this page in the location where you want to display the returned data/code.\n\nIf you want to direct output to a Javascript, make sure you specify that instead.');
//				}
//			else
//				{
				theContainer.innerHTML = theResponse;
				theResponse.evalScripts();
//				}
			}
		
		if (theResultJS != '')
			{
			var theRecID = theResponse;
			eval(theResultJS);
			}
		}
	}


/******************************************************************************/
/* updateStatus() displays a progress or status indicator based on the value  */
/*                of 'act'. It taps the statusFlags JS object for instructions*/
/*                                                                            */
/*                act = value of act                                          */
/*                                                                            */
/******************************************************************************/
function updateStatus(theAct)
	{
	if (statusFlags[theAct])
		{
		var theParams = statusFlags[theAct];

		if (theParams['name'] == 'generalProgress')
			{
			var theProgressIndicator = document.getElementById('generalProgress');
			theProgressIndicator.style.display = 'inline';
			}
		else
			{
			if (theParams['type'] == 'text')
				{
				var theMessage = '<span class="statusBox">'+ statusFlags[theAct]['message']  +'</span>';
				}
			else
				{
				var theMessage = statusFlags[theAct]['message'];
				}
				
			var theDivName = statusFlags[theAct]['name'];
			var theStatusFlag = document.getElementById(theDivName);
			
//			if(theStatusFlag == undefined)
//			{
//				alert( 'updateStatus() in core_ajax.js says: The Div ID you specified for displaying the status indicator/message does not exist on this page.  Please look in the site_ajax.js file where you defined statusFlags[\'' + theAct + '\'] and change the first param (' + theDivName + ') to refer to a Div ID that actually exists.\n\nAlternatively, you could add the code <div id="' + theDivName + '"></div> to this page in the location where you want to display the status indicator.');
//			}
			theStatusFlag.innerHTML = theMessage;
			}
		}
	}


/******************************************************************************/
/* zeroStatus() blanks out a status or progress indicator.                    */
/*                                                                            */
/*              theID = HTML element that contains the indicator.             */
/*                                                                            */
/******************************************************************************/
function zeroStatus(theID)
	{
	var theParams = statusFlags[theID];
	var theMessage = '';
	var theDivName = statusFlags[theID]['name'];
	var theStatusFlag = document.getElementById( theDivName );
	
	theStatusFlag.innerHTML = theMessage;
	}


/******************************************************************************/
/* zeroSwooshBox() blanks out a swoosh box on submit or cancel.               */
/*                                                                            */
/*                 theID = HTML element where the contents of the swoosh box  */
/*                         are punched in.
/*                                                                            */
/******************************************************************************/
function zeroSwooshBox(theID)
	{
	var theInputDivName = swooshBoxes[theID]['inputdiv'];
	var theInputDiv = document.getElementById( theInputDivName );
	
	theInputDiv.innerHTML = '&nbsp;&nbsp;<img src="' + theHost + brainstemFolder + 'wb_cerebellum/media/ajax_loader_sm.gif"><i>&nbsp;&nbsp;&nbsp;Setting up...</i><br><br><br>';
	}


/******************************************************************************/
/* hideSwooshBox() is an aggregating function called when a Swoosh Box is     */
/*                 closed                                                     */
/*                                                                            */
/*                 el = name of the swoosh box div.                           */
/*                                                                            */
/******************************************************************************/
function hideSwooshBox(el)
	{
	var theBox = document.getElementById(el);
	disappearSwooshBox(theBox, 'Fold');
	zeroSwooshBox(el);
	}


/******************************************************************************/
/* reSort() sorts records displayed by drawList() or drawIndex().             */
/*                                                                            */
/*          theForm  = name of the hidden form storing sort and search params.*/
/*          theSort  = name of sort field.                                    */
/*          theOrder = sort order.                                            */
/*          useThis  = 'data' or 'raw', depending on how sort should be done. */
/*                                                                            */
/******************************************************************************/
function reSort(theForm, theSort, theOrder, useThis)
	{
	//theSort is the actual field name in fmp.
	//theOrder is either ascend or descend.

	theForm = document[theForm];
	
	//add these values to the form
	theForm['SortField'].value = theSort;
	theForm['SortOrder'].value = theOrder;
	theForm['UseThis'].value = useThis;

	//get these values from the form
	var theLoc = theForm['loc'].value;
	var theAct = theForm['act'].value;
		
	//specify the ajax file
	var theURL = theHost + siteFolder + 'functions/site_ajax_resort.php';

	//make key/value pairs
	var theParams = makeFormElementsParam(theForm);
	
	callAJAX(theLoc, theAct, theParams, theURL);
	}


/******************************************************************************/
/* rePage() punches in another page displayed by drawList() or drawIndex().   */
/*                                                                            */
/*          theForm     = name of the hidden form storing sort and search     */
/*                        params.                                             */
/*          thePageNum  = page id to display (0 is the first page).           */
/*                                                                            */
/******************************************************************************/
function rePage(theForm, thePageNum)
	{
	//thePageNum is the number of the group to display.
	var theForm = document[theForm];
	
	//add these values to the form
	theForm['PageNum'].value = thePageNum;
	
	//if(theForm['ReSort'] != undefined)
	//{
	//	theForm['ReSort'].value = '0';
	//}
	
	//get these values from the form
	var theLoc = theForm['loc'].value;
	var theAct = theForm['act'].value;
	
	//specify the ajax file
	var theURL = theHost + siteFolder + 'functions/site_ajax_resort.php';

	//make key/value pairs
	var theParams = makeFormElementsParam(theForm);
	
	callAJAX(theLoc, theAct, theParams, theURL);
	}


/******************************************************************************/
/* sortSideBar() wraps reSort when used in a sidebar.                         */
/*                                                                            */
/*          theForm  = name of the hidden form storing sort and search params.*/
/*          theSort  = name of sort field.                                    */
/*                                                                            */
/******************************************************************************/
function sortSideBar(theFormName, theSourceForm, theSort)
	{
	if (theSort == '')
		{
		return false;
		}
	else
		{
		//pull values for sort order and array to use from hidden form elements
		var theIndex = theSourceForm['sidebarSorter'].selectedIndex - 1;
	
		var theOrderString = theSourceForm['SortPopOrder'].value;
		var theUseString = theSourceForm['SortUseOrder'].value;
		
		var theOrderArray = theOrderString.split('|');
		var theUseArray = theUseString.split('|');
	
		//call resort
		reSort(theFormName, theSort, theOrderArray[theIndex], theUseArray[theIndex]);
		}
	}


/*****************************************************************************/
/*                                                                           */
/* ajaxParams() creates a sub-object for a given Swoosh Box.                 */
/*                                                                           */
/*              name =     name of the Swoosh Box                            */
/*              loc =      loc                                               */
/*              act =      act                                               */
/*              inputdiv = html element where the contents will land         */
/*              param0 =   first field (usually recID)                       */
/*              param1 =   second field                                      */
/*              param2 =   third field                                       */
/*              param3 =   fourth field                                      */
/*                                                                           */
/*****************************************************************************/
function ajaxParams(theName, theLoc, theAct, theInputDiv, param1, param2, param3, param4)
	{
	this['name'] = theName;
	this['loc'] = theLoc;
	this['act'] = theAct;
	this['inputdiv'] = theInputDiv;
	this['param0'] = param1;
	this['param1'] = param2;
	this['param2'] = param3;
	this['param3'] = param4;
	}


/*****************************************************************************/
/*                                                                           */
/* statusFlagParams() creates a sub-object for a given Status Flag. Params   */
/*                                                                           */
/*                    name    = id of the Status Flag div             	     */
/*                    act     = act                                          */
/*                    message = message                                      */
/*                    type    = type                                         */
/*                                                                           */
/*****************************************************************************/
function statusFlagParams(theName, theAct, theMessage, theType)
	{
	this['name'] = theName;
	this['act'] = theAct;
	this['message'] = theMessage;
	this['type'] = theType;
	}


/*****************************************************************************/
/*                                                                           */
/* writeRetrievedParams() creates a sub-object for a given Write Retrieved   */
/*                        Action.                                            */
/*                                                                           */
/*                        responsediv = id of the ResponseDiv                */
/*                        resultJS    = JS to evaluate on response           */
/*                        returnRecID = set to 1 if you want to return the   */
/*                                      RecID as the response                */
/*                                                                           */
/*****************************************************************************/
function writeRetrievedParams(theResponseDiv, theResultJS, theReturnRecIDFlag)
	{
	this['responsediv'] = theResponseDiv;
	this['resultJS'] = theResultJS;
	this['returnRecID'] = theReturnRecIDFlag;
	}


/******************************************************************************/
/*                                                                            */
/* makeFormElementsParam() creates a series of parameter pairs in the format  */
/*                         this=that&these=those from the elements of a form  */
/*                                                                            */
/* theForm = the name of the form to process.                                 */
/*                                                                            */
/******************************************************************************/
function makeFormElementsParam(theForm)
	{
	var theParams = '';
	
	for (i = 0; i < theForm.length; i++)
		{
		var theValue = '';
		var theElement = theForm.elements[i];
		
		if (i != 0)
			{
			theParams += '&';
			}
			
		if (theForm.elements[i].type == 'checkbox' || theForm.elements[i].type == 'radio')
			{
			if (theElement.checked)
				{
				theValue += theElement.value;
				}
			}
		else
			{
			theValue += encodeURIComponent(theForm.elements[i].value);
			}
		
		theParams += theForm.elements[i].name + '=' + theValue;
		}

	return theParams;
	}


/*****************************************************************************/
/*                                                                           */
/* selectFirstUserInput() places the cursor in the first user input in a     */
/*                        form, provided the first input is a textarea or    */
/*                        single-line text input. If the first input type is */
/*                        a popup list (select), it is highlighted.          */
/*                                                                           */
/* theForm = the name of the form to take action on.                         */
/*                                                                           */
/*****************************************************************************/
function selectFirstUserInput(theForm)
	{
	for (i = 0; i < document[theForm].length; i++)
		{
		if (document[theForm].elements[i].type == 'text' || document[theForm].elements[i].type == 'textarea' || document[theForm].elements[i].type == 'select-one')
			{
			document[theForm].elements[i].focus();
			if (document[theForm].elements[i].type == 'text' || document[theForm].elements[i].type == 'textarea')
				{
				document[theForm].elements[i].select();
				}
			return false;
			}
		}
	return true;
	}



/*****************************************************************************/
/*                                                                           */
/* showSwooshBox() contols how a swooshBox appears and moves.                */
/*                                                                           */
/*                 el    = the name of the div to display                    */
/*                 xDist = the horizontal distance to travel                 */
/*                 yDist = the vertical distance to travel                   */
/*                                                                           */
/*****************************************************************************/
function appearSwooshBox(el, xDist, yDist)
	{
	boxVis = true;

	new Effect.Appear(el, {duration: 0.45});
	//new Effect.Move (el,{ x: xDist, y: yDist, mode: 'relative', duration: 0.5,  fps: 200});
	new Effect.Move (el,{ x: xDist, y: yDist, transition: Effect.Transitions.spring, mode: 'relative', duration: 1.5,  fps: 100});
	}


/*****************************************************************************/
/*                                                                           */
/* disappearSwooshBox() controls how a swooshBox disappears from the screen. */
/*                                                                           */
/*                      el        = the name of the div to hide              */
/*                      theEffect = the scriptaculous effect to use          */
/*                                                                           */
/*****************************************************************************/
function disappearSwooshBox(el, theEffect)
	{
	boxVis = false;

	if (theEffect == 'Fold')
		{
		Effect.Fold(el, {duration:0.1});
		}
	else
		{
		Effect.Fold(el, {duration:0.1});
		}
	}


/*****************************************************************************/
/*                                                                           */
/* parseRespLoc() looks for parameters called RespLoc and JSAction in the    */
/*                parameters fed to callAJAX(). If found, these items are    */
/*                returned and used to override the standard JS Object       */
/*                writeRetrievedResp usage. Note: if the value of RespLoc is */
/*                'recID', then the JSAction is triggered in callAJAX.       */
/*                                                                           */
/* theParams = parameters fed to callAJAX in query-pair format               */
/*                                                                           */
/*****************************************************************************/
function parseRespLoc(theParams)
	{
	var theParamArray = theParams.split('&');
	
	var respLoc = new Array();
	respLoc[0] = '';
	respLoc[1] = '';
	
	for (i = 0; i < theParamArray.length; i++)
		{
		//tease out a value of 'RespLoc', if any
		if (theParamArray[i].indexOf('RespLoc=') == 0)
			{
			var theRespPair = theParamArray[i].split('=');
			respLoc[0] = theRespPair[1]
			}
		
		//tease out a value of 'JSAction', if any
		if (theParamArray[i].indexOf('PostJS=') == 0)
			{
			var theRespPair = theParamArray[i].split('=');
			respLoc[1] = theRespPair[1]
			}
		}
		
	return respLoc;
	}
