/********************************************************************************************************************************
* Licensed Materials - Property of IBM                                                                                          *
*                                                                                                                               *
* IBM Cognos Products: AGS                                                                                                      *
*                                                                                                                               *
* (C) Copyright IBM Corp. 2005, 2014                                                                                            *
*                                                                                                                               *
* US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. *
*********************************************************************************************************************************/

var GET_PARAMETERS_RESPONSE_ROOT = "getParametersResponse";
var GET_PARAMETERS_MARKUP = "markup";
var GET_PARAMETERS_DISPLAY = "parametersDisplay";
var GET_PARAMETERS_DISPLAY_PARAMETER = "parameter";
var GET_PARAMETERS_NAME_ATTR = "name";
var GET_PARAMETERS_CAPTION_ATTR = "caption";
var GET_PARAMETERS_MULTIVALUED_ATTR = "multivalued";
var GET_PARAMETERS_REQUIRED_ATTR = "required";
var GET_PARAMETERS_TYPE_ATTR = "type";
var GET_PARAMETERS_FORMAT_ATTR = "format";
var GET_PARAMETERS_MODELVALUE_ATTR = "modelValue";
var GET_PARAMETERS_VALUE_ATTR = "value";

var current_gp_method;
var current_task_id;
var current_param_response_xts;
var doGetParametersRequestURL;

// utility function
//pass in the taskId so that we can cache credential params
//on a per task basis
function getGetParameterRequestString(obj, context, taskId)
{
    current_task_id = taskId;
	var sURL = "";
	var cl = "cl";
	var locales = getLocales(cl, "pl");	
		
	sURL += URIEncode(cl, locales[cl]);
	sURL += URIEncode("obj", obj);
	sURL += URIEncode("context", context);
	sURL += URIEncode("method", "getParameters");
	sURL += URIEncode("displayedPage", "report");
	sURL += URIEncode("parameterValues", getConnectionParameterValues(taskId));
	sURL += URIEncode("prompt", "false");
	// always have to ask for credential parameters too 
	sURL += URIEncode("credentialParameters", "true");
	
	var messageIFrame = getMessageIFrame();
	var messageIFrame_doc = getFrameDocument(messageIFrame);
	
	if(messageIFrame_doc){
	        var model = messageIFrame_doc.getElementById('model');
	        var modelValue = "";
					
	        if(model && model.value != ""){
				modelValue = model.value;
				sURL += URIEncode("model", modelValue);
	        } else {
				var routingServerGroup = messageIFrame_doc.getElementById('ui.routingServerGroup');
				var routingServerGroupValue = "";
				if(routingServerGroup && routingServerGroup.value != ""){
					routingServerGroupValue = routingServerGroup.value;
					sURL += URIEncode("routingServerGroup", routingServerGroupValue);
				}
			}
	}
	current_param_response_xts = URIEncode("buildResponseXTS","/ags/async/getParametersResponse.xts");

	// return the request
	//SEC_INFO sUrl - The request is not parsed as a string so should not be subject to an injection attack
	return sURL;
}


// utility function
function getGetParametersQfSpecificationRequestString(sql_package, sql_procedure_name, context, taskId)
{
    current_task_id = taskId;
	var sURL = "";
	var cl = "cl";
	var locales = getLocales(cl, "pl");	
		
	sURL += URIEncode(cl, locales[cl]);
	sURL += URIEncode("inlineSpecType", "queryFrameworkSpecification");	
	sURL += URIEncode("sql_package", sql_package);
	sURL += URIEncode("sql_procedure_name", sql_procedure_name);
	sURL += URIEncode("context", context);
	sURL += URIEncode("method", "getParametersSpecification");
	sURL += URIEncode("parameterValues", getConnectionParameterValues(taskId));
	sURL += URIEncode("displayedPage", "sql");
	sURL += URIEncode("prompt", "false");
	// always have to ask for credential parameters too 
	sURL += URIEncode("credentialParameters", "true");
	
	var messageIFrame = getMessageIFrame();
	var messageIFrame_doc = getFrameDocument(messageIFrame);
	
	if(messageIFrame_doc){
	        var model = messageIFrame_doc.getElementById('model');
	        var modelValue = "";
					
	        if(model && model.value != ""){
				modelValue = model.value;
				sURL += URIEncode("model", modelValue);
	        } else {
				var routingServerGroup = messageIFrame_doc.getElementById('ui.routingServerGroup');
				var routingServerGroupValue = "";
				if(routingServerGroup && routingServerGroup.value != ""){
					routingServerGroupValue = routingServerGroup.value;
					sURL += URIEncode("routingServerGroup", routingServerGroupValue);
				}
			}
	}
	current_param_response_xts = URIEncode("buildResponseXTS","/ags/async/getSpParametersResponse.xts");
	current_param_response_xts += URIEncode("buildRequestXTS","/ags/async/spParamRequest.xts");

    //SEC_INFO sUrl - The request is not parsed as a string so should not be subject to an injection attack
	return sURL;
}

function getRequestFromMethod(clientContext, current_task_id) {
    
    if (typeof current_gp_method == "function") {
        //Get the function name
        var fName = current_gp_method.toString().match(/function (\w+)/)[1];

        if (fName == 'getGetParametersQfSpecificationRequestString') {
            return getGetParametersQfSpecificationRequestString(null,null,clientContext, current_task_id);
        } else if (fName == 'getGetParameterRequestString') {
            return getGetParameterRequestString(null,clientContext, current_task_id);
        }
    }
}

function promptGetParametersResponse(parameters, response, conversation, clientContext, tracking)
{
	if (response == "Cancel" || response == "Error")
	{
		// we don't want to close everything down - so just cancel the prompt and parameter load
		injectHTML("");
		// hide the dialog frame 
		hideDialogFrame();
	}
	else
	{
		// we're passed the parameters - so save them for the task
	    saveParameterValues(parameters, current_task_id);
		// send the context and the final response from prompts back
		var request = getRequestFromMethod(clientContext, current_task_id);
		//request += URIEncode("context", clientContext);
		request += URIEncode("promptResponse", response);
        request += URIEncode("disp_trackingInfo", tracking);       

		// hide the dialog frame 
		hideDialogFrame(); 

		//SEC_INFO request - javascript encode the request prior to firing setTimeout. The
		//setTimeout function will un-encode the request before it is submitted
		request = jsStrEncode(request);
		// resubmit the request
		setTimeout("doGetParametersRequest(\'" + request + "\');",100);
	}
}

//called to initiate the asynch request
function startGetParametersRequest(request, gp_method){
    applicationActionManager.blockActions();
    //ahh the beauty of function pointers!
    current_gp_method = gp_method ? gp_method : getGetParameterRequestString;
    doGetParametersRequest(request);
}

function resendLoadParameters() {
    getCommandStackManager().getCommandStack().push("doGetParametersRequest()");
}

function doGetParametersRequest(request,isSecondary)
{
    if (request == undefined || request.length ==0) {
        request = doGetParametersRequestURL;
    } else if (!isSecondary) {
        doGetParametersRequestURL = request;
    }

	// build up the URL
	var url = "b_action=xts.run";
	url += URIEncode("m","/ags/async/asyncConv.xts");
	//url += URIEncode("buildResponseXTS","/ags/async/getParametersResponse.xts");
	// force SOAPFault for passport expire instead of getting a logon page 
	url += URIEncode("forceSOAPFault","false");
	url += current_param_response_xts;
	url += request;

	if (cafContextId != "") {
		url += URIEncode("cafcontextid",cafContextId);
		//SEC_INFO url - The request is not parsed as a string so should not be subject to an injection attack
	}
    
    try{
    	// send off the resquest
    	sendDispatcherRequestWithXMLTextResponse(url, getParametersXMLTextResponse);
    }catch(ex){
        applicationActionManager.allowActions(ex);    
    }
}

function getParametersXMLTextResponse(responseArray)
{
    // get the values returned
    var responseXML = responseArray[0];
    var responseText = responseArray[1];

    var workingRoot = responseXML.getElementsByTagName(ASYNC_WORKING);
    var promptingRoot = responseXML.getElementsByTagName(ASYNC_PROMPTING);
    var getParametersResponseRoot = responseXML.getElementsByTagName(GET_PARAMETERS_RESPONSE_ROOT);

    var httpStop = true;

    var parsedResponse = parseResponse(responseXML,responseText);
    // decide what we're going to do
    //This is a case when getContent in asyncConv faults with either session expiry or
    //external logon to a different name space fault.
    if (parsedResponse.isLogonFault()) {
        doPassportExpire(responseXML,resendLoadParameters,parsedResponse);
    } else if (parsedResponse.isSoapFault()) {
        if (parsedResponse.isCancelledWait()) {
            //This was a server cancelled wait. We need to resubmit. This could happen
            //if we have a SSO on and we hit an password protected external datasource,
            //The dispacther will fire the same request again, in this wait fired twice
            //Will cancel conversation if first wait fails. WO1903, WO2338
            resendLoadParameters();
            setTimeout("getCommandStackManager().processCommandStack()", 100);
        } else {
            // we have a fault which is a genuine fault fault
            doSOAPFault(responseXML,tidyParametersDiv,parsedResponse);
        }
    } else if (workingRoot.length == 1) {
        httpStop = false;
        // we have a working response
        doWorking(workingRoot[0], "doGetParametersRequest");
    } else if (promptingRoot.length == 1) {
        // are we prompting - promptGetParametersResponse
        doPrompting(promptingRoot[0], 2);
    } else if (getParametersResponseRoot.length == 1) {
        httpStop = false;
        // we have the actually information
        useGetParametersResponse(getParametersResponseRoot[0]);
    } else {
        tidyParametersDiv();

        if (parsedResponse.isHTML() && !parsedResponse.isEmptyBody()) {
            // check the text response to see if we got a html page back in the response
            doHTMLResponse(responseText);
        } else {	    
            // send the alert 
            alert(asyncGetParametersError_string);
        }
    }

    if(httpStop){
        applicationActionManager.allowActions();    
    }
}

