// nsb_ajax.js
// (c) 2008 - noisybear
//

function Ajax() {
	this.req = null;
	this.url = null;
	this.status = null;
	this.statusText = '';
	this.method = 'GET';
	this.async = true;
	this.dataPayload = null;
	this.readyState = null;
	this.responseText = null;
	this.responseXML = null;
	this.handleResp = null;
	this.responseFormat = 'text', // 'text', 'xml', 'object'
	this.mimeType = null;
	this.headers = [];
	
	this.init = function() {
		var i = 0;
		var reqTry = [ 
		  function() { return new XMLHttpRequest(); },
		  function() { return new ActiveXObject('Msxml2.XMLHTTP') },
		  function() { return new ActiveXObject('Microsoft.XMLHTTP' )} ];
		  
		while (!this.req && (i < reqTry.length)) {
		  try { 
			this.req = reqTry[i++]();
		  } 
		  catch(e) {}
		}
		return true;
	};
	
	this.getContent = function(url) {
		var req = null;
		if (!this.init()) {
		  alert('Could not create XMLHttpRequest object.');
		  return;
		}
		req = this.req;
		req.open('GET', url, false);
		req.send(null);
		return req.responseText;
	},
	
	this.uploadImage = function(url,attributes) {
		if (!this.init()) {
		  alert('Could not create XMLHttpRequest object.');
		  return;
		}
		this.req.open('GET', url, false);
		this.req.send(null);
		this.req.onreadystatechange = function() {
			alert(this.req.readyState);
			 if (this.req.readyState == 4) {
				 return attributes;
			 } else {
				alert('Could not create XMLHttpRequest object.');
		  		return;
			 }
		}
	},
	
	this.doGet = function(url, hand, format) {
		this.url = url;
		this.handleResp = hand;
		this.responseFormat = format || 'text';
		this.doReq();
	};
	
	this.doPost = function(url, dataPayload, hand, format) {
		this.url = url;
		this.dataPayload = dataPayload;
		this.handleResp = hand;
		this.responseFormat = format || 'text';
		this.method = 'POST';
		this.doReq();
	};
	
	this.doReq = function() {
		var self = null;
		var req = null;
		var headArr = [];
		
		if (!this.init()) {
		  alert('Could not create XMLHttpRequest object.');
		  return;
		}
		req = this.req;
		req.open(this.method, this.url, this.async);
		if (this.method == "POST") {
			this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		}
		self = this;
		req.onreadystatechange = function() {
		  var resp = null;
		  self.readyState = req.readyState;
		  if (req.readyState == 4) {
			
			self.status = req.status;
			self.statusText = req.statusText;
			self.responseText = req.responseText;
			self.responseXML = req.responseXML;
			
			switch(self.responseFormat) {
			  case 'text':
				resp = self.responseText;
				break;
			  case 'xml':
				resp = self.responseXML;
				break;
			  case 'object':
				resp = req;
				break;
			}
			
			if (self.status > 199 && self.status < 300) {
			  if (!self.handleResp) {
				alert('No response handler defined ' +
				  'for this XMLHttpRequest object.');
				return;
			  }
			  else {
				self.handleResp(resp);
			  }
			}
			
			else {
			  self.handleErr(resp);
			}
		  }
		}
		req.send(this.dataPayload);
	};
	
	
}

function toQuery(docForm) {
	
	var submitContent = '';
    var formElem;
    var lastElemName = '';
	
	for (i = 0; i < docForm.elements.length; i++) {
        
        formElem = docForm.elements[i];
        switch (formElem.type) {
            // Text fields, hidden form elements
            case 'text':
            case 'hidden':
            case 'password':
            case 'textarea':
            case 'select-one':
                submitContent += formElem.name + '=' + escape(formElem.value) + '&'
                break;
                
            // Radio buttons
            case 'radio':
                if (formElem.checked) {
                    submitContent += formElem.name + '=' + escape(formElem.value) + '&'
                }
                break;
                
            // Checkboxes
            case 'checkbox':
                if (formElem.checked) {
                    // Continuing multiple, same-name checkboxes
                    if (formElem.name == lastElemName) {
                        // Strip of end ampersand if there is one
                        if (submitContent.lastIndexOf('&') == submitContent.length-1) {
                            submitContent = submitContent.substr(0, submitContent.length - 1);
                        }
                        // Append value as comma-delimited string
                        submitContent += ',' + escape(formElem.value);
                    }
                    else {
                        submitContent += formElem.name + '=' + escape(formElem.value);
                    }
                    submitContent += '&';
                    lastElemName = formElem.name;
                }
                break;
                
        }
    }
    // Remove trailing separator
    submitContent = submitContent.substr(0, submitContent.length - 1);
    return submitContent;
}