/*

name			Dynamic content
author			Mark de Jong
copyright		Senna Multimedia
updated			2007-2010


ContentLoader is originally from the book 'Ajax in Action' by Dave Crane, Eric Pascarello and Darren James
and is modified by Mark de Jong (Spellcoder)
*/

/* namespacing object */
var net=new Object();

net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;

function requestdoc(settings)
{
	//console.log(settings);
	var loader = new net.ContentLoader(
									 settings.url
									,settings.callback
									,settings.callbackError
									,settings.method
									,settings.params
									,settings.usefilecache
								);
	return loader;
}

// content loader object for cross-browser requests
net.ContentLoader=function ContentLoader(url,onload,onerror,method,params,contentType,usefilecache)
{
	this.urly		= url;		// Spellcoder
	this.req			= null;
	this.onload		= onload;
//	this.onerror	= (onerror) ? onerror : this.defaultError;

	this.onerror	= (onerror) ? onerror : this.defaultError;

	this.loadXMLDoc(url,method,params,contentType,usefilecache);
	this.parameter	= null;
}

net.ContentLoader.prototype.abort = function ContentLoader_abort()
{
	this.onload = null;
	this.onerror = null;
	this.req.abort();
	console.warn("xmlhttprequest aborted");
}

net.ContentLoader.prototype.loadXMLDoc=function ContentLoader_loadXMLDoc(url,method,params,contentType,usefilecache)
{
	if (!method)
		method="GET";

	// use filecache if possible and if findInFilecache actually exists
	if (method=='GET' && usefilecache && findInFilecache)
	{
		this.req = {};
		this.req.responseText = findInFilecache(url);
		if (this.req.responseText != undefined) {
			this.onload();
			return;	
		}
//		else
//			this.onerror();
//		return;
	}

	var pData = '';

	if (method=="POSTJSON")
	{
		pData = JSON.stringify(params, null,"\t");
		method = 'POST';
		contentType = 'application/json';
	}
	else
	{
		var pData = getURLQueryString(params);

		if (method!='POST')
		{
			if (pData != "")
				url = url + "?" + pData;
			pData = null;
		}
	}

	this.loadXMLDoc2(url, method, pData, contentType);
}

// serialize parameters to an URL query string
//	also see http://xkr.us/articles/javascript/encode-compare/
function getURLQueryString(params)
{
	var paramstring="";
	var iCount = 0;
	for (var pItem in params)
	{
		if (iCount>0)
			paramstring = paramstring + '&';

		paramstring = paramstring + pItem + '=' + encodeURIComponent(params[pItem]);
		iCount++;
	}
	return paramstring;
}



net.ContentLoader.prototype.gethttprequestobject = function ContentLoader_gethttprequestobject()
{
	/*
	20 mei 2010 - deze code gedisabled, is alleen nog voor IE < 7
    (Maar Google Maps V3 en onze app support IE6 niet meer)
	
	var req;

	if(window.XMLHttpRequest && !useragent.isIE) {
		req = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		try
		{
			req = new ActiveXObject('Microsoft.XMLHTTP');
			//req = new ActiveXObject('Microsoft.XMLDOM');	<-- doesn't work on my IE6 test image
		}
		catch(e)
		{
			try {
				req = new ActiveXObject("Msxml2.XMLHttp");
			}
			catch(e2) { }
		}
	}
	*/

	var req = new XMLHttpRequest();
	
	if (typeof req == 'undefined')
	{
		console.error('Cannot create an XMLHttpRequest object.');
		return;
	}
	
	return req;
}

net.ContentLoader.prototype.loadXMLDoc2=function ContentLoader_loadXMLDoc2(url,method,pData,contentType)
{
    method = method.toUpperCase();
	var loader=this;
	this.urly = url;
	
	if (!contentType && method=="POST")
		contentType='application/x-www-form-urlencoded';

	if (!contentType)
		contentType = 'text/xml';
  
    this.req = this.gethttprequestobject();
	if (!this.req)
		return;
  
	this.req.onreadystatechange=function ContentLoader_internal_onReadyState()
	{
		net.ContentLoader.onReadyState.call(loader);
	}

	try
	{
		//console.log('Doing a '+method+' request for URL: '+url+"\n"+'with data '+pData);
	
		this.req.open(method,url,true);

		if (contentType)
			this.req.setRequestHeader('Content-Type', contentType);

		// FIXME: a test to force the browser not to cache the file
		//		this.req.setRequestHeader('If-Modified-Since', 'Wed, 15 Nov 1995 00:00:00 GMT');
		this.req.send(pData);
	}
	catch (err){
		console.error('Got an error on requesting '+url+'.');
		this.onerror.call(this);
	}
}