function useGetParametersResponse(responseRootNode)
{
	// get the markup and the script which is returned
	var markupNode = responseRootNode.getElementsByTagName(GET_PARAMETERS_MARKUP);
	// get the actual values from here
	var markup = getTextNodeValue(markupNode[0]);
	
	// do the HTML injection - should be interesting 
	injectHTML(markup);
	
	// also want to call a function in page - to set dropZones
	var parameterNodes = responseRootNode.getElementsByTagName(GET_PARAMETERS_DISPLAY_PARAMETER);
	var parameterArray = new Array();
	for (var i = 0; i < parameterNodes.length; ++i) {
		var obj = new Object();
		obj.name = parameterNodes[i].getAttribute(GET_PARAMETERS_NAME_ATTR);
		if (parameterNodes[i].getAttribute(GET_PARAMETERS_MODELVALUE_ATTR)) {
			obj.modelValue = parameterNodes[i].getAttribute(GET_PARAMETERS_MODELVALUE_ATTR);
		}
		var val = parameterNodes[i].getAttribute('value');
		val = val.replace(/\?/g, "");
		obj.sqlValue = val;
		// save the object
		parameterArray.push(obj);
	}
	// have to execute the function
	messageIFrame.initPromptPage(parameterArray);
}

//if we have an error, or if we move to a package with
//no stored procedures, then the getParameters call is never made
//we must manually clean up the pvs
function clearParametersValues(){
    var messageIFrame = getMessageIFrame();
	var messageIFrame_doc = getFrameDocument(messageIFrame);
	
	if(messageIFrame_doc){
        var tps = messageIFrame_doc.getElementById('taskParameters');
        if(tps){
            tps.value = "";
        }
    }
}

function injectHTML(markup)
{
	// do the HTML injection - should be interesting 
	var messageIFrame = getMessageIFrame();
	var messageIFrame_doc = getFrameDocument(messageIFrame);
	// get the insertion location - and inject the HTML
	var promptValuesDiv = messageIFrame_doc.getElementById("promptValuesDiv");
	promptValuesDiv.innerHTML=markup;
	
	if(messageIFrame.initInjectedHtml){
		
		messageIFrame.initInjectedHtml();	
	}
	applicationActionManager.allowActions();
}

function tidyParametersDiv() {
    var html = '<a href="#" onclick="loadParameters()">' + refresh_string + '</a>';
    // something went radically wrong - we want to tidy up a little 
	injectHTML(html);
	// hide the dialog frame 
	hideDialogFrame();
}

////////////////////////////////////
//collect stuff
///////////////////////////////////

//called to initiate the asynch request
function doXHTTPCollectParameterValues(){
    setAsynchRequestCancelled(false);
    addDebugWaitMessage("sending collect parameters request");
    doCollectParameterValuesSpecificationRequest(getCollectParameterValuesSpecificationRequestString());
}

function getCollectParameterValuesSpecificationRequestString()
{
	var sURL = "";
	var cl = "cl";
	var locales = getLocales(cl, "pl");	
		
	sURL += URIEncode(cl, locales[cl]);
	var spec = getConfigFrame().cfgGet("inlineSpec");
	sURL += URIEncode("inlineSpec",spec);
	//what is this?
	//sURL += URIEncode("context", context);
	sURL += URIEncode("method", "collectParameterValuesSpecification");
	//pass in any cached connection parameters
	sURL += URIEncode("parameterValues",getConnectionParameterValues());
	sURL += URIEncode("prompt", "false");
	sURL += URIEncode("model", cfgGet("cmLastModel"));
	// always have to ask for credential parameters too 
	//sURL += URIEncode("credentialParameters", "true");

	// return the request
	return sURL;
}

