/**
 *  Add this code if you need page without form to reload
 *  window.location.reload(true) will be called.
 * 	<gds:script>		
 *		setClientNearbyModeListener(null);
 *	</gds:script>
 * 
 *  Add this code if you need to refresh page with form. 
 * 	<gds:script>		
 *		setClientNearbyModeListener($('<form_name>'));
 *	</gds:script>
 * 
 *  where <form_name> - name of form to refresh
 *  
 */

//
//Can be only one listener. We need only one refresh.
//
var needRefresh = false;
var clientNearbyModeListener = null;
var forwardToController = null;
var switchModeURL = null;
var clientNearbyImg = null;
var clientAwayImg = null;
var isClientNearby = false;

Ajax.Responders.register({
	onComplete: function(responder, request, transport, json){
		var params = extractAJAXObject(request);
		if(params && params['switchClientNearbyMode']){
			if(needRefresh) {
				window.location.reload(true);
			} else {
				isClientNearby = !isClientNearby;
				if(isClientNearby) {
					clientAwayImg.hide();
					clientNearbyImg.show();
				} else {
					clientAwayImg.show();
					clientNearbyImg.hide();
				}
			}
		}
	}			
});

function initSwitchModeLink(currentController, url, nearbyImg, awayImg, _isClientNearby){
	forwardToController	= currentController;
	switchModeURL = url;
	clientNearbyImg = nearbyImg;
	clientAwayImg = awayImg;
	isClientNearby = _isClientNearby;
}

function setClientNearbyModeListener(listener, refresh){
	if(listener == null){
		if ( refresh ){
			needRefresh = true;
		}
		
		return;
	}
	
	if(clientNearbyModeListener == null){
		needRefresh = true;
		clientNearbyModeListener = listener;
	}
}

function removeClientNearbyModeListener(){
	needRefresh = false;
	clientNearbyModeListener = null;	
}

function switchClientNearbyMode(){
	if(clientNearbyModeListener != null && isForm(clientNearbyModeListener)){

		var hiddenElem = document.createElement("input");
		hiddenElem.type = "hidden";
		hiddenElem.name = "_forwardTo";
		hiddenElem.value = forwardToController;
		clientNearbyModeListener.appendChild(hiddenElem);
		
		clientNearbyModeListener.action = switchModeURL;		
		clientNearbyModeListener.submit();
	} else {
		ajaxInvoke(switchModeURL, { method: 'get', parameters: 'action=switchModeAjax'});			
	}
}
		
function isForm(obj){
	return true;
}