net.ContentLoader.onReadyState=function ContentLoader_onReadyState()
{
	var req=this.req;
	var ready=req.readyState;

	/*
	Spellcoder notes:
	- Safari won't give back an status when the application runs from the file:// protocol
	For Safari I added a check for NULL. If there's no status, it'll just assume there's no error.
	(this was tested in Safari 2 ?)
	*/

	if (ready==net.READY_STATE_COMPLETE)
	{
		var httpStatus=req.status;
		if (httpStatus==null || httpStatus==200 || httpStatus==0)
		{
			//alert('file '+this.req.urly+" is ingeladen.\nContents:\n"+this.req.responseText);
			//			alert('contentloader '+req.responseText)
			this.onload.call(this);
		}
		else
		{
			this.onerror.call(this);
		}
	}
}

net.ContentLoader.prototype.defaultError=function()
{
	var unk = '(undefined)';

	console.error
		( "Data request failed"
		+ "\nURL:"+this.urly
		+ "\n\nreadyState:"+readval(this.req.readyState,unk)
		+ "\nstatus: "+readval(this.req.status,unk)
		+ "\nheaders: "+readval(this.req.getAllResponseHeaders(),unk)
		+ "\nresponseText:"+readval(this.responseText,'undefined')
		);
}

function readval(val,defval) {
	return typeof val=='undefined' ? defval : val;
}

net.formsubmitter=function(formnode, onloadhandler)
{
//	this.urly		= url;		// Spellcoder
	this.req			= null;
	this.onload		= onloadhandler;
	this.onerror	= this.defaultError; //(onerror) ? onerror : this.defaultError;

	this.loadXMLDoc2(
		  product.url.api //formnode.getAttribute('action')
		, formnode.getAttribute('method')
		, formData2QueryString(formnode)
		, ''
		);
}

net.formsubmitter.prototype = net.ContentLoader.prototype;


/** @short parse JSON
*/
function parseResponse(responsetext)
{
	if (typeof JSON == 'object')
	{
		try
		{
			// use native JSON parser or available JSON parse functions
			return JSON.parse(responsetext);
		}
		catch(e)
		{
			//alert(responsetext);
			console.error('Failed to parse JSON');
			console.log(responsetext);
			return;
		}
	}
/*
	else
	{
		// fallback to eval (less save!)
		eval('test='+responsetext);
		return test;
	}
*/
}


/*
author:  Mark de Jong
version: 10 december 2009
*/
function handleSubmit(form, validatefunction, responsehandler)
{
//	try
//	{
		if (validatefunction != '')
		{
			// prevent an error in the submithandler to not cancel the submit
			setTimeout( function()
						{
							// validation
							if (typeof window[validatefunction] == 'undefined')
							{
								console.error('Unknown function '+validatefunction);
								return;
							}

							console.log('Calling validation function');
							var sendform = window[validatefunction](form);
							
							if (sendform)
							{
								console.log('Sending form data');
								var loader = new net.formsubmitter(form, responsehandler/*product.genericresponsehandler*/);
							}
						}, 1);
		}
//	}
//	catch(err)
//	{
//		console.error(err);
//	}

	return false;
}


function onXMLHttpLoad( objXMLHttp) {
   var xml = objXMLHttp.responseXML;  // First try to use the auto-parsed value
   if( !xml || !xml.documentElement ) { // The browser failed, but we think we're smarter
//  if( !objXMLHttp.responseXML || !objXMLHttp.documentElement ) { // The browser failed, but we think we're smarter

//alert('Parsing to XML');

		if( window.ActiveXObject ) {
			// Internet Explorer, use the Msxml COM object
			xml = new ActiveXObject( "Msxml2.DOMDocument" );
			xml.loadXML( objXMLHttp.responseText );
		} else if ( DOMParser ) {
			// Use the gecko builtin if it's available.
			xml = new DomParser().parseFromString(objXMLHttp.responseText, "text/xml" );
	    }

	}
	return xml;
}



/*
 * Copyright 2005 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Original code by Matthew Eernisse (mde@fleegix.org)
 * Additional bugfixes by Mark Pruett (mark.pruett@comcast.net)
 *
*/

// The var docForm should be a reference to a <form>

function formData2QueryString(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;
}



function dovizservercall(settings)
{
	settings.params["class"] = settings["class"];
	settings.params["method"] = settings.method;

	requestdoc({ url:				product.url.api
				, method:			settings.params.postmethod ? settings.params.postmethod : 'GET'
				, params:           settings.params
				, callback:			function()
					{
						console.log('Loaded list of question collections.');

						var returnvalue = parseResponse(this.req.responseText);
						
						if (returnvalue == null)
						{
							console.error("Invalid JSON recieved for call to "+settings["class"]+":"+settings["method"]);
							return;
						}
						
						settings.callback(returnvalue);
					}
				, callbackError:	function()
					{
						console.error("Failed to retrieve data for call to "+settings["class"]+":"+settings["method"]);
					}
			});
}
