// File:		$Id: anymeta_rest.js,v 1.8 2005/09/06 16:09:13 bas Exp $
// Author:		Marc Worrell
// Copyright:	(c) 2005 Mediamatic
// Description:	Support functions to user the Anymeta REST API
//				When the XMLHttpRequest is not available, then this
//				module will try a graceful fallback to using a 
//				image reply format from the REST API.

// 


// Function:	anymeta_rest_confirm
// Parameters:	form		the name or id of the form to submit
//				method		the method to set
// Returns:		-
// Description:	sets the method to eg. remove instead of add
//
function anymeta_rest_confirm ( form, text )
{
	if (typeof text != 'string')
	{
		text = 'Weet u dit zeker';
	}
	var f = document.getElementById(form);
	if (!f)
	{
		f = document.forms[form];
	}
	if (f)
	{
		if (confirm(text))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}

// Function:	anymeta_rest_setmethod
// Parameters:	form		the name or id of the form to submit
//				method		the method to set
// Returns:		-
// Description:	sets the method to eg. remove instead of add
//
function anymeta_rest_setmethod ( form, method )
{
	var f = document.getElementById(form);
	if (!f)
	{
		f = document.forms[form];
	}
	if (f && f.elements['method'])
	{
		f.elements['method'].value = method;
	}
}


// Function:	anymeta_rest_disconnect
// Parameters:	form		the name or id of the form to submit
//				method		the method to set
// Returns:		-
// Description:	remove 
//
function anymeta_rest_remove ( anchor, parms, on_action, on_ok, on_fail, callback, opt, text )
{
	if (typeof text != 'string')
	{
		text = 'Weet u dit zeker';
	}
	if (confirm(text))
	{
		anymeta_rest_onclick(anchor, parms, on_action, on_ok, on_fail, callback, opt);
	}
	return false;
}


// Function:	anymeta_rest_onclick
// Parameters:	anchor		the anchor tag clicked
//				parms		parameters for method
//				on_action	divs to show/hide when calling the service
//				on_ok		divs to show/hide upon success
//				on_fail		divs to show/hide upon failure
//				callback	optional callback function (instead of above two parms)
//				opt			optional parameter of the function
//				cnfrm		if confirm is needed
// Returns:		-
// Description:	performs a method call for an anchor handler.
//				pass the ref to the <a/> tag in anchor.
//				place the method in the 'rel' attribute of the anchor handler.
//
function anymeta_rest_onclick ( anchor, parms, on_action, on_ok, on_fail, callback, opt, cnfrm )
{
	if (anchor.rel)
	{
		var m = anchor.rel;

		anymeta_rest_showhide(on_action);

		if (callback)
		{
			if (cnfrm)
			{
				if (confirm(cnfrm)) anymeta_rest(m, parms, callback, opt);
			}
			else
			{
				anymeta_rest(m, parms, callback, opt);
			}
		}
		else
		{
			if (cnfrm)
			{
				if (confirm(cnfrm)) anymeta_rest(m, parms, anymeta_rest_onsubmit_cb, new Array(on_ok, on_fail));
			}
			else
			{
				anymeta_rest(m, parms, anymeta_rest_onsubmit_cb, new Array(on_ok, on_fail));
			}
		}
	}
	return false;
}


// Function:	anymeta_rest_onsubmit
// Parameters:	form		the name or id of the form to submit
//				on_action	divs to show/hide when calling the service
//				on_ok		divs to show/hide upon success
//				on_fail		divs to show/hide upon failure
//				callback	optional callback function (instead of above two parms)
// Returns:		-
// Description:	performs a submit to the method in the method input in
//				the form.  either a show/hide function is used to show/hide the
//				given divs, or a callback is done.
//				the show/hide list is a comma separated list of ids of divs.
//				use a + or a - in front of the div name to show or hide the
//				given div.
//				the callback function can be used instead of the on_ok/fail strings.
//				prototype of callback:  callback ( bool success, xml result, id of form )
//
function anymeta_rest_onsubmit ( form, on_action, on_ok, on_fail, callback, opt )
{
	var f = document.getElementById(form);
	if (!f)
	{
		f = document.forms[form];
	}
	if (f)
	{
		var m = f.elements['method'].value;
		var p = anymeta_rest_form2parms(f);

		anymeta_rest_showhide(on_action);

		if (callback)
		{
			anymeta_rest(m, p, callback, opt)
		}
		else
		{
			anymeta_rest(m, p, anymeta_rest_onsubmit_cb, new Array(on_ok, on_fail))
		}
	}
	return false;
}


// Function:	anymeta_rest_onsubmit_cb
// Parameters:	success		set to true on success
//				data		xml data returned by rest api
//				opt			array(on_ok, on_fail)
// Returns:		-
// Description:	callback for anymeta_rest_onsubmit.
//				hides or shows the divs for success or failure.
//
function anymeta_rest_onsubmit_cb ( success, data, opt )
{
	if (success)
	{
		s = opt[0];
	}
	else
	{
		s = opt[1];
	}
	anymeta_rest_showhide(s);
}


// Function:	anymeta_rest_showhide
// Parameters:	s		comma separated string with -/+ prefixed div ids
// Returns:		-
// Description:	accepts a comma separated string of div ids.  each id 
//				can be prefixed with a + or -.  Default is +.
//				a + prefix (or no prefix) show the given div
//				a - prefix hides the given div
//
function anymeta_rest_showhide(s)
{
	if (s != '' && s != null)
	{
		a = s.split(',');
		for (var i=0; i<a.length; i++)
		{
			s = a[i];
			c = s.charAt(0);
			v = 'block';
			if (c == '-')
			{
				v = 'none';
				s = s.substr(1,s.length-1);
			}
			else if (c == '+')
			{
				s = s.substr(1,s.length-1);
			}
			
			if (document.getElementById(s))
			{
				document.getElementById(s).style.display = v;
			}
			else
			{
				//alert('rest show/hide: no elt "' + s + '"');
			}
		}
	}
}

// Function: 	anymeta_rest_form2parms
// Parameters:	form		form to be processed
// Returns:		uri
// Description:	Transforms the given form to an uri
//
function anymeta_rest_form2parms ( form )
{
	var uri = '';
	var sep = '';
	
	for (var i=0; i<form.length; i++)
	{
		var value = anymeta_rest_getvalue(form.elements[i]);
		
		if (value.length > 0 && form.elements[i].name != 'method')
		{
			uri = uri + sep + escape(form.elements[i].name) + '=' + escape(value);
			sep = '&';
		}
	}
	return uri;
}


// Function:	getvalue
// Parameters:	ffield
// Returns:		value of the formfield
//
function anymeta_rest_getvalue ( ffield )
{
  v="";
  t=ffield.type;
  if(!t)t=ffield[0].type;
  else if(t=="checkbox" && ffield.checked) v=ffield.value;
  else if(t=="file") v=ffield.value;
  else if(t=="hidden") v=ffield.value;
  else if(t=="password") v=ffield.value;
  else if(t=="radio")
  {
  	if(ffield.length){for(gv_i=0;gv_i<ffield.length;gv_i++)if(ffield[gv_i].checked) v=ffield[gv_i].value;}  
    else{if(ffield.checked) v=ffield.value;}	
  } 
  else if(t=="select-multiple")  v=ffield.options[ffield.selectedIndex].value;
  else if(t=="select-one")  v=ffield.options[ffield.selectedIndex].value;
  else if(t=="text") v=ffield.value;
  else if(t=="textarea") v=ffield.value;
  return v;
}


// Function:	anymeta_rest
// Parameters:	method		method to call
//				parms		the parameters to append (use &amp; between parameters)
//				callback	function to call when ready
//				opt			optional parameter of the function
// Returns:		-
// Description:	call asynchronously the method.  upon finishing this function
//				will call the given callback function.
//				prototype of callback:   callback ( bool success, xml result, mixed opt )
//
function anymeta_rest ( method, parms, callback, opt )
{
	if (typeof parms == 'object')
	{
		var parms_tmp = '';
		var amp		  = ''
		for (var p in parms) {
			if (p=='RESTURL') continue;
			parms_tmp += amp+p+'='+parms[p];
			amp	= '&'
		}
		parms = parms_tmp;
	}

	var xmlhttp = false;
	
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	try 
	{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e) 
	{
		try 
		{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (E) 
		{
			xmlhttp = false;
		}
	}
	@end @*/
	
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') 
	{
		xmlhttp = new XMLHttpRequest();
	}

	if (xmlhttp)
	{
		// Use the xmlhttp request object
		xmlhttp.open("GET", "/services/rest/?method=" + method + '&' + parms, true);
		xmlhttp.onreadystatechange = 
					function() 
					{
						if (xmlhttp.readyState == 4 && xmlhttp.status >= 200 && xmlhttp.status < 300) 
						{
							rsp = xmlhttp.responseXML.getElementsByTagName("rsp");

//alert(method + " ++++++++++++ "+ callback);
							if (callback)
							{
								if (rsp)
								{
									result = rsp.item(0);
									stat   = result.getAttribute('stat');
								}
								else
								{
									stat   = 'error';
								}
								callback(stat == 'ok', result, opt);
							}

						}
					};
		xmlhttp.send(null);
	}
	else
	{
		// Use an image object to communicate with the REST server
		// NOTE: safari does not support the onerror of the image object.
		
		img = new Image();
		if (callback)
		{
			img.onload  = function () { callback(true,  false, opt); };
			img.onerror = function () { callback(false, false, opt); };
		}
		img.src	= "/services/rest/?method=" + method + '&format=img&random=' + Math.random() + '&' + parms;
	}
}

// 