// 2008.01.28 KJD: Ported for ooma

// 2007.01.30 KJD: Updated Ajax Request object
// 2008.02.13 KJD: Added Post vars

// This is buggy, but at least it's close
function ShowXMLArray( xmlarray, mystring, mylocation )
{
	if( typeof mystring 	== 'undefined' )	{		var mystring 	= "";	}
	if( typeof mylocation 	== 'undefined' )	{		var mylocation	= "";	}
	
	for( var i in xmlarray )
	{
		if( typeof xmlarray[i] == 'object' )
		{
			mystring += "\n[" + i + "]";
			mystring = ShowXMLArray( xmlarray[i], mystring );
		}
		else
		{
			mystring += "\n\t[" + i + "]=" + xmlarray[i];
		}
	}
	
	return mystring;
}

// 2008.02.13 KJD: If it is a post
function PostFile( thisfilename, postVars )
{
	var thisitem;

	thisitem = RequestFile( thisfilename, '', "POST", postVars );
	
	return thisitem;
}


function GetFile( thisfilename, thistype, thisobjecttype )
{
	// 2008.02.06 KJD: Added request type

	var thisitem;

	if( thistype == 'TEXT' )
	{
		thisitem = thistype;
		
		
		// Request file
		thisitem = RequestFile( thisfilename, thistype, "GET" );
		
		if( thisobjecttype == 'array' )
		{
			thisitem = thisitem.replace('\r','');
			thisitem = thisitem.split('\n');
		}
	}
	else if( thistype == 'XML' )
	{
		thisitem = RequestFile( thisfilename, thistype, "GET" );
		
		if( thisobjecttype == 'array' )
		{
			thisitem = XML2Array( thisitem );
		}
	}
	

	return thisitem;
}

function XML2Array( thisobject, thisarray )
{
	if( typeof thisarray == 'undefined' )	{		var thisarray = new Array();	}

	for( var i = 0; i< thisobject.childNodes.length; i++ )
	{

		if( thisobject.childNodes[i].childNodes.length - 1 )
		{
			thisarray[ thisobject.childNodes[i].nodeName ] = new Array();
			thisarray[ thisobject.nodeName ] = XML2Array( thisobject.childNodes[i], thisarray[ thisobject.childNodes[i].nodeName ] );
		}
		else
		{
			thisarray[ thisobject.childNodes[i].nodeName ] = thisobject.childNodes[i].childNodes[0].nodeValue;
		}
	}

	return thisarray;
}


function RequestFile( thisfilename, thistype, requestType, postVars )
{
	var http_request 	= false;
	var urlmethod 		= "GET";
	
	// 2008.02.06 KJD: Added request type switch
	if( requestType == 'POST' )	{	urlmethod = 'POST';	}
	
	var thisinfo;
	
	// 2006.09.14 KJD: Determine the Browser we're using
	if( window.XMLHttpRequest )
	{
		// 2006.09.14 KJD: NON-IE Browsers
		http_request = new XMLHttpRequest();

		if ( http_request.overrideMimeType )
		{
			if( thistype == 'TEXT' )
			{
				http_request.overrideMimeType('text/html');
			}
			else if( thistype == 'XML' )
			{
				http_request.overrideMimeType('text/xml');
			}
		}
	}
	else if( window.ActiveXObject )
	{
		// 2006.09.14 KJD: Internet Explorer
		try
		{
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	// 2006.09.14 KJD: Open the URL ( true = continue even if object hasn't been receive, false = wait until we get a response )
	http_request.open( urlmethod, thisfilename, false );
	
	
	// 2006.09.14 KJD: If it's a GET request send a null response
	if( urlmethod == 'GET' )
	{
		http_request.send( null );
	}
	else
	{
		var contentCount	= 0;
		var thisParams		= "";
		for( var i in postVars )
		{
			if( contentCount )	{		thisParams += "&";	}
			
			thisParams += i + "=" + escape( postVars[ i ] );
			
			contentCount++;
		}
	
		// 2008.02.13 KJD: Send post parameters.
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http_request.setRequestHeader("Content-length", contentCount );
		http_request.setRequestHeader("Connection", "close");
		
		http_request.send( thisParams );
		/*
		for( var i in postVars )
		{
			alert( i + "=" + postVars[ i ] );
			http_request.send( i + "=" + postVars[ i ] );
			alert( i + "=" + postVars[ i ] );
		}
		*/
	
		thistype = 'TEXT';
	}
	
	// readyState is 4 at this point
	thisinfo = CheckStatus( http_request, thistype );
	
	return thisinfo;
}

function CheckStatus( http_request, thistype )
{
	var thisinfo;
	if( http_request.readyState == 0 )
	{
		// Not initialized
	}
	else if( ( http_request.readyState == 1 ) || ( http_request.readyState == 2 ) )
	{
		// Loading
	}
	else if( http_request.readyState == 3 )
	{
		// Interactive
	}
	else if( http_request.readyState == 4 )
	{
		// 2006.09.14 KJD: Page is ready, check the status

		// 2006.09.14 KJD: These are the status codes ( 404,500, 200, etc ) 0==local
		if( ( http_request.status == 200 ) || ( http_request.status == 0 ) )
		{
			// 2006.09.14 KJD: Page is good
			if( thistype == 'TEXT' )
			{
				thisinfo = http_request.responseText;
			}
			else if( thistype == 'XML' )
			{
				thisinfo = http_request.responseXML;
			}
		}
		else if( http_request.status == 404 )
		{
			// 2006.09.14 KJD: Page not found
		}
		else if( http_request.status == 500 )
		{
			// 2006.09.14 KJD: Server error
		}
	}
	else
	{
		// Anything else?
	}

	return thisinfo;
}

// 2008.02.06 KJD: Parse the Ajax response, taken from older validation code
function ParseResponse( responseXML )
{
	// 2008.02.06 KJD: Return an array instead
	var resultArray = new Array();

	var error	= "";
	var output	= "";
	
	if( responseXML && getElementText( responseXML.getElementsByTagName( 'output')[0] ) )
	{
		error	= getElementText( responseXML.getElementsByTagName( 'error' )[0] );
		output	= getElementText( responseXML.getElementsByTagName( 'output')[0] );

		output	= JSON.parse( output );
		error	= JSON.parse( error );
	}
	else
	{
		error	= 30500;
	}
	
	resultArray[ 'error' ]	= error;
	resultArray[ 'output' ] = output;
	
	return resultArray;
}


// 2008.02.06 KJD: Remove White space from XML
function RemoveWhiteSpace( thisString )
{
	try
	{
		// 2008.02.06 KJD: Convert object into string
		thisString += " ";
		thisString = thisString.replace( /^\s+|\s+$/gi, '' );
	}
	catch(e){}
	return thisString;
}

// 2008.02.06 KJD: Get the corrected text (if CDATA elements)
function getElementText( node )
{
    if( node == null )
	{
        return("");
    }
    
    child 			= node.firstChild;
    foundCDATA		= false;
    foundPlainText	= false;
    
    while (child != null)
	{    
        if (child.nodeType == 4)
		{            // CDATA node
            result = child.nodeValue;
            foundCDATA = true;
        }
        else
		{
            if (child.nodeType == 3)
			{        // Text node
                result = child.nodeValue;
                foundPlainText = true;
            }
        }
        if (foundCDATA == true)
		{
			// 2008.02.06 KJD: Also remove white space
			result = RemoveWhiteSpace( result );
			return result;
        }    
        child = child.nextSibling    
    }
    if (foundPlainText == false)
	{
        return("")
    }
	
    return result;
}
