
/*
This requires an additional (custom) parameter to be added to the AWS/PAA request:

	EndpointUri = (AWS endpoint)/onca/xml

where (AWS endpoint) should be replaced with whatever the intended destination of the request is.
You can change the name of the parameter used for this below in strDestinationParm; if you do,
make sure your requests are adjusted as to match.
*/

var strDestinationParm = "EndpointUri";


/**********************************************************************************/

/* parameter names to find certain values */
var strAWSAccessKeyIdParm = "AWSAccessKeyId";


// error meesages
var MSGNoParams      = 'No request present.';
var MSGNoEndpointUri = 'Need EndpointUri parameter to provide (endpoint)(uri).';
var MSGNoAWSId       = 'Need AWSAccessKeyId parameter to look up key.';

// store errors here
var errs = [];

// parse Request & return some useful results
function getRequestSignature( request, strAWSSecretAccessKey ) {

	// results in
	var bOk = 0;
	var strSignedQuery = "";  // full request url, for GETs
	var strMethod = "";       // http method used in signature (GET or POST)
	var strDestination = "";  // endpoint + uri
	var oSign = { Timestamp: "", Signature: "", parameters: [] }

	// get info from form or query
	var strAWSAccessKeyId = "";
	var colParams = null;

	strMethod = "GET";
	var a = request.split('&')
	var colParams = new Object;
		
	for (var i=0;i<a.length;i++) {
		var b = a[i].split('=');
		colParams[b[0]] = b[1];
	}
	
	if ( colParams ) {
		// check for destination & AWSId
		if ( (strDestination = colParams[ strDestinationParm ] + "") == "undefined"  || strDestination == "" )
			errs.push( MSGNoEndpointUri )

		if ( (strAWSAccessKeyId = colParams[ strAWSAccessKeyIdParm ] + "") == "undefined" || strAWSAccessKeyId == "" )
			errs.push( MSGNoAWSId );
	} else {
		errs.push( MSGNoParams );
	}

	strAWSAccessKeyId = colParams[ strAWSAccessKeyIdParm ];
	
	// sign query
	if ( errs.length == 0 ) {

		oSign = AWSQS.getSignatureFromArray( strMethod, strDestination, colParams, strAWSSecretAccessKey );
		var aParams = oSign.parameters;
		aParams.push( "Signature=" + oSign.Signature );
		
		strSignedQuery = "http://" + strDestination + "?" + aParams.join("&");

		bOk = 1
	}
	return new fnResult( bOk, strSignedQuery, strMethod, strDestination, oSign.Timestamp, oSign.Signature );
}

function fnResult( bOk, strSignedQuery, strMethod, strDestination, strTimestamp, strSignature ) {
	this.ok = bOk;
	this.signedquery = strSignedQuery;
	this.method = strMethod;
	this.destination = strDestination;
	this.Timestamp = strTimestamp;
	this.Signature = strSignature;
}

function fnDisplayErrors( response ) {
	for ( var i = 0; i < errs.length; i++  )
		response.Write( "<li>" + errs[i] + "</li>" );
}

function fnCheckErrItem( i, msg ){ 
	return errs[i] == msg ? 1 : 0; 
}
