

/*
RESTProvider. Class that encapsulates the AREST functionality
Args: base_uri, the BASE URI of the service provider
*/

function RESTProvider(base_uri){
	this.BaseUri = base_uri;
	this.message = "";
}



/*
*  Copied from: http://www.peej.co.uk/articles/rich-user-experience 
*  30/05/05
*
*  Iván Chavero <ichavero@uach.mx>
*
*  This function sould work on all major browsers.
*  it contains a conditional execution block that only IE will run that tries
*  to load the ActiveX version of XMLHttpRequest, before then trying to create a
*  XMLHttpRequest object the standard way.
*
*/

/*
This variable is needed because of the asychronous nature of the getREST functions.
var GlobalHTTP;

*/
function getHTTPObject() {
	var xmlhttp;
	/*@cc_on 
	@if (@_jscript_version >= 5)
		 try {
			 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	 	}
	 catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (E) {
			xmlhttp = false;
		}
	}
	@else 
		xmlhttp = false;
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		}
		catch (e) {
			xmlhttp = false;
		}
	}
	return xmlhttp;
}

/*
* Iván Chavero <ichavero@uach.mx>
* This function gets a uri and returns it's content
* Params: path, the REST path that we handles the service
* 	  callback, the function we want to call after a succesfull get
*
*/

function Get(uri,callback){
		resource = this.BaseUri+uri;
		http = getHTTPObject();
		/* this.message = document.getElementById("this.message");
		SetMessage(this.message,"Getting...",'#ffffff','#0000cc'); */
		http.open("GET", resource, true);
		http.onreadystatechange = function() {
			if (http.readyState == 4) {
				window.status = "Get succesfull";
				//SetMessage(this.message,"Get Successfull",'#ffffff','#0000cc');
				callback(http);
			//	setTimeout('ClearMessage(this.message)',2000);
				
  			}
			else{
				window.status = "Loading";
				//SetMessage(this.message,"Loading",'#ffffff','#00cc00');
			//	setTimeout('ClearMessage(this.message)',2000);
			}
 		}
		http.send(null);

}


/*
* Iván Chavero <ichavero@uach.mx>
* This function posts data to a service
* Params: path, the path that  handles the service
*	  content, the content we want to send to the service	  
* 	  callback, the function we want to call after a succesfull post
*	  
*
*/
function Post(uri,content,callback){
		http = getHTTPObject();
		http.open("POST", this.BaseUri+uri, true);
		http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		//this.message = document.getElementById("this.message");
		//SetMessage(this.message,"Posting...",'#ffffff','#0000cc');
		text = http.send(content);
		http.onreadystatechange = function() {
			if (http.readyState == 4) {
				window.status = "Post succesfull";
				SetMessage(this.message,"Post Successfull",'#ffffff','#0000cc');
				callback(http);
				setTimeout('ClearMessage(this.message)',2000);
  			}
			else {
				window.status = "Loading";
				SetMessage(this.message,"Loading",'#ffffff','#00cc00');
				setTimeout('ClearMessage(this.message)',2000);
			}
 		}
		return text; 
}


function SetMessage(messages,text,fgcolor,bgcolor){
		messages.style.width = text.length+'em';
		messages.style.backgroundColor = bgcolor;
		messages.style.color = fgcolor;
		messages.style.fontWeight = 'bolder';
		messages.innerHTML = text;
}

function ClearMessage(messages) {
	messages.innerHTML = "";

}

RESTProvider.prototype.Get = Get;
RESTProvider.prototype.Post = Post;
RESTProvider.prototype.SetMessage = SetMessage;
RESTProvider.prototype.ClearMessage = ClearMessage;
RESTProvider.prototype.getHTTPObject = getHTTPObject;
/*
*
* Iván Chavero <ichavero@uach.mx>
* Based on the example of: http://www.quirksmode.org/js/findpos.html
*
* This function returns the position of an object in the X axis
*
* Params: obj, the object of which we want the X coordinate
*
* 31/05/05
*/

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}


/*
*
* Iván Chavero <ichavero@uach.mx>
* Based on the example of: http://www.quirksmode.org/js/findpos.html
*
* This function returns the position of an object in the Y axis
*
* Params: obj, the object of which we want the Y coordinate
*
* 31/05/05
*/

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

/*
*
* Iván Chavero <ichavero@uach.mx>
* Based on the example of: http://www.quirksmode.org/js/findpos.html
*
* This function sets the position of a layer over another layer (overlaps the layers).
*
* Params: obj1, the object of which we want get the coordinates
*         obj2, the object of which we want set the coordinates
*
* 31/05/05
*/

function overlap(obj1,obj2)
{
	var newX = findPosX(obj1);
	var newY = findPosY(obj1);
	obj2.style.top = newY + 'px';
	obj2.style.left = newX + 'px';
}

var comboReq;

function fillCombo(combo, url) 
{
	comboReq = new getHTTPObject();
	comboReq.onreadystatechange = function() {
			fillComboChange(combo);
		}
	comboReq.open("GET", url, true);
	comboReq.send(null);
}

function fillComboChange(combo) {
	var key, value;
	if (comboReq.readyState == 4) {
		if (comboReq.status == 200) {
			// Empty combo
			for (i=combo.options.length-1; i>=0; i--) {
				combo.options[i] = null;
			}
			// Fill combo
			comboXML = comboReq.responseXML;
			items = comboXML.getElementsByTagName('item');
			for (var i = 0; i < items.length; i++) {
				key = items[i].attributes.getNamedItem('key').value;
				value = items[i].attributes.getNamedItem('value').value;
				combo.options[i] = new Option(value,key);
			}
			// Call to its onchange
			combo.onchange();
			
		} else {
			alert("There was a problem retrieving the XML data:\n" + comboReq.statusText);
		}
	}
}


// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresarch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// ====================================================================
function URLEncode(content)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = content;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			  /*  alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
			*/
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return(encoded);
};


function URLDecode(encoded_string)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = encoded_string;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				//alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};