function doCollectParameterValuesSpecificationRequest(request)
{
    // build up the URL
	var url = "b_action=xts.run";
	url += URIEncode("m","/ags/async/asyncConv.xts");
	// force SOAPFault for passport expire instead of getting a logon page 
	url += URIEncode("forceSOAPFault","false");
	url += request;
    
	if (cafContextId != "") {
		url += URIEncode("cafcontextid",cafContextId);
	}
    
    try{      
    	// send off the resquest
    	sendDispatcherRequestWithXMLTextResponse(url, collectParametersXMLTextResponse);
    }catch(ex){
        processAsynchCancel();
		throw ex;  
    }
}

function resendDoXHTTPCollectParameterValues() {
    getCommandStackManager().getCommandStack().push("doXHTTPCollectParameterValues()");
}

function collectParametersXMLTextResponse(responseArray)
{
    // get the values returned
    var responseXML = responseArray[0];
    var responseText = responseArray[1];

    var workingRoot = responseXML.getElementsByTagName(ASYNC_WORKING);
    var promptingRoot = responseXML.getElementsByTagName(ASYNC_PROMPTING);
    var asyncReply = responseXML.getElementsByTagName(ASYNC_RESPONSE);
    var cancelledRoot = responseXML.getElementsByTagName(CANCEL_RESPONSE);

    var parsedResponse = parseResponse(responseXML,responseText);
    // decide what we're going to do
    //This is a case when getContent in asyncConv faults with either session expiry or
    //external logon to a different name space fault.
    if (parsedResponse.isLogonFault()) {
        addDebugWaitMessage("Passport expired");
        doPassportExpire(responseXML,resendDoXHTTPCollectParameterValues,parsedResponse);
    } else if (parsedResponse.isSoapFault()) {
        if (parsedResponse.isCancelledWait()) {
            //This was a server cancelled wait. We need to resubmit. This could happen
            //if we have a SSO on and we hit an password protected external datasource,
            //The dispacther will fire the same request again, in this wait fired twice
            //Will cancel conversation if first wait fails. WO1903, WO2338
            resendDoXHTTPCollectParameterValues();
            setTimeout("getCommandStackManager().processCommandStack()", 100);
        } else {
            addDebugWaitMessage("Soap fault");
            // we have a fault which is a genuine fault fault
            doSOAPFault(responseXML,null,parsedResponse);
        }
    } else if (workingRoot.length == 1) {

       if(isAsynchRequestCancelled()){
	        doCancel(workingRoot[0], "doCollectParameterValuesSpecificationRequest");
	    }else{
	        addDebugWaitMessage("waiting for parameters");
    		// we have a working response
            doWorking(workingRoot[0], "doCollectParameterValuesSpecificationRequest");
    	}
    } else if (cancelledRoot.length == 1 || isAsynchRequestCancelled()) {
        addDebugWaitMessage("cancelled");
		// we are cancelled
		processAsynchCancel();
	} else if (promptingRoot.length == 1) {
        addDebugWaitMessage("prompting");
        // are we prompting - promptCollectResponse
        doPrompting(promptingRoot[0], 3);
    } else if (asyncReply.length == 1) {
        addDebugWaitMessage("done.");
        if(!getCommandStackManager().getCommandStack().isEmpty()){
            // none of the above - there are no prompts to prompt
            setTimeout("getCommandStackManager().processCommandStack()", 100);          
        } else {
           processAsynchCancel(); 
        }
    } else {
        if (parsedResponse.isHTML() && !parsedResponse.isEmptyBody()) {
            addDebugWaitMessage("html response in getParameters");
            // check the text response to see if we got a html page back in the response        
            doHTMLResponse(responseText);
        } else {	    
            // send the alert 
            alert(asyncGetParametersError_string);
        }    
    }
}

//we have values returned, save and continue
function promptCollectResponse(parameters, response, conversation, clientContext)
{
    if (response != "Cancel" && response != "Error")
    {
        //re write any connection ParameterValues saved
		saveParameterValues(parameters);
        
        //close the pop up when the prompt page reloads to finish
        doSetPopUpClosureFlag();
        
        //TODO save other params
        setTimeout("getCommandStackManager().processCommandStack()", 500);
    }else{
        //close the pop up
        doClosePopUp();
        //and clear the stack
        setTimeout("getCommandStackManager().getCommandStack().clear()", 100);
    }
}