var strAjaxDoPath = '/dios/ajaxDo'; // the full path to ajaxDo (this will be component-specific)

function sendControlDataOrgList(strControlData, tabId) {
	/**
	 * Send status of form controls to server to update SESSION vars
	 */
	sendRequest(strAjaxDoPath + '.php?anonMode=1&tabId='+tabId+'&action=setOrgListFilter&update=1', sendControlDataOrgList_Callback, strControlData);
}

function sendControlDataOrgList_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */

	// hide view content
	$('#viewContent').hide();

	// show hidden content message
	$('#hiddenContent').show();

	s = req.responseText;

	if (s != 'success') { // error
		if (s == 'error: not logged in') { // not logged in - open a login box in another window
			var winLogin = window.open('/dios/?pageDst=home', 'loginWindow');
		} else { // some other error - alert the user
			alert('There was a problem updating the Organisation List. The error returned was: ' + s);
		}
	} else { // success - finished updating SESSION vars, now update report list via ajax request
		// send regardless of ajax request status
		getOrgList_inline();

		// also, update text next to organisation filter
		updateOrgFilterText_inline();

		// re-draw chart if it is visible
		//if ($('#visualFilter').is(':visible')) {// chart is visible - re-draw it
			runChart();// embed flash
		//}
	}
}

function sendControlDataOrgListText_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */

	s = req.responseText;

	getObj('infoOrgs');
	obj.innerHTML = s;
}

function sendControlDataOrgListTextDem_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */
	$('#infoOrgsDemographic').html(req.responseText);
	/*s = req.responseText;
	getObj('infoOrgsDemographic');
	obj.innerHTML = s;*/
}

function sendControlDataNQPS(strControlData, tabId) {
	/**
	 * Send status of form controls to server to update SESSION vars
	 */
	// hide view content
	getObj('viewContent');
	if (obj!==undefined) {// object found
		//obj.style.display = 'none';
		$('#viewContent').hide();
	}

	// show hidden content message
	getObj('hiddenContent');
	if (obj!==undefined) {// object found
		//obj.style.display = 'block';
		$('#hiddenContent').show();
	}
	// update data scope filter
	sendRequest(strAjaxDoPath + '.php?anonMode=1&action=setDataScopeFilter&tabId='+tabId+'&update=1', sendControlDataNQPS_Callback, strControlData);
}// function sendControlDataNQPS

function sendControlDataNQPS_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */

	s = req.responseText;

	if (s != 'success') { // error
		if (s == 'error: not logged in') { // not logged in - open a login box in another window
			var winLogin = window.open('/dios/?pageDst=home', 'loginWindow');
		} else { // some other error - alert the user
			alert('There was a problem updating the Data Scope Filter. The error returned was: ' + s);
		}
	} else { // success - finished updating SESSION vars, now update report list via ajax request
		// update text next to data scope filter
		updateDataFilterText_inline();
		// update visual filter
		updateVisualFilter_inline();
		// update indicator export list if rendered
		if ($('#tree_indicators_box').length) updateIndicatorExportList();
	}
}// function sendControlDataNQPS_Callback

function sendControlDataNQPSText_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */

	s = req.responseText;

	getObj('infoScope');
	obj.innerHTML = s;
}// function sendControlDataNQPSText_Callback

function sendControlDataShowLocal(strControlData, tabId) {
	/**
	 * Send status of chkShowLocal to server to update SESSION var
	 */

	sendRequest(strAjaxDoPath + '.php?anonMode=1&action=setShowLocal&tabId='+tabId+'&setFlag=' . strControlData, sendControlDataShowLocal_Callback);
}

function sendControlDataShowLocal_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */

	s = req.responseText;

	if (s != 'success') { // error
		if (s == 'error: not logged in') { // not logged in - open a login box in another window
			var winLogin = window.open('/dios/?pageDst=home', 'loginWindow');
		} else { // some other error - alert the user
			alert('There was a problem updating the view page. The error returned was: ' + s);
		}
	} else { // success - finished updating SESSION vars
	}
}

function sendControlDataSearchOptions(strControlData, tabId) {
	/**
	 * Send status of form controls to server to update SESSION vars
	 */

	sendRequest(strAjaxDoPath + '.php?anonMode=1&tabId=' + tabId + '&action=setSearchOptions&update=1', sendControlDataSearchOptions_Callback, strControlData);
}// function sendControlDataSearchOptions

function sendControlDataSearchOptions_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */

	s = req.responseText;

	if (s != 'success') {// error
		if (s == 'error: not logged in') {// not logged in - open a login box in another window
			var winLogin = window.open('/dios/?pageDst=home', 'loginWindow');
		} else {// some other error - alert the user
			alert('There was a problem updating the search options. The error returned was: ' + s);
		}
	}/* else {// success - finished updating SESSION vars, now update report list via ajax request
		// update text next to data scope filter
		updateDataFilterText_inline();
	}*/

}// function sendControlDataSearchOptions_Callback

function sendControlDataViewPage(strControlData, tabId) {
	/**
	 * Send status of form controls to server to update SESSION vars
	 */
	sendRequest(strAjaxDoPath + '.php?anonMode=1&action=setDataViewPage&tabId='+tabId+'&update=1', sendControlDataViewPage_Callback, strControlData);
}

function sendControlDataViewPage_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */

	s = req.responseText;

	if (s != 'success') { // error
		if (s == 'error: not logged in') { // not logged in - open a login box in another window
			var winLogin = window.open('/dios/?pageDst=home','loginWindow');
		} else { // some other error - alert the user
			alert('There was a problem updating the view page. The error returned was: ' + s);
		}
	} else { // success - finished updating SESSION vars, now update report list via ajax request
		// send regardless of ajax request status

//		getOrgList_inline(); - TODO - for when we have a page which makes use of the data scope filter

	}

	getViewPage_inline(); // update view page via AJAX call
}

function getNQPSList(tabId) {
	/**
	 * Retrieve nqps list via ajax call
	 */

	// NOT USED AT THE MOMENT

	showLoadingMessage(); // show loading message

	sendRequest(strAjaxDoPath + '.php?anonMode=1&tabId=' + tabId + '&action=getDataScopeFilter', getNQPSList_Callback);

	return;
}

function getNQPSList_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */

	s = req.responseText;

	getObj('nqpsList');
	obj.innerHTML = s; // replace contents of element

	hideLoadingMessage(); // hide loading message
}

function getOrgList(tabId) {
	/**
	 * Retrieve organisation list via ajax call
	 */
	getObj('orgList');
	showLoadingMessage(obj); // show loading message
	//sendRequest(strAjaxDoPath + '.php?anonMode=1&tabId=' + tabId + '&action=getOrgListFilter', getReportList_Callback);
	$.get(strAjaxDoPath+'.php?anonMode=1&tabId='+tabId + '&action=getOrgListFilter', function(strHtml) {
		$('#orgList').html(strHtml);
		hideLoadingMessage();// hide the ajax loading message
	});
	return;
}

function getReportList_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 *
	 * DB: replaced with jquery code in getOrgList 07122011 (see DORS-337)
	 */
	s = req.responseText;
	getObj('orgList');
	obj.innerHTML = s; // replace contents of element

	hideLoadingMessage(); // hide loading message
}// getReportList_Callback

function getViewPage(tabId) {
	/**
	 * Retrieve view page via ajax call
	 */
	showLoadingMessage(); // show loading message

	sendRequest(strAjaxDoPath + '.php?anonMode=1&tabId=' + tabId + '&action=getDisplayReportView', getViewPage_Callback);

	return;
}

function getViewPage_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */

	s = req.responseText;

	getObj('viewer');
	obj.innerHTML = s; // replace contents of element

	hideLoadingMessage(); // hide loading message
}

function updateDataFilterText(tabId) {
	// load text next to data scope filter
	getObj('infoScope'); // data scope filter info text span
	obj.innerHTML='&nbsp;<span style="color: #000000;"><img src="/core/assets/images/spinner_14.gif"/>&nbsp;Calculating...</span>'; // show loading spinner
	sendRequest(strAjaxDoPath + '.php?anonMode=1&tabId=' + tabId + '&action=getDataScopeFilterText', sendControlDataNQPSText_Callback);
	// update data scope filter organisation text
	$('#infoScopeOrganisations').html('&nbsp;<img src="/core/assets/images/spinner_14.gif"/>'); // show loading spinner
	$.get(strAjaxDoPath + '.php?anonMode=1&tabId=' + tabId + '&action=getDataScopeFilterReportedText', '', function(strReturn) {
		$('#infoScopeOrganisations').html(strReturn);
	});
}// function updateDataFilterText

function updateOrgFilterText(tabId) {
	// load text next to organisation filter
	getObj('infoOrgs'); // organisation filter info text span
	obj.innerHTML='&nbsp;<span style="color: #000000;"><img src="/core/assets/images/spinner_14.gif"/>&nbsp;Calculating...</span>'; // show loading spinner
	//getObj('infoOrgsDemographic'); // organisation filter demographic info text span
	//obj.innerHTML='<br />'; // show loading spinner
	sendRequest(strAjaxDoPath + '.php?anonMode=1&tabId=' + tabId + '&action=getOrgListFilterText', sendControlDataOrgListText_Callback);
	sendRequest(strAjaxDoPath + '.php?anonMode=1&tabId=' + tabId + '&action=getOrgListDemographicText', sendControlDataOrgListTextDem_Callback);
	$('#infoScopeOrganisations').html('&nbsp;<img src="/core/assets/images/spinner_14.gif"/>'); // show loading spinner
	$.get(strAjaxDoPath + '.php?anonMode=1&tabId=' + tabId + '&action=getDataScopeFilterReportedText', '', function(strReturn) {
		$('#infoScopeOrganisations').html(strReturn);
	});

	// update organisation highlight menu if rendered
	// DB: moved to ajaxDo.inc
} // updateOrgFilterText

function toggleOrgList() {
	/**
	 * Toggle visibility of Organisation List
	 */
	toggle('orgList', '/dios/images/menu/expand');
	getObj('orgList');
	if ($('#orgList').is(':visible')) {// org list visible, update it via ajax call
		showLoadingMessage(obj); // show loading message
		updateSessionOrgFilter_inline();
	} else { // org list not visible, clear contents
		showLoadingMessage(obj);// show loading message
	}
}

function hideLoadingMessage() {
	getObj('loading-image');
	obj.style.display = 'none'; // hide loading message

	/*// un-hide content and hide hiddenContent message
	getObj('viewContent');
	if (obj!==undefined) { // object found
		obj.style.display = 'block';
	}*/

	// show hidden content message
	getObj('hiddenContent');
	if (obj!==undefined) { // object found
		obj.style.display = 'none';
	}
}

function showLoadingMessage(objN) {
	/**
	 * obj - optional object, to set its innerhtml to a loading message
	 */

	if (objN===undefined) { // no object specified
		getObj('loading-image');
		obj.style.display = 'block';
	} else { // object specified, set its innerhtml property
		objN.innerHTML = '<span class="loading-msg">Loading...</span>&nbsp;<img src="/core/assets/images/spinner_20.gif"/>';
	}
}

function sendControlDataVisualList(strControlData, tabId) {
	/**
	 * Send status of form controls to server to update SESSION vars
	 */

	// hide view content
	getObj('viewContent');
	if (obj!==undefined) { // object found
		obj.style.display = 'none';
	}

	// show hidden content message
	getObj('hiddenContent');
	if (obj!==undefined) { // object found
		obj.style.display = 'block';
	}

	sendRequest(strAjaxDoPath + '.php?anonMode=1&action=setVisualListFilter&tabId='+tabId+'&update=1', sendControlDataVisualList_Callback, strControlData);
}

function sendControlDataVisualList_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */

	s = req.responseText;

	if (s != 'success') { // error
		if (s == 'error: not logged in') { // not logged in - open a login box in another window
			var winLogin = window.open('/dios/?pageDst=home', 'loginWindow');
		} else { // some other error - alert the user
			alert('There was a problem updating the Visualization Filter. The error returned was: ' + s);
		}
	} else { // success - finished updating SESSION vars, now update report list via ajax request
		// update text next to data scope filter
		updateVisualFilterText();
	}
}// function sendControlDataVisualList_Callback

function updateVisualFilterText(tabId) {
	// load text next to visual filter
	getObj('infoVisual'); // visual filter info text span

	obj.innerHTML='&nbsp;<span style="color: #000000;"><img src="/core/assets/images/spinner_14.gif"/>&nbsp;Calculating...</span>'; // show loading spinner
	sendRequest(strAjaxDoPath + '.php?anonMode=1&action=getVisualListFilterText&tabId='+tabId, sendControlDataVisualText_Callback);
}// function updateVisualFilterText

function sendControlDataVisualText_Callback(req) {
	/**
	 * Handle callback data from the AJAX call
	 */

	s = req.responseText;

	getObj('infoVisual');

	obj.innerHTML = s;
}// function sendControlDataVisualText_Callback

/**
 * Pipelining for datatables
 */

var oCache = {
	iCacheLower: -1
};

function fnSetKey( aoData, sKey, mValue )
{
	for ( var i=0, iLen=aoData.length ; i<iLen ; i++ )
	{
		if ( aoData[i].name == sKey )
		{
			aoData[i].value = mValue;
		}
	}
}

function fnGetKey( aoData, sKey )
{
	for ( var i=0, iLen=aoData.length ; i<iLen ; i++ )
	{
		if ( aoData[i].name == sKey )
		{
			return aoData[i].value;
		}
	}
	return null;
}

function fnDataTablesPipeline ( sSource, aoData, fnCallback ) {
	var iPipe = 5; /* Ajust the pipe size */

	var bNeedServer = false;
	var sEcho = fnGetKey(aoData, "sEcho");
	var iRequestStart = fnGetKey(aoData, "iDisplayStart");
	var iRequestLength = fnGetKey(aoData, "iDisplayLength");
	var iRequestEnd = iRequestStart + iRequestLength;
	oCache.iDisplayStart = iRequestStart;

	/* outside pipeline? */
	if ( oCache.iCacheLower < 0 || iRequestStart < oCache.iCacheLower || iRequestEnd > oCache.iCacheUpper )
	{
		bNeedServer = true;
	}

	/* sorting etc changed? */
	if ( oCache.lastRequest && !bNeedServer )
	{
		for( var i=0, iLen=aoData.length ; i<iLen ; i++ )
		{
			if ( aoData[i].name != "iDisplayStart" && aoData[i].name != "iDisplayLength" && aoData[i].name != "sEcho" )
			{
				if ( aoData[i].value != oCache.lastRequest[i].value )
				{
					bNeedServer = true;
					break;
				}
			}
		}
	}

	/* Store the request for checking next time around */
	oCache.lastRequest = aoData.slice();

	if ( bNeedServer )
	{
		if ( iRequestStart < oCache.iCacheLower )
		{
			iRequestStart = iRequestStart - (iRequestLength*(iPipe-1));
			if ( iRequestStart < 0 )
			{
				iRequestStart = 0;
			}
		}

		oCache.iCacheLower = iRequestStart;
		oCache.iCacheUpper = iRequestStart + (iRequestLength * iPipe);
		oCache.iDisplayLength = fnGetKey( aoData, "iDisplayLength" );
		fnSetKey( aoData, "iDisplayStart", iRequestStart );
		fnSetKey( aoData, "iDisplayLength", iRequestLength*iPipe );

		$.post( sSource, aoData, function (json) {
			/* Callback processing */
			oCache.lastJson = jQuery.extend(true, {}, json);

			if ( oCache.iCacheLower != oCache.iDisplayStart )
			{
				json.aaData.splice( 0, oCache.iDisplayStart-oCache.iCacheLower );
			}
			json.aaData.splice( oCache.iDisplayLength, json.aaData.length );

			fnCallback(json)
		},"json" );
	}
	else
	{
		json = jQuery.extend(true, {}, oCache.lastJson);
		json.sEcho = sEcho; /* Update the echo for each response */
		json.aaData.splice( 0, iRequestStart-oCache.iCacheLower );
		json.aaData.splice( iRequestLength, json.aaData.length );
		fnCallback(json);
		return;
	}
}

