// File:		$Id: anymeta_rest.js 18822 2006-02-01 17:26:20Z bas $
// 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:	validate_def
// Parameters:	form_name	form to check
//				msg			if no msg is used the default one is
// Returns:		true if from is valid
// Description:	Validate the form
//				Depending on alt attributes in form elements
//				If alt attribute and alt text is required then check that field
//
function anymeta_rest_validate ( form, alrt, opt )
{
	if (form)
	{
		var f = document.getElementById(form);
		if (!f)
		{
			f = document.forms[form];
		}
	}
	else
	{
		alert('Function needs a form as a parameter')
		return false;
	}

	if (alrt == null)
	{
		alrt = 'All fields with * are required';
	}

	var isValid		= true;
	var	vFormElems	= new Array();

	for (i=0;i<f.elements.length;i++)
	{
		elem  = f.elements[i];

	//	alert(f.id + " " + elem.name + " " + f.elements[elem.name].length);

		vCode = ( elem['alt'] ) ? elem['alt'] : elem.getAttribute('alt');

		if ( !( typeof vCode == 'undefined' || vCode == null || vCode == "" ) )
		{
			if (inArray(vFormElems, elem.name))
			{
				break;
			}
			else
			{
				v = anymeta_rest_getvalue(f.elements[elem.name]);
				if (vCode == 'required' && v.length < 1)
				{
					isValid = false;
				}
				vFormElems[i] = elem.name;
			}
		}
	}

	if (!isValid)
	{
		alert(alrt);
		return false;
	}
	else if (opt != null)
	{
		// TODO: simplefy this
		// was trying to do this more generuc but the time was short again
		// so gave some extra opt paramters for the nearby future ;)
		return anymeta_rest_onsubmit(opt[0], opt[1], opt[2], opt[3], opt[4], opt[5], opt[6], opt[7], opt[8]);
	}
	else
	{
		return true;
	}
}

// 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, cnfrm )
{
	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)
		{
			if (cnfrm)
			{
				if (confirm(cnfrm)) anymeta_rest(m, p, callback, opt);
			}
			else
			{
				anymeta_rest(m, p, callback, opt)
			}
		}
		else
		{
			if (cnfrm)
			{
				if (confirm(cnfrm)) anymeta_rest(m, p, anymeta_rest_onsubmit_cb, new Array(on_ok, on_fail));
			}
			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:	anymeta_rest_getvalue
// Parameters:	ffield
// Returns:		value of the formfield
//
function anymeta_rest_getvalue ( ffield, lngth )
{
	v="";
	t=ffield.type;
	if(!t)t=ffield[0].type;

	if(t=="checkbox")
	{
		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=="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;
	}
}

// 