/*
 * Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
 *
 * 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.
 */

/*
services.js is manipulate the service related scripts.
*/


/////////////////////////////////////////
// Globle variables services

var serviceSpecificName = "";
var lastUsedServiceId = "";
////////////////////////////////////////

////////////////////////////////////////
// Globle variable for operation


var serviceOperationParameters = "";
var OPERATION_ADMIN_SERVER_URL = "OperationAdmin";
var lastOperationUsed = "";

////////////////////////////////////////


////////////////////////////////////////
// Module Specific

var moduleSpanToUse = "";
var moduleComboName = "";

var setModuleVersion = "";
var setModuleName = "";
var MODULE_ADMIN_STRING = "ModuleAdmin";
var MODULE_ADMIN_SERVER_URL = "ModuleAdmin";
var setOperationName = "";
///////////////////////////////////////


//////////////////////////////////////
// Policy specific

var lastUsedServiceVersion = "";


////////////////////////////////////


//////////////////////////////////////////
// stub generation

var genFileKey = "";
var mainservicPortComboValue = "";
var mainServiceBindingName = "";

///////////////////////////////////////////

var defaultHttpPort;
var defaultBrowserHost;
var SERVICE_REFRESH_TIME = 10000;

// This holds thread's id, which is positive
var listServiceDataRequestInterval = 0;
var showListServiceDataDiv = false;

var listServiceGroupsRequestInterval = 0;
var showListServcieGroupDiv = false;
//////////////////////////////////////////

var operationNameForEngagedOperationHandlers;

// getters and setters

function getServiceSpecificName() {
    return serviceSpecificName;
}

function getServiceOperationParameters() {
    return serviceOperationParameters;
}


function listServiceGroups() {
    var body_xml = '<ns1:listServiceGroups  xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                   ' </ns1:listServiceGroups>\n';

    var callURL = serverURL + "/" + SERVICE_GROUP_ADMIN_STRING + "/" + "listServiceGroups";

    if (document.getElementById("divListServiceGroups").style.display == 'none' &&
        showListServcieGroupDiv) {
        showListServcieGroupDiv = false;
        clearInterval(listServiceGroupsRequestInterval);
        listServiceGroupsRequestInterval = 0;
        // this is to counter if focus to divHome is vanished.
        return false;

    }
    new wso2.wsf.WSRequest(callURL, "listServiceGroups", body_xml, listServiceGroupsCallback);
}

function listServiceGroupsCallback() {
    showListServcieGroupDiv = true;
    //    wso2.wsf.Util.callbackhelper(this.req.responseXML,("list_services.xsl", document.getElementById("divListServiceGroups"));
    transformationWithoutHistory(this.req.responseXML,"list_services_info.xsl", document.getElementById("listServicesInformation"),[["resourceHTTPEPR",HTTP_URL + "/"]]);
    //showing the non refreshing Div
    document.getElementById('formsetWrapper').style.display = 'inline';
    loadFaultyServices();

}

function loadFaultyServices() {
    var body_xml = '<req:getNumberOfFaultyServicesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' </req:getNumberOfFaultyServicesRequest>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" ;
    new wso2.wsf.WSRequest(callURL, "getNumberOfFaultyServices", body_xml, loadFaultyServicesCallback);
}

function loadFaultyServicesCallback() {

    var obj = document.getElementById('faultyServices');

    var data = this.req.responseXML;
    var intValue = data.getElementsByTagName("return")[0].firstChild.nodeValue;

    if (intValue == '0') {
        obj.style.display = 'none';
    } else {
        obj.style.display = 'inline';
        obj.innerHTML =
        '<h4><a href="#" onClick="javascript:listFaultyArchives(); return false;"><b><i>[' +
        intValue + '] faulty service(s)</a></i></b></h4>';
    }

}

function deleteServiceGroupCallBack() {

    wso2.wsf.Util.cursorWait();
    setTimeout("showAARGenerationCompleteMsg('The Service Group has been successfully deleted. This page will be refreshed shortly.')",
            1000);

}

function deleteServiceGroup(serviceGroupName) {
    var delete_to = confirm("Do you really want to delete [" + serviceGroupName + "] ?");
    if (delete_to == true) {
        /* stopping the refreshing first */
        stoppingRefreshingMethodsHook();
        var body_xml = '<req:deleteServiceGroupRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                       ' <req:serviceGroupName>' + serviceGroupName + '</req:serviceGroupName>\n' +
                       ' </req:deleteServiceGroupRequest>\n';

        var callURL = serverURL + "/" + "ServiceGroupAdmin" ;
        new wso2.wsf.WSRequest(callURL, "deleteServiceGroup", body_xml, deleteServiceGroupCallBack);
    } else {
        //        alertMessage("Aborted Deletion !");
        return false;
    }
}
function showAARGenerationCompleteMsg(msg) {
    wso2.wsf.Util.cursorClear();
    wso2.wsf.Util.alertMessage(msg);
    showServiceInitializer();
}

function listServiceDataRefresh(serviceName) {
    /*stopping the refreshing first */
    stoppingRefreshingMethodsHook();

    serviceSpecificName = serviceName;
    listServiceData(serviceName);

    if (listServiceDataRequestInterval == 0) {
        listServiceDataRequestInterval = setInterval(function() {
            listServiceData(getServiceSpecificName());
        }, SERVICE_REFRESH_TIME);
    }


}

function listGeneralServiceData(serviceName) {
    var bodyXML = '<req:getServiceData xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:serviceName>' + serviceName + '</req:serviceName>\n' +
                   ' </req:getServiceData>\n';
    var callURL = wso2.wsf.Util.getServerURL() + "/" + "GeneralServices";
    new wso2.wsf.WSRequest(callURL, "urn:getServiceData", bodyXML, listGeneralServiceDataCallback);

}

function listGeneralServiceDataCallback() {
    //todo
    wso2.wsf.Util.callbackhelper(this.req.responseXML,"list_general_services_main_info.xsl" , document.getElementById("divServicesGeneralDescription"));

}

function listServiceData(serviceName) {
    var body_xml = '<req:getServiceDataRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:serviceName>' + serviceName + '</req:serviceName>\n' +
                   ' </req:getServiceDataRequest>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" + "/" ;

    if (document.getElementById("divListServiceData").style.display == 'none' &&
        showListServiceDataDiv) {
        showListServiceDataDiv = false;
        clearInterval(listServiceDataRequestInterval);
        listServiceDataRequestInterval = 0;
        // this is to counter if focus to divHome is vanished.
        return false;

    }

    new wso2.wsf.WSRequest(callURL, "getServiceData", body_xml, listServiceDataCallback);

}

/**
 * Configure service level MTOM handling
 */
function configServiceMTOM(flag,serviceName) {
    stoppingRefreshingMethodsHook();

    var body_xml = '<req:configureMTOM xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<flag>' + flag + '</flag>\n' +
                   '<serviceName>' + serviceName + '</serviceName>\n' +
                   '</req:configureMTOM>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" + "/" ;

    new wso2.wsf.WSRequest(callURL, "urn:configureMTOM", body_xml, configServiceMTOMCallback);
}

function configServiceMTOMCallback() {

    listServiceDataRefresh(serviceSpecificName);

}

function listServiceDataCallback() {

    showListServiceDataDiv = true;
    wso2.wsf.Util.callbackhelper(this.req.responseXML,"list_service_main_info.xsl", document.getElementById("divListServiceData"));

}

function activationOfService(serviceStatus) {
    var body_xml = '';
    var callURL = serverURL + "/" + "ServiceAdmin" ;
    var soapAction = "";
    if (serviceStatus == true) {
        body_xml = '<req:startServiceRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:serviceName>' + serviceSpecificName + '</req:serviceName>\n' +
                   ' </req:startServiceRequest>\n';
        soapAction = "startService";
    }
    if (serviceStatus == false) {
        body_xml = '<req:stopServiceRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:serviceName>' + serviceSpecificName + '</req:serviceName>\n' +
                   ' </req:stopServiceRequest>\n';
        soapAction = "stopService";

    }
    new wso2.wsf.WSRequest(callURL, soapAction, body_xml, activationOfServiceCallback);
}

function activationOfServiceCallback() {

    wso2.wsf.Util.cursorWait();
    setTimeout("showlistSericeData()", 1000);
}


function showlistSericeData() {
    wso2.wsf.Util.cursorClear();
    listServiceData(serviceSpecificName);
    var obj = document.getElementById("divListServiceData");
    wso2.wsf.Util.showOnlyOneMain(obj);
}

function listAllOperations(serviceName) {

    /*stopping the refreshing first */
    stoppingRefreshingMethodsHook();

    serviceSpecificName = serviceName;
    lastUsedServiceId = serviceName;
    // need to see the output to write the xsl
    var xsltFileName = "";
    var body_xml = '<ns1:listAllOperations xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                   ' <arg0>' + serviceName + '</arg0>\n' +
                   ' <arg1>' + serviceName + '</arg1>\n' +
                   ' </ns1:listAllOperations>\n';

    var callURL = serverURL + "/" + "OperationAdmin" + "/" + "listAllOperations";
    new wso2.wsf.WSRequest(callURL, "listAllOperations", body_xml, listAllOperationsCallback);
}

function listAllOperationsCallback() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,"list_operations.xsl", document.getElementById("divListAllOperations"));
    showlistOperationsHeader(document.getElementById('listOperationsHeader'));
}


/**
 * configure opeation level mtom
 */
function configOperationMTOM(flag,operation){
    var body_xml = '<ns1:configureMTOM xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                   '<flag>' + flag + '</flag>\n' +
                   '<serviceName>' + serviceSpecificName + '</serviceName>\n' +
                   '<operationName>' + operation + '</operationName>\n' +
                   '</ns1:configureMTOM>\n';

    var callURL = serverURL + "/" + "OperationAdmin" + "/";
    new wso2.wsf.WSRequest(callURL, "urn:configureMTOM", body_xml, configOperationMTOMCallback);

}

function configOperationMTOMCallback() {

    listAllOperations(serviceSpecificName);

}

function engageModulePerService(serviceName) {

    /*stopping the refreshing first */
    stoppingRefreshingMethodsHook();

    lastUsedServiceId = serviceName;
    var objDiv = document.getElementById("divEngageModule");
    var strHTML = "<h4><a href='#' onClick='javascript:showServiceInitializer(); return false;'>Services</a>&nbsp;&gt;&nbsp;<a href='#' onClick='javascript:listServiceData(\"" +
                  serviceName + "\"); return false;'>" + serviceName +
                  "</a>&nbsp;&gt;&nbsp;Engage Modules</h4>" +
                  "<fieldset style='border: none;'>" +
                  "<div id='formset'>" +
                  "<form>" +
                  "<fieldset>" +
                  "<legend>Engage module to service " + serviceName + "</legend>" +
                  "<div><label>Module</label><span id='engageModulePerServiceCombo'></span></div>" +
                  "<div class='buttonrow'><input type='button' onclick='javascript:engageModulePerServiceExec(\"" +
                  serviceName +
                  "\", document.getElementById(\"cmbEngageModulePerServiceCombo\").value);' value='Engage'/></div>" +
                  "</fieldset>" +
                  "</form>" +
                  "<div id='modulesPerServiceOnly' style='display:inline; position: relative; top: 20px;'></div>" +
                  "<div id='modulesEngagedOnParent' style='display:inline; position: relative; top: 20px;'></div>" +
                  "<div id='globleModulesOnService' style='display:inline; position: relative; top: 20px;'></div>" +
                  "</div>" +
                  "</fieldset>";

    var body_xml = '<req:listServiceModulesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:serviceName>' + serviceName + '</req:serviceName>\n' +
                   ' </req:listServiceModulesRequest>\n';

    objDiv.innerHTML = strHTML;
    wso2.wsf.Util.showOnlyOneMain(objDiv);

    var callURL = serverURL + "/" + "ModuleAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL, "listServiceModules", body_xml, engageModulePerServiceCombo);

    // get Globalling engaged Modules

}

function engageModulePerServiceCombo() {

    var xsltFileName = "list_engaged_modules_per_service.xsl";
    var objDiv = document.getElementById("modulesPerServiceOnly");
    var data = this.req.responseXML;
    wso2.wsf.Util.processXML(data, xsltFileName, objDiv);
    //alert("Callback fired");
    //    getGlobalModuleCombo(document.getElementById("engageModulePerServiceCombo"), "cmbEngageModulePerServiceCombo");
    getGlobalModuleComboService(document.getElementById("engageModulePerServiceCombo"), "cmbEngageModulePerServiceCombo");


}

function getGlobalModuleComboService(cmbSpan, cmbName) {
    moduleSpanToUse = cmbSpan;
    moduleComboName = cmbName;
    //    alert("Global module getting function called");

    var body_xml = '<ns1:listModules  xmlns:ns1="http://org.apache.axis2/xsd"/>\n';

    var callURL = serverURL + "/" + MODULE_ADMIN_STRING + "/" + "listModules";
    new wso2.wsf.WSRequest(callURL, "listModules", body_xml, getGlobalModuleComboPerServiceCallback);

}

function getGlobalModuleComboPerServiceCallback() {

    var data = this.req.responseXML;

    //    alert("XSL = " + (new XMLSerializer()).serializeToString(data));

    var strHTML = "<select id='" + moduleComboName + "'>";
    var rets = data.getElementsByTagName("return");
    var len = rets.length;
    var count;
    var moduleVersion;
    for (count = 0; count < len; count++) {
        if (rets[count].getElementsByTagName("moduleVersion")[0].firstChild != null) {
            moduleVersion =
            rets[count].getElementsByTagName("moduleVersion")[0].firstChild.nodeValue;
        } else {
            moduleVersion = "";
        }
        displayModuleVersion = (moduleVersion == "" ? "" : ("-" + moduleVersion));
        strHTML +=
        "<option value='" + rets[count].getElementsByTagName("moduleId")[0].firstChild.nodeValue +
        '||' + moduleVersion + "'>" +
        rets[count].getElementsByTagName("modulename")[0].firstChild.nodeValue +
        displayModuleVersion + "</option>\n";
    }
    strHTML += "</select>"

    moduleSpanToUse.innerHTML = strHTML;

    //globally engage

    body_xml = '<req:listGloballyEngagesModulesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
               ' </req:listGloballyEngagesModulesRequest>\n';
    callURL = serverURL + "/" + "ModuleAdmin" + "/";
    new wso2.wsf.WSRequest(callURL, "listGloballyEngagesModules", body_xml, listGloballyEngageModulesPerServiceCallback);
}

function listGloballyEngageModulesPerServiceCallback() {

    var xsltFileName = "list_engaged_modules_per_service.xsl";
    var objDiv = document.getElementById("globleModulesOnService");
    var data = this.req.responseXML;
    wso2.wsf.Util.processXML(data, xsltFileName, objDiv);

    // Engaged Modules this service's parent

    var body_xml = '<req:listServicesParentEngagedModulesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<serviceName>' + lastUsedServiceId + '</serviceName>\n' +
                   '</req:listServicesParentEngagedModulesRequest>\n';
    callURL = serverURL + "/" + "ModuleAdmin" + "/";

    new wso2.wsf.WSRequest(callURL, "listServicesParentEngagedModules", body_xml, listServicesParentEngagedModulesCallback);

}

function listServicesParentEngagedModulesCallback() {

    var xsltFileName = "list_engaged_modules_per_service.xsl";
    var objDiv = document.getElementById("modulesEngagedOnParent");
    var data = this.req.responseXML;
    wso2.wsf.Util.processXML(data, xsltFileName, objDiv);

}


function engageModulePerServiceExec(serviceName, moduleName) {
    var moduleVersion = moduleName.substring(moduleName.indexOf('||') + 2, moduleName.length);
    lastUsedServiceId = serviceName;
    setModuleVersion = moduleVersion;
    moduleName = moduleName.substring(0, moduleName.indexOf('||'));
    //	alert("engageModulePerServiceExec Called with serviceName = " +serviceName + " || moduleName = " + moduleName + " ||| moduleVersion = " + moduleVersion);
    setModuleName = moduleName;
    var body_xml = '<req:engageModuleForServiceRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:moduleId>' + moduleName + '</req:moduleId>\n' +
                   ' <req:moduleVersion>' + moduleVersion + '</req:moduleVersion>\n' +
                   ' <req:serviceId>' + serviceName + '</req:serviceId>\n' +
                   ' <req:serviceVersion></req:serviceVersion>\n' +
                   ' </req:engageModuleForServiceRequest>\n';

    var callURL = serverURL + "/" + "ModuleAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL, "engageModuleForService", body_xml, engageModulePerServiceCallBack);


}

function engageModulePerServiceCallBack() {

    var data = this.req.responseXML;
    var text = data.getElementsByTagName('return')[0];

    wso2.wsf.Util.alertMessage(text.firstChild.nodeValue);

    setTimeout(function() {
        engageModulePerService(lastUsedServiceId);
    }, 1000);
    //    engageModulePerService(lastUsedServiceId);
}


function getServiceSpecficParametersForConfig(serviceName,serviceType) {
    /*stopping the refreshing first */
    stoppingRefreshingMethodsHook();

    if (serviceName == null) {
        serviceName = lastUsedServiceId;
    } else {
        lastUsedServiceId = serviceName;
        serviceSpecificName = serviceName;
    }
    var body_xml = '<req:getDeclaredServiceParametersRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:serviceId>' + serviceName + '</req:serviceId>\n' +
                   ' <req:serviceVersion>' + serviceName + '</req:serviceVersion>\n' +
                   ' </req:getDeclaredServiceParametersRequest>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" ;

	if(serviceType != 'ejb_service' || serviceType == null){
    	new wso2.wsf.WSRequest(callURL, "getDeclaredServiceParameters", body_xml, getServiceSpecficParametersForConfigCallback);
	}else {
    	new wso2.wsf.WSRequest(callURL, "getDeclaredServiceParameters", body_xml, getServiceSpecficParametersForEJBConfigCallback);
	}
}

function getServiceSpecficParametersForConfigEJB(serviceName,serviceType) {
    /*stopping the refreshing first */
    stoppingRefreshingMethodsHook();

    if (serviceName == null) {
        serviceName = lastUsedServiceId;
    } else {
        lastUsedServiceId = serviceName;
        serviceSpecificName = serviceName;
    }
    var body_xml = '<req:getDeclaredServiceParametersRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:serviceId>' + serviceName + '</req:serviceId>\n' +
                   ' <req:serviceVersion>' + serviceName + '</req:serviceVersion>\n' +
                   ' </req:getDeclaredServiceParametersRequest>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" ;

	if(serviceType == 'Normal' || serviceType == null){
    	new wso2.wsf.WSRequest(callURL, "getDeclaredServiceParameters", body_xml, getServiceSpecficParametersForConfigCallback);
	}else if(serviceType == 'ejb_service'){
    	new wso2.wsf.WSRequest(callURL, "getDeclaredServiceParameters", body_xml, getServiceSpecficParametersForEJBConfigCallback);
	}
}

function getServiceSpecficParametersForConfigCallback() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,"list_service_param_edit.xsl", document.getElementById("divGetServiceSpecficParametersForConfig"));
    showlistServiceParamEditHeader(document.getElementById('listServiceParamEditHeader'));
}
function getServiceSpecficParametersForEJBConfigCallback() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,"list_service_param_edit_ejb_service.xsl", document.getElementById("divGetServiceSpecficParametersForConfig"));
    showlistServiceParamEditHeader(document.getElementById('listServiceParamEditHeader'));
}


function arrangeEJBServiceParams(pArr, vArr) {
	var pA=new Array();
	var vA=new Array();
	
	pA[0]='remoteInterfaceName';
	for(var index=0; index<pArr.length; index++) {
		if (pArr[index]=='remoteInterfaceName') {
			vA[0]=vArr[index];
			pArr.splice(index, 1);
			vArr.splice(index, 1);
			break;
		}
	}
	pA[1]='homeInterfaceName';
	for(var index=0; index<pArr.length; index++) {
		if (pArr[index]=='homeInterfaceName') {
			vA[1]=vArr[index];
			pArr.splice(index, 1);
			vArr.splice(index, 1);
			break;
		}
	}
	pA[2]='beanJndiName';
	for(var index=0; index<pArr.length; index++) {
		if (pArr[index]=='beanJndiName') {
			vA[2]=vArr[index];
			pArr.splice(index, 1);
			vArr.splice(index, 1);
			break;
		}
	}
	pA[3]='jndiUser';
	for(var index=0; index<pArr.length; index++) {
		if (pArr[index]=='jndiUser') {
			vA[3]=vArr[index];
			pArr.splice(index, 1);
			vArr.splice(index, 1);
			break;
		}
	}
	
	pA[4]='jndiPassword';
	for(var index=0; index<pArr.length; index++) {
		if (pArr[index]=='jndiPassword') {
			vA[4]=vArr[index];
			pArr.splice(index, 1);
			vArr.splice(index, 1);
			break;
		}
	}
	for(var index=0, i=5; index<pArr.length; index++,i++) {
		pA[i] = pArr[index];
		vA[i] = vArr[index];
	}
	var str='';
	var label;
	for(var index=0; index<pA.length; index++) {
		if(pA[index]=='remoteInterfaceName') {
			label='Remote Interface Name';
		}
		else if (pA[index]=='homeInterfaceName') {
			label='Home Interface Name';
		}
		else if (pA[index]=='beanJndiName') {
			label='Bean JNDI Name';
		}
		else if (pA[index]=='jndiUser') {
			label='JNDI User';
		}
		else if (pA[index]=='jndiPassword') {
			label='JNDI Password';
		}
		else if (pA[index]=='serviceType') {
			label='Service Type';
		}
		else if (pA[index]=='jndiContextClass') {
			label='JNDI Context Class';
		}
		else if (pA[index]=='providerUrl') {
			label='Provider URL';
		}
		else if (pA[index]=='ServiceClass') {
			label='Service Class';
		}
		str = str +  '<div style="clear:both;"><label style="width: 25%">' + label + '</label>';
		str = str + '<input type="text" size="50" value="' + vA[index] + '"';
		str += ' id="' + pA[index] + '"';
		str += 'tabindex="'+index + '"';
		if (pA[index]=='serviceType' || pA[index] == 'ServiceClass'){
			str += ' disabled=true ';
		}
		str = str + '></input></div>';
		
	}
	document.getElementById('param_div').innerHTML=str;
}


////////////////////////////////////////////////////////////////////////////////
//                            <wsp:Policy> 				      //
////////////////////////////////////////////////////////////////////////////////


function getServiceSpecificPoliciesForConfig(serviceId, serviceVersion) {

    /*stopping the refreshing first */
    stoppingRefreshingMethodsHook();

    lastUsedServiceId = serviceId;
    lastUsedServiceVersion = serviceVersion;

    serviceSpecificName = serviceId;
    // is this necessary ?

    var xsltFileName = "list_service_policies_edit.xsl";
    var body_xml = '<ns1:getPoliciesRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:serviceId>' + serviceId + '</ns1:serviceId>' +
                   '<ns1:serviceVersion>' + serviceVersion + '</ns1:serviceVersion>' +
                   '</ns1:getPoliciesRequest>';

    var callURL = serverURL + "/" + "ServiceAdmin";

    new wso2.wsf.WSRequest(callURL, "getPolicies", body_xml, getServiceSpecificPoliciesForConfigCallBack);

}


function getServiceSpecificPoliciesForConfigCallBack() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,"list_service_policies_edit.xsl", document.getElementById("divServices"));
    showlistPolicyInfoEditHeader(document.getElementById('listPolicyInfoEditHeader'));
}

function setServiceSpecificPolicyFromConfig(serviceId, serviceVersion, policyValue) {
    var body_xml = '<my:setPolicy xmlns:my="http://org.apache.axis2/xsd">' +
                   '<my:serviceId>' + serviceId + '</my:serviceId>' +
                   '<my:version>' + serviceVersion + '</my:version>' +
                   '<my:policyString><![CDATA[' + policyValue + ']]></my:policyString>' +
                   '</my:setPolicy>';

    var callURL = serverURL + "/" + "ServiceAdmin";
    new wso2.wsf.WSRequest(callURL, "setPolicy", body_xml, function() {
        wso2.wsf.Util.alertMessage("Service policy successfully updated.");
    });
}


/////////////////////////////////////////////////////// Policy Ends


/*
@deprecated
*/
function isServiceWSDLAvailable(callback) {

    /*stopping the refreshing first */
    stoppingRefreshingMethodsHook();

    var body_xml = '<req:isWSDLAvailable xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<req:serviceName>' + getServiceSpecificName() + '</req:serviceName>\n' +
                   ' </req:isWSDLAvailable>\n';

    var callURL = serverURL + "/" + "WSDLInfoService" + "/" ;
    new wso2.wsf.WSRequest(callURL, "isWSDLAvailable", body_xml, callback);

}

function isServiceWSDLAvailableTryItCallback() {

    var data = this.req.responseXML;
    //One click Jar download
    isServiceWSDLAvailableHelperTryIt(data);


}
function isServiceWSDLAvailableOneClickJarDownloadCallback() {

    var data = this.req.responseXML;
    //One click Jar download
    isServiceWSDLAvailableHelperGenerateClient(data);


}

function isServiceWSDLAvailableHelperGenerateClient(data) {
    var rets = data.getElementsByTagName("return")[0];
    var returnTextValue = rets.firstChild.nodeValue;
    if (returnTextValue == 'true') {
        //process
        stubGenerationMetaInfo();
    } else if (returnTextValue == 'false') {
        // no proecessing
        wso2.wsf.Util.alertMessage("Client generation could not continue due to WSDL not being available or\n" +
                     " the message receiver not being RPCMessageReceiver.");

    } else {
        wso2.wsf.Util.alertWarning(lable + "  Operations Could not be continued");

    }

}

function isServiceWSDLAvailableHelperTryIt(data) {
    var rets = data.getElementsByTagName("return")[0];
    var returnTextValue = rets.firstChild.nodeValue;
    if (returnTextValue == 'true') {
        //process
        dynamicClientGeneration();
    } else if (returnTextValue == 'false') {
        // no proecessing
        wso2.wsf.Util.alertMessage("DHTML generation could not continue due to WSDL not being available or\n" +
                     " the message receiver not being RPCMessageReceiver.");

    } else {
        wso2.wsf.Util.alertWarning(lable + "  Operations Couldnot be continued");

    }

}

function stubGenerationMetaInfo(wv) {
    if (!wv) {
        wv = "1.1";
    }

    var wsdlLocation;
    if (wv == "1.1") {
        wsdlLocation = HTTP_URL + '/' + getServiceSpecificName() + '?wsdl';
    } else {
       wsdlLocation = HTTP_URL + '/' + getServiceSpecificName() + '?wsdl2';
    }

    var buttonObj = document.getElementById('dynamicClientButtonId');
    if (buttonObj != null) {
        buttonObj.disabled=true;
    }

    var body_xml = '<req:listServicesAndPortsRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<serviceName>' + getServiceSpecificName() + '</serviceName>\n' +
                   '<wsdlVersion>' + wv + '</wsdlVersion>\n'+
                   '<wsdlLocation>' + wsdlLocation+ '</wsdlLocation>\n' +
                   '</req:listServicesAndPortsRequest>\n';

    var callURL = serverURL + "/" + "WSDLInfoService" + "/" ;
    wso2.wsf.Util.cursorWait();
    new wso2.wsf.WSRequest(callURL, "listServicesAndPorts", body_xml, stubGenerationMetaInfoCallback);
}

function stubGenerationMetaInfoCallback() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,"stub_meta_info.xsl", document.getElementById("divStubGeneration"));
    showstubGenMetaInfo(document.getElementById('stubGenMetaInfo'));
}

function stubGenerationSOAPRequest(packageNameObj, invocationStyleObj,
                                   generateTestCasesObj, databindingMethodObj,
                                   unpackClassesObj, serviceBindingName,
                                   serviceBindingPortObj, unwrapObj, wsdlVersionObj) {
    var packageName = packageNameObj.value;
    var serviceName = serviceSpecificName;
    var invocationStyle = invocationStyleObj[invocationStyleObj.selectedIndex].value;
    var generateTestCases = generateTestCasesObj[generateTestCasesObj.selectedIndex].value;
    var databindingMethod = databindingMethodObj[databindingMethodObj.selectedIndex].value;
    var unpackClasses = unpackClassesObj[unpackClassesObj.selectedIndex].value;
    var serviceBindingPort = serviceBindingPortObj[serviceBindingPortObj.selectedIndex].value;
    var unwrap = unwrapObj[unwrapObj.selectedIndex].value;
    var wsdlVersion = wsdlVersionObj[wsdlVersionObj.selectedIndex].value;

    var pattern = /^[a-zA-Z](([a-zA-Z_]+)([a-zA-Z0-9_]?)\.?)+[a-z0-9_]$/;
    if (packageName == null || wso2.wsf.Util.trim(packageName) == '') {
        wso2.wsf.Util.alertWarning("Package name is mandatory");
        return;
    }
    if (!pattern.test(packageName)) {
        wso2.wsf.Util.alertWarning("Package name is not valid under Java package naming conventions");
        return;
    }

    var wsdlLocation;
    if (wsdlVersion == "1.1") {
        wsdlLocation = HTTP_URL + '/' + serviceName + '?wsdl';
    } else {
       wsdlLocation = HTTP_URL + '/' + serviceName + '?wsdl2';
    }

    var buttonObj = document.getElementById('dynamicClientButtonId');
    if (buttonObj != null) {
        buttonObj.disabled = true;
    }

    var body_xml = ' <req:generateRequest xmlns:req="http://wsdl2code.service.admin.wsas.wso2.org">\n' +
                   ' <service>' + serviceName + '</service>\n' +
                   ' <packageName>' + packageName + '</packageName>\n' +
                   ' <invocationStyle>' + invocationStyle + '</invocationStyle>\n' +
                   ' <generateTestCase>' + generateTestCases + '</generateTestCase>\n' +
                   ' <databindingMethod>' + databindingMethod + '</databindingMethod>\n' +
                   ' <unpackClasses>' + unpackClasses + '</unpackClasses>\n' +
                   ' <serviceBindingName>' + serviceBindingName + '</serviceBindingName>\n' +
                   ' <servicePortName>' + serviceBindingPort + '</servicePortName>\n' +
                   ' <unwrap>' + unwrap + '</unwrap>\n' +
                   ' <wsdlVersion>' + wsdlVersion + '</wsdlVersion>\n' +
                   ' <wsdlLocation>' + wsdlLocation + '</wsdlLocation>\n' +
                   ' </req:generateRequest>\n';

    var callURL = serverURL + "/" + "JavaClientGeneratorService" ;
    wso2.wsf.Util.cursorWait();
    new wso2.wsf.WSRequest(callURL, "generate", body_xml, generateCallBack);
}

function generateCallBack() {

    //response will be a link and it will call the download dialog
    var data = this.req.responseXML;

    var responseTextValue = data.getElementsByTagName("return")[0].firstChild.nodeValue;

    var buttonObj = document.getElementById('dynamicClientButtonId');
    if (buttonObj != null) {
        buttonObj.disabled = false;
    }

    window.location = URL + responseTextValue;
}


function loadUsersComboBox() {
    var xsltFileName = "user.xsl";
    var body_xml = '<req:getUsersRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' </req:getUsersRequest>\n';

    var callURL = serverURL + "/" + "UserAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL, "getUsers", body_xml, loadUsersCallback);
}

function loadRolesComboBox() {
    //    var xsltFileName = "role.xsl";
    var body_xml = '<req:getRoleNamesAndDescriptionsRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' </req:getRoleNamesAndDescriptionsRequest>\n';

    var callURL = serverURL + "/" + "UserAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL, "getRoleNamesAndDescriptions", body_xml, loadRolesComboBoxCallback);
}

function loadRolesComboBoxCallback() {

    var comboToLoad = document.getElementById('serviceRoleName');
    var data = this.req.responseXML;
    //    alert((new XMLSerializer()).serializeToString(data));
    var rets = data.getElementsByTagName("return");
    var len = rets.length;
    var count;
    for (count = 0; count < len; count++) {
        var roleCollection = rets[count].getElementsByTagName("role");
        comboToLoad.options[count] = new Option(roleCollection[0].firstChild.nodeValue);
        comboToLoad.options[count].value = roleCollection[0].firstChild.nodeValue;
    }
    wso2.wsf.Util.showOnlyOneMain(document.getElementById("divListRoles"));
}

function loadUsersCallback() {

    var comboToLoad = document.getElementById('serviceUserName');
    var data = this.req.responseXML;
    var rets = data.getElementsByTagName("return");
    var len = rets.length;
    var count;
    for (count = 0; count < len; count++) {
        comboToLoad.options[count] = new Option(rets[count].firstChild.nodeValue);
        comboToLoad.options[count].value = rets[count].firstChild.nodeValue;
    }
}

/* @depricated */
function serviceUNameToeknAuth() {
    listUsers1();
}


function loadRolesComboBox1() {
    //    var xsltFileName = "role.xsl";
    var body_xml = '<req:getRoleNamesAndDescriptionsRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' </req:getRoleNamesAndDescriptionsRequest>\n';

    var callURL = serverURL + "/" + "UserAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL, "getRoleNamesAndDescriptions", body_xml, loadRolesComboBoxCallback1);
}

function loadRolesComboBoxCallback1() {

    var comboToLoad = document.getElementById('serviceRoleName');
    var data = this.req.responseXML;
    //    alert((new XMLSerializer()).serializeToString(data));
    var rets = data.getElementsByTagName("return");
    var len = rets.length;
    var count;
    for (count = 0; count < len; count++) {
        var roleCollection = rets[count].getElementsByTagName("role");
        comboToLoad.options[count] = new Option(roleCollection[0].firstChild.nodeValue);
        comboToLoad.options[count].value = roleCollection[0].firstChild.nodeValue;
    }
    //showOnlyOneMain(document.getElementById("divListRoles"));
}


function getOperationSpecficParameters(operation) {
    serviceOperationParameters = operation;

    showOperationSpecificStatistics();
}

//@private
function getOperationSpecficParameters0() {

    var body_xml = '<req:getDeclaredOperationParametersRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<serviceName>' + getServiceSpecificName() + '</serviceName>\n' +
                   '<operationName>' + getServiceOperationParameters() + '</operationName>\n' +
                   '</req:getDeclaredOperationParametersRequest>\n';

    var callURL = serverURL + "/" + "OperationAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL, "getDeclaredOperationParameters", body_xml, getOperationSpecficParameters0Callback);

}

function getOperationSpecficParameters0Callback() {

    transformationWithoutHistory(this.req.responseXML,"list_service_param.xsl", document.getElementById("listOperationsParameters"));

}

function showOperationSpecificStatistics() {
    var body_xml = '<req:getOperationStatisticsRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<serviceName>' + getServiceSpecificName() + '</serviceName>\n' +
                   '<operationName>' + getServiceOperationParameters() + '</operationName>\n' +
                   '</req:getOperationStatisticsRequest>\n';

    var callURL = serverURL + "/" + "OperationAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL, "getOperationStatistics", body_xml, showOperationSpecificStatisticsCallback);

}

function showOperationSpecificStatisticsCallback() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,"show_param_statistics.xsl", document.getElementById("divGetOperationSpecficParameters"));

    showlistOperationParamAndStatisticsEditHeader(document.getElementById('listServiceParamHeader'));

    getOperationSpecficParameters0();

}


function getServiceGroupSpecificParameters(group) {
    var body_xml = '<req:getDeclaredServiceGroupParametersRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:service_group_id>' + group + '</req:service_group_id>\n' +
                   ' <req:group_version></req:group_version>\n' +
                   ' </req:getDeclaredServiceGroupParametersRequest>\n';

    var callURL = serverURL + "/" + "ServiceGroupAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL, "getDeclaredServiceGroupParameters", body_xml, function() {
        wso2.wsf.Util.callbackhelper(this.req.responseXML,"list_service_group_param.xsl", document.getElementById("divServiceGroupParams"));
    });

}

function getOperationSpecficParametersForConfig(operation) {
    if (operation == null) {
        operation = serviceOperationParameters;
    } else {
        serviceOperationParameters = operation;
    }
    var body_xml = '<req:getDeclaredOperationParametersRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:serviceId>' + getServiceSpecificName() + '</req:serviceId>\n' +
                   ' <req:operationId>' + operation + '</req:operationId>\n' +
                   ' </req:getDeclaredOperationParametersRequest>\n';

    var callURL = serverURL + "/" + OPERATION_ADMIN_SERVER_URL ;
    new wso2.wsf.WSRequest(callURL, "getDeclaredOperationParameters", body_xml, getOperationSpecficParametersForConfigCallback);

}

function getOperationSpecficParametersForConfigCallback() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,"list_operation_params_edit.xsl",
            document.getElementById("divGetOperationSpecficParametersForConfig"));
    showlistOperationParamEditHeader(document.getElementById('listOperationParamEditHeader'));
}


var cur_module_number_ser = 0;
var global_arrayOfNames_ser = null;
var global_arrayOfValues_ser = null;
//operation parameter update procedure
//loop through the two arrays and pass through each and every parameter

//display the messages for the modules
function updateServiceOperationInfoDisplay(message) {
    document.getElementById('operationConfigUpdate').innerHTML = message;
}

//add operation specific parameter
function addOperationParameter() {
    var newParam = wso2.wsf.Util.getUserInput();
    if (newParam != null) {
        processSingleOperationParameterConfigEntry(
                lastUsedServiceId,
                serviceOperationParameters,
                newParam[0],
                newParam[1], getOperationSpecficParametersForConfig);
    }
}

//remove operation specific parameter
function removeOperationParameter(button) {
    processSingleOperationParameterConfigEntryRemoval(
            lastUsedServiceId,
            serviceOperationParameters,
            button.id, getOperationSpecficParametersForConfig);

}

//add a single operation parameter entry
function processSingleOperationParameterConfigEntryRemoval(
        serviceId,
        operationId,
        parameterName, operation_callback) {

    if (!parseParameterName(parameterName)) {
        wso2.wsf.Util.alertMessage("Parameter name contains an invalid character");
        return false;
    }

    var body_xml = '<ns1:removeOperationParameterRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:serviceId>' + serviceId + '</ns1:serviceId>' +
                   '<ns1:operationId>' + operationId + '</ns1:operationId>' +
                   '<ns1:group_version></ns1:group_version>' +
                   '<parameter locked="false" name="' + parameterName + '"></parameter>' +
                   '</ns1:removeOperationParameterRequest>';

    var callURL = serverURL + "/" + OPERATION_ADMIN_SERVER_URL;
    new wso2.wsf.WSRequest(callURL, "removeOperationParameter", body_xml, operation_callback);
}

function processMultipleOperationParameterConfigEntry(serviceId,
                                                      operationId,
                                                      parameterNamesObj,
                                                      parameterValueObj) {
    var paramElements = '';
    for (var i = 0; i < parameterNamesObj.length; i++) {
        paramElements += '<parameter locked="false" name="' + parameterNamesObj[i] + '"><![CDATA[' +
                         parameterValueObj[i] + ']]></parameter>\n';
    }
    var body_xml = '<ns1:setOperationParameters xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:serviceId>' + serviceId + '</ns1:serviceId>' +
                   '<ns1:operationId>' + operationId + '</ns1:operationId>' +
                   '<ns1:groupVersion></ns1:groupVersion>' +
                   paramElements +
                   '</ns1:setOperationParameters>';

    var callURL = serverURL + "/" + OPERATION_ADMIN_SERVER_URL;
    new wso2.wsf.WSRequest(callURL, "setOperationParameters", body_xml, processMultipleOperationParameterConfigEntryCallback);


}

function processMultipleOperationParameterConfigEntryCallback() {

    wso2.wsf.Util.alertMessage("Operation parameters were successfully updated.");

    getOperationSpecficParametersForConfig(getServiceOperationParameters());

}

//add a single operation parameter entry
function processSingleOperationParameterConfigEntry(
        serviceId,
        operationId,
        parameterName,
        parameterValue, operation_callback) {

    if (!parseParameterName(parameterName)) {
        wso2.wsf.Util.alertMessage("Parameter name contains an invalid character");
        return false;
    }

    var body_xml = '<ns1:setOperationParameterRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:serviceId>' + serviceId + '</ns1:serviceId>' +
                   '<ns1:operationId>' + operationId + '</ns1:operationId>' +
                   '<ns1:group_version></ns1:group_version>' +
                   '<parameter locked="false" name="' + parameterName + '"><![CDATA[' +
                   parameterValue + ']]></parameter>' +
                   '</ns1:setOperationParameterRequest>';

    var callURL = serverURL + "/" + OPERATION_ADMIN_SERVER_URL;

    new wso2.wsf.WSRequest(callURL, "setOperationParameter", body_xml, operation_callback);
}
//end of  processSingleOperationParameterConfigEntry
function engageModulePerOperation(operationName) {
    lastOperationUsed = operationName;
    var objDiv = document.getElementById("divEngageModulePerOperation");
    var strHTML = "<h4><a href='#' onClick='javascript:showServiceInitializer(); return false;'>Services</a>&nbsp;&gt;&nbsp;<a href='#' onClick='javascript:listServiceData(\"" +
                  getServiceSpecificName() + "\"); return false;'>" + getServiceSpecificName() +
                  "</a>" + "&nbsp;&gt;&nbsp;<a href='#' onClick='javascript:listAllOperations(\"" +
                  getServiceSpecificName() + "\"); return false;'>Operation[" + lastOperationUsed +
                  "]</a>&nbsp;&gt;&nbsp;Engage Module" + "</h4>" +
                  "<fieldset style='border: none;'>" +
                  "<div id='formset'>" +
                  "<form>" +
                  "<fieldset>" +
                  "<legend>Engage module to operation <font color='blue'>" + operationName +
                  "</font></legend>" +
                  "<div><label>Module</label><span id='engageModulePerOperationCombo'></span></div>" +
                  "<div class='buttonrow'><input type='button' onclick='javascript:engageModulePerOperationExec(\"" +
                  operationName +
                  "\", document.getElementById(\"cmbEngageModulePerOperationCombo\").value);' value='Engage'/></div>" +
                  "</fieldset>" +
                  "</form>" +
                  "<div id='modulesPerOperation' style='display:inline; position: relative; top: 20px;'></div>" +
                  "<div id='modulesPerService' style='display:inline; position: relative; top: 20px;'></div>" +
                  "<div id='modulesPerServiceParentEngagedModules' style='display:inline; position: relative; top: 20px;'></div>" +
                  "<div id='globleModules' style='display:inline; position: relative; top: 20px;'></div>" +
                  "</div></fieldset>";

    var body_xml = '<req:listOperationModulesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:serviceId>' + getServiceSpecificName() + '</req:serviceId>\n' +
                   ' <req:operationId>' + operationName + '</req:operationId>\n' +
                   ' </req:listOperationModulesRequest>\n';

    objDiv.innerHTML = strHTML;
    wso2.wsf.Util.showOnlyOneMain(objDiv);

    var callURL = serverURL + "/" + MODULE_ADMIN_SERVER_URL ;
    new wso2.wsf.WSRequest(callURL, "listOperationModules", body_xml, engageModulePerOperationCombo);

}

function engageModulePerOperationCombo() {

    var xsltFileName = "list_engaged_modules_per_operation.xsl";
    var objDiv = document.getElementById("modulesPerOperation");
    var data = this.req.responseXML;
    wso2.wsf.Util.processXML(data, xsltFileName, objDiv);

    var body_xml = '<req:listServiceModulesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:serviceName>' + getServiceSpecificName() + '</req:serviceName>\n' +
                   ' </req:listServiceModulesRequest>\n';

    var callURL = serverURL + "/" + "ModuleAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL, "listServiceModules", body_xml, engageModullePerOperationComboCallback);
}

function engageModullePerOperationComboCallback() {

    var xsltFileName = "list_engaged_modules_per_operation.xsl";
    var objDiv = document.getElementById("modulesPerService");
    var data = this.req.responseXML;
    wso2.wsf.Util.processXML(data, xsltFileName, objDiv);

    getGlobalModuleCombo(document.getElementById("engageModulePerOperationCombo"), "cmbEngageModulePerOperationCombo");
}

function getGlobalModuleCombo(cmbSpan, cmbName) {
    moduleSpanToUse = cmbSpan;
    moduleComboName = cmbName;
    //    alert("Global module getting function called");

    var body_xml = '<ns1:listModules  xmlns:ns1="http://org.apache.axis2/xsd"/>\n';

    var callURL = serverURL + "/" + MODULE_ADMIN_STRING + "/" + "listModules";
    new wso2.wsf.WSRequest(callURL, "listModules", body_xml, getGlobalModuleComboCallback);

}

function getGlobalModuleComboCallback() {

    var data = this.req.responseXML;

    //    alert("XSL = " + (new XMLSerializer()).serializeToString(data));

    var strHTML = "<select id='" + moduleComboName + "'>";
    var rets = data.getElementsByTagName("return");
    var len = rets.length;
    var count;
    var moduleVersion;
    for (count = 0; count < len; count++) {
        if (rets[count].getElementsByTagName("moduleVersion")[0].firstChild != null) {
            moduleVersion =
            rets[count].getElementsByTagName("moduleVersion")[0].firstChild.nodeValue;
        } else {
            moduleVersion = "";
        }
        displayModuleVersion = (moduleVersion == "" ? "":("-" + moduleVersion));
        strHTML += "<option value='" +
                   rets[count].getElementsByTagName("moduleId")[0].firstChild.nodeValue + '||' +
                   moduleVersion + "'>" +
                   rets[count].getElementsByTagName("modulename")[0].firstChild.nodeValue +
                   displayModuleVersion + "</option>\n";
    }
    strHTML += "</select>"
    moduleSpanToUse.innerHTML = strHTML;

    //globally engage

    body_xml = '<req:listGloballyEngagesModulesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
               ' </req:listGloballyEngagesModulesRequest>\n';

    callURL = serverURL + "/" + "ModuleAdmin" + "/";
    new wso2.wsf.WSRequest(callURL, "listGloballyEngagesModules", body_xml, listGloballyEngageModulesCallback);

}

function listGloballyEngageModulesCallback() {

    var xsltFileName = "list_engaged_modules_per_service.xsl";
    var objDiv = document.getElementById("globleModules");
    var data = this.req.responseXML;
    wso2.wsf.Util.processXML(data, xsltFileName, objDiv);

    //Operation's Parent's Parent module Listing

    var body_xml = '<req:listOperationsParentParentEngagedModulesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<serviceName>' + getServiceSpecificName() + '</serviceName>\n' +
                   '<operationName>' + lastOperationUsed + '</operationName>\n' +
                   '</req:listOperationsParentParentEngagedModulesRequest>\n';

    callURL = serverURL + "/" + "ModuleAdmin" + "/";
    new wso2.wsf.WSRequest(callURL, "listOperationsParentParentEngagedModules", body_xml, listOperationsParentParentEngagedModulesCallback);


}

function listOperationsParentParentEngagedModulesCallback() {

    var xsltFileName = "list_engaged_modules_per_service.xsl";
    var objDiv = document.getElementById("modulesPerServiceParentEngagedModules");
    var data = this.req.responseXML;
    wso2.wsf.Util.processXML(data, xsltFileName, objDiv);


}

function engageModulePerOperationExec(operationName, moduleName) {
    var moduleVersion = moduleName.substring(moduleName.indexOf('||') + 2, moduleName.length);
    moduleName = moduleName.substring(0, moduleName.indexOf('||'));
    setOperationName = operationName;

    var body_xml = '<req:engageModuleForOperationRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:moduleId>' + moduleName + '</req:moduleId>\n' +
                   ' <req:moduleVersion>' + moduleVersion + '</req:moduleVersion>\n' +
                   ' <req:serviceId>' + getServiceSpecificName() + '</req:serviceId>\n' +
                   ' <req:serviceVersion></req:serviceVersion>\n' +
                   ' <req:operationId>' + operationName + '</req:operationId>\n' +
                   ' </req:engageModuleForOperationRequest>\n';

    var callURL = serverURL + "/" + "ModuleAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"engageModuleForOperation",body_xml,engageModulePerOperationCallBack);


}
function engageModulePerOperationCallBack() {

    var data = this.req.responseXML;
    var text = data.getElementsByTagName('return')[0];

    wso2.wsf.Util.alertMessage(text.firstChild.nodeValue);

    engageModulePerOperation(lastOperationUsed);
}

// disengaging modules from operation
function disengageModuelfromOperationExec(moduleName, moduleVersion) {
    var body_xml = '<req:disengageModuleFromOperationRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:moduleId>' + moduleName + '</req:moduleId>\n' +
                   ' <req:moduleVersion>' + moduleVersion + '</req:moduleVersion>\n' +
                   ' <req:serviceId>' + getServiceSpecificName() + '</req:serviceId>\n' +
                   ' <req:serviceVersion></req:serviceVersion>\n' +
                   ' <req:operationId>' + lastOperationUsed + '</req:operationId>\n' +
                   ' </req:disengageModuleFromOperationRequest>\n';

    var callURL = serverURL + "/" + "ModuleAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"disengageModuleFromOperation",body_xml,disengageModuleFromOperationCallBack);
}

function disengageModuleFromOperationCallBack() {

    wso2.wsf.Util.alertMessage("Module was disengaged from operation successfully.");
    engageModulePerOperation(lastOperationUsed);
}

// disengaging modules from operation
function disengageModuelfromServiceExec(moduleName, moduleVersion) {
    // gettting all the values from engageModulePerOperationExec
    var body_xml = '<req:disengageModuleFromService xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:moduleId>' + moduleName + '</req:moduleId>\n' +
                   ' <req:moduleVersion>' + moduleVersion + '</req:moduleVersion>\n' +
                   ' <req:serviceId>' + getServiceSpecificName() + '</req:serviceId>\n' +
                   ' <req:serviceVersion></req:serviceVersion>\n' +
                   ' </req:disengageModuleFromService>\n';

    var callURL = serverURL + "/" + "ModuleAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"disengageModuleFromService",body_xml,disengageModuelfromServiceCallBack);
}

function disengageModuelfromServiceCallBack() {

    wso2.wsf.Util.alertMessage("Module was disengaged from service successfully.");
    setTimeout(function() {
        engageModulePerService(getServiceSpecificName());
    }, 1000);
    //    engageModulePerService(getServiceSpecificName());

}
function addServiceSpecificParameters() {
    var newParam = wso2.wsf.Util.getUserInput();
    if (newParam != null) {
        processServiceOperationParameterConfigEntry(
                lastUsedServiceId,
                serviceSpecificName,
                newParam[0],
                newParam[1], getServiceSpecficParametersForConfig);
    }
 }

function removeServiceSpecificParameter(button) {
    processServiceOperationParameterConfigEntryRemoval(
            lastUsedServiceId,
            serviceSpecificName,
            button.id, getServiceSpecficParametersForConfig);
}

function removeEJBServiceSpecificParameter(button) {
    processServiceOperationParameterConfigEntryRemoval(
            lastUsedServiceId,
            serviceSpecificName,
            button.id.substring(3), getServiceSpecficParametersForConfig);
}

//remove a single operation parameter entry
function processServiceOperationParameterConfigEntryRemoval(
        serviceId,
        serviceVersion,
        parameterName, service_callback) {

    if (!parseParameterName(parameterName)) {
        wso2.wsf.Util.alertMessage("Parameter name contains an invalid character");
        return false;
    }


    var body_xml = '<ns1:removeServiceSpecificParameterRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:serviceId>' + serviceId + '</ns1:serviceId>' +
                   '<ns1:serviceVersion>' + serviceId + '</ns1:serviceVersion>' +
                   '<parameter locked="false" name="' + parameterName + '"></parameter>' +
                   '</ns1:removeServiceSpecificParameterRequest>';

    var callURL = serverURL + "/" + "ServiceAdmin";
    //update the information in operation display page
    new wso2.wsf.WSRequest(callURL,"removeServiceSpecificParameter",body_xml,service_callback);
}
//end of  processSingleOperationParameterConfigEntry

function processMultipleServiceOperationParameterConfigEntry(serviceId,
                                                             parameterNamesObj,
                                                             parameterValueObj) {
    var paramElements = '';
    for (var i = 0; i < parameterNamesObj.length; i++) {
        paramElements += '<parameter locked="false" name="' + parameterNamesObj[i] + '"><![CDATA[' +
                         parameterValueObj[i] + ']]></parameter>\n';
    }
    var body_xml = '<ns1:setServiceParameters xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:serviceId>' + serviceId + '</ns1:serviceId>' +
                   '<ns1:serviceVersion>' + serviceId + '</ns1:serviceVersion>' +
                   paramElements +
                   '</ns1:setServiceParameters>';

    var callURL = serverURL + "/" + "ServiceAdmin";

    new wso2.wsf.WSRequest(callURL,"setServiceParameters",body_xml,processMultipleServiceOperationParameterConfigEntryCallback);


}

function processMultipleServiceOperationParameterConfigEntryEJB(serviceId,
                                                             parameterNamesObj,
                                                             parameterValueObj) {
    var paramElements = '';
    for (var i = 0; i < parameterNamesObj.length; i++) {
        paramElements += '<parameter locked="false" name="' + parameterNamesObj[i] + '"><![CDATA[' +
                         parameterValueObj[i] + ']]></parameter>\n';
    }
    var body_xml = '<ns1:setServiceParameters xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:serviceId>' + serviceId + '</ns1:serviceId>' +
                   '<ns1:serviceVersion>' + serviceId + '</ns1:serviceVersion>' +
                   paramElements +
                   '</ns1:setServiceParameters>';

    var callURL = serverURL + "/" + "ServiceAdmin";

    new wso2.wsf.WSRequest(callURL,"setServiceParameters",body_xml,processMultipleServiceOperationParameterConfigEntryEJBCallback);


}

function processMultipleServiceOperationParameterConfigEntryCallback() {

    wso2.wsf.Util.alertMessage("Service parameters were successfully updated.");
    getServiceSpecficParametersForConfig(lastUsedServiceId);

}

function processMultipleServiceOperationParameterConfigEntryEJBCallback() {

    wso2.wsf.Util.alertMessage("Service parameters were successfully updated.");
	getServiceSpecficParametersForConfig(lastUsedServiceId, 'ejb_service');

}

//add a single operation parameter entry
function processServiceOperationParameterConfigEntry(
        serviceId,
        serviceVersion,
        parameterName,
        parameterValue, service_callback) {

    if (!parseParameterName(parameterName)) {
        wso2.wsf.Util.alertMessage("Parameter name contains an invalid character");
        return false;
    }


    var body_xml = '<ns1:setServiceParameterRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<ns1:serviceId>' + serviceId + '</ns1:serviceId>' +
                   '<ns1:serviceVersion>' + serviceId + '</ns1:serviceVersion>' +
                   '<parameter locked="false" name="' + parameterName + '"><![CDATA[' +
                   parameterValue + ']]></parameter>' +
                   '</ns1:setServiceParameterRequest>';

    var callURL = serverURL + "/" + "ServiceAdmin";
    //update the information in operation display page
    new wso2.wsf.WSRequest(callURL,"setServiceParameter",body_xml,service_callback);
}
//end of  processSingleOperationParameterConfigEntry

//display the messages for the modules
function updateServiceInfoDisplay(message) {
    document.getElementById('serviceConfigUpdate').innerHTML = message;
}

function processOperationParameterConfigUpdate(arrayOfNames, arrayOfValues) {

    processMultipleOperationParameterConfigEntry(lastUsedServiceId, serviceOperationParameters, arrayOfNames, arrayOfValues);

}
function processServiceOperationParameterConfigUpdate(arrayOfNames, arrayOfValues) {
	processMultipleServiceOperationParameterConfigEntry(lastUsedServiceId, arrayOfNames, arrayOfValues);
}

function processServiceOperationParameterConfigUpdateEJB(arrayOfNames, arrayOfValues) {
	processMultipleServiceOperationParameterConfigEntryEJB(lastUsedServiceId, arrayOfNames, arrayOfValues);
}

function completeServiceFileUpload(msg) {
    wso2.wsf.Util.cursorWait();
    if (msg) {
        showAARGenerationCompleteMsg(msg);
    } else {
        showAARGenerationCompleteMsg("Archive was successfully uploaded.\n" +
                                     "This page will be auto refreshed shortly.");
    }
}

function serviceParameters(serviceId, serviceVersion) {
    lastUsedServiceId = serviceId;
    lastUsedServiceVersion = serviceVersion;

    var body_xml = '<req:getServiceParametersRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:serviceId>' + serviceId + '</req:serviceId>\n' +
                   ' <req:serviceVersion>' + serviceVersion + '</req:serviceVersion>\n' +
                   ' </req:getServiceParametersRequest>\n';


    var callURL = serverURL + "/" + "ServiceAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"getServiceParameters",function() {
        wso2.wsf.Util.callbackhelper(this.req.responseXML,"list_service_param.xsl",document.getElementById("divServiceParameters"));
    });

}

//faulty services

function listFaultyArchives() {
    var body_xml = '<req:getFaultyServiceArchivesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' </req:getFaultyServiceArchivesRequest>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" ;
    new wso2.wsf.WSRequest(callURL,"getFaultyServiceArchives",body_xml,function(){
        wso2.wsf.Util.callbackhelper(this.req.responseXML,"service_faults.xsl",document.getElementById("divFaultyServices"));
    });


}

function deleteFaultyService(faultServicePath) {
    var delete_to = confirm("Do you really want to Delete this Faulty Service ?");
    if (delete_to == true) {
        var body_xml = '<req:deleteFaultyServiceArchiveRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                       ' <req:archiveName>' + faultServicePath + '</req:archiveName>\n' +
                       ' </req:deleteFaultyServiceArchiveRequest>\n';

        var callURL = serverURL + "/" + "ServiceAdmin" ;
        new wso2.wsf.WSRequest(callURL,"deleteFaultyServiceArchive",body_xml,deleteFaultyServiceCallback);
    } else {
        //        alertMessage("Aborted Deletion.")
        return false;
    }

}

function deleteFaultyServiceCallback() {

    wso2.wsf.Util.cursorWait();
    setTimeout("showAARGenerationCompleteMsg('The Faulty Service has been successfully deleted')",
            1000);
}


// Stub generation
function getClassListFromArchive(archiveId) {
    genFileKey = archiveId;

    var dynamicServiceObj = document.getElementById('divDynamicService');
    wso2.wsf.Util.showOnlyOneMain(dynamicServiceObj);

    var body_xml = '<req:getClassNamesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:archiveId>' + genFileKey + '</req:archiveId>\n' +
                   ' </req:getClassNamesRequest>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" ;
    new wso2.wsf.WSRequest(callURL, "getClassNames", body_xml, function() {
        var xslAbsPath = URL + "/extensions/core/xslt/class_selection_wizard.xsl";
        wso2.wsf.Util.callbackhelper(this.req.responseXML, xslAbsPath, document.getElementById("divDynamicService"), false, true);
    });
}

function generateAARSelectClasses() {
    var classes = document.getElementsByName("chkClasses");
    var arrayString = '';
    var isClassSelected = false;
    for (var i = 0; i < classes.length; i++) {
        if (classes[i].checked) {
            isClassSelected = true;
            arrayString += ' <req:serviceClasses>' + classes[i].value + '</req:serviceClasses>\n';
        }
    }
    if (!isClassSelected) {
        wso2.wsf.Util.alertWarning("Please select at least one service class");
        return;
    }

    var body_xml = '<req:createAndDeployServiceRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<req:archiveId>' + genFileKey + '</req:archiveId>\n' +
                   arrayString +
                   '</req:createAndDeployServiceRequest>\n';

    //    alert(body_xml);
    var callURL = serverURL + "/" + "ServiceAdmin" ;
    new wso2.wsf.WSRequest(callURL,"createAndDeployService",body_xml,completeAARGenerationCB);
}

function completeAARGenerationCB() {
    wso2.wsf.Util.cursorWait();
    showAARGenerationCompleteMsg("Service configurtaion was successfully uploaded.\n" +
                                 "This page will be auto refreshed shortly.");
}


function selectAll(checkboxes, select) {
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = select;
    }
}

function dynamicClientGeneration() {

    /*var body_xml =  '<req:generateAjaxClient xmlns:req="http://services.codegen.wsas.wso2.org">\n' +
             '<serviceName>' + getServiceSpecificName() + '</serviceName>\n' +
             '</req:generateAjaxClient>\n';

var callURL = serverURL + "/" + "AjaxClientGeneratorService" ;
cursorWait();
send("generateAjaxClient", body_xml, "", callURL, "", false, dynamicClientGenerationCallBack);*/

    /*stopping the refreshing first */
    stoppingRefreshingMethodsHook();

    var body_xml = '<req:generate xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<serviceName>' + getServiceSpecificName() + '</serviceName>\n' +
                   '</req:generate>\n';

    var callURL = serverURL + "/" + "DynamicCodeGeneratorService" ;
    wso2.wsf.Util.cursorWait();
    new wso2.wsf.WSRequest(callURL,"generate",body_xml,dynamicClientGenerationCallBack);
}

function dynamicClientGenerationCallBack() {

    //response will be a link and it will call the download dialog
    var data = this.req.responseXML;

    var rets = data.getElementsByTagName("return");

    //    alert('return value' + rets[0].firstChild.nodeValue);
    //    dynamicClientResponseVisibility(URL + rets[0].firstChild.nodeValue);
    //    window.location = URL + rets[0].firstChild.nodeValue;
    wso2.wsf.Util.cursorClear();

    dynamicClientResponseVisibilityAllBrowsers(data);
}


function dynamicClientGenerationMetaInfo() {
    var xsltFileName = "";
    var body_xml = '<req:listServicesAndPortsRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<req:serviceName>' + getServiceSpecificName() + '</req:serviceName>\n' +
                   ' </req:listServicesAndPortsRequest>\n';

    var callURL = serverURL + "/" + "WSDLInfoService" + "/" ;
    new wso2.wsf.WSRequest(callURL,"listServicesAndPorts",body_xml,dynamicClientGenerationMetaInfoCallback);

}

function dynamicClientGenerationMetaInfoCallback() {

    wso2.wsf.Util.callbackhelper(this.req.responseXML,"dynamic_client_meta_info.xsl", document.getElementById("divDynamicClientGeneration"));
    showdynamicClientMetaInfo(document.getElementById('dynamicClientMetaInfo'));
}


function dynamicClientResponseVisibility(url) {
    var objDiv = document.getElementById("divDynamicClientResponse");
    var headerElement = "<h3><a href='#' onClick='javascript:showServiceInitializer(); return false;'>Services</a>&nbsp;&gt;&nbsp;<a href='#' onClick='javascript:listServiceData(\"" +
                        getServiceSpecificName() + "\"); return false;'>" +
                        getServiceSpecificName() + "</a>" + "&nbsp;&gt;&nbsp;Dynamic Client" +
                        "</h3>";
    var dynamicClientInnerFrame = "<div style=\"height:600px;position:relative;\"><form>" +
                                  "<iframe id=\"divDynamicClientResponseInnerFrame\" frameborder=\"0\"  style=\"width:70%;height:100%;position:absolute;\" scrolling=\"auto\"></iframe>" +
                                  "</div>";
    var temp = "<p/>";
    objDiv.innerHTML = headerElement + dynamicClientInnerFrame + temp;
    document.getElementById("divDynamicClientResponseInnerFrame").src = url;

    wso2.wsf.Util.showOnlyOneMain(objDiv);
}


function dynamicClientResponseVisibilityAllBrowsers(data) {

    var xsltFileName = "try_it.xsl";
    var objDiv = document.getElementById('divTryit');
    wso2.wsf.Util.processXML(data, xsltFileName, objDiv);
    wso2.wsf.Util.showOnlyOneMain(objDiv);

}

function wsdlForDynamicClient() {
    window.open("/" + SERVICE_PATH + '/' + getServiceSpecificName() + '?wsdl');
}

function readOnlyServices(thisObj, index) {
    if (thisObj && index) {
        renderSelectedMenuItem(thisObj, index);
        gatherHistoryObject(thisObj.id, index);
    }
    var body_xml = '<ns1:listServiceGroups  xmlns:ns1="http://org.apache.axis2/xsd">\n' +
                   ' </ns1:listServiceGroups>\n';

    var relCallURL = wso2.wsf.Util.getServerURL() + "/GeneralServices";
    new wso2.wsf.WSRequest(relCallURL, "urn:listServiceGroups", body_xml, readOnlyServicesCallback);


}

function readOnlyServicesCallback() {
    var divObject = document.getElementById("divServicesGeneral");
    var xsltHelperObj = new wso2.wsf.XSLTHelper();
    var relXslPath = "extensions/core/xslt/list_general_services.xsl";
    xsltHelperObj.transform(divObject, this.req.responseXML, relXslPath, true, false, [["resourceHTTPEPR",HTTP_URL + "/"]]);
    wso2.wsf.Util.showOnlyOneMain(divObject);

}


function startServices(thisObj, index) {

    if (thisObj && index) {
        renderSelectedMenuItem(thisObj, index);
        gatherHistoryObject(thisObj.id, index);
    }

    showServiceInitializer();
}

function showServiceInitializer() {

    var tmpTransformationNode;

    /* The checking for the existance for window.XMLHttpRequest to figure out the browser
     and the functionality was dropped since the new version of IE has this object. */
    if (wso2.wsf.Util.isIE()) {
        tmpTransformationNode = new ActiveXObject("Microsoft.XmlDom");
        var sXml = "<initializeService></initializeService>";
        tmpTransformationNode.loadXML(sXml);
    } else {
        tmpTransformationNode =
        document.implementation.createDocument("", "initializeService", null);
    }

    var jv ="1.5";
    if (javaVersion.indexOf("1.4") > -1) {
        jv = "1.4";
    }
    var divObject = document.getElementById("divListServiceGroups");
    var xsltHelperObj = new wso2.wsf.XSLTHelper();
    xsltHelperObj.transform(divObject, tmpTransformationNode, "list_services.xsl", false, false, [["conditionalJavaversion",jv],["javaVersion",javaVersion]]);
    wso2.wsf.Util.showOnlyOneMain(document.getElementById("divListServiceGroups"));


    listServiceGroups();
    if (listServiceGroupsRequestInterval == 0) {
        listServiceGroupsRequestInterval = setInterval('listServiceGroups()', SERVICE_REFRESH_TIME);
    }
}

function openWindowHTTP(value) {
    window.open(HTTP_URL + "/" + value);
}


function getExposedTransports(serviceId) {

    /*stopping the refreshing first */
    stoppingRefreshingMethodsHook();

    var body_xml = '<req:getExposedTransportsRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<serviceId>' + serviceId + '</serviceId>\n' +
                   '</req:getExposedTransportsRequest>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" ;
    new wso2.wsf.WSRequest(callURL,"getExposedTransports",body_xml,getExposedTransportsCallback);

}

function getExposedTransportsCallback() {

    //        alert("Response" + (new XMLSerializer()).serializeToString(getBody(xhReq.responseXML)));
    wso2.wsf.Util.callbackhelper(this.req.responseXML,"list_transport.xsl", document.getElementById("divListTransports"));

    // breadcrumbs setting
    showListTransportDiv(document.getElementById('breadcumbsgetExposedTransportsHeader'));

    listSystemTransports();

}

function listSystemTransports() {

    var body_xml = '<req:listTransportsRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '</req:listTransportsRequest>\n';

    var callURL = serverURL + "/" + "TransportAdmin" ;
    new wso2.wsf.WSRequest(callURL,"listTransports",body_xml,listSystemTransportsCallback);

}

function listSystemTransportsCallback() {
    //    alert("Response" + (new XMLSerializer()).serializeToString(getBody(xhReq.responseXML)));

    var txSelectionCombo = document.getElementById('transportSelectionCombo');

    var data = this.req.responseXML;

    var protocols = data.getElementsByTagName('protocol');

    for (var i = 0; i < protocols.length; i++) {
        txSelectionCombo.options[i] = new
        Option(protocols[i].firstChild.nodeValue);
        txSelectionCombo.options[i].value = protocols[i].firstChild.nodeValue;
    }

}

function addNewTransportForService(obj) {
    //selecting the value from combo
    var protocol = obj[obj.selectedIndex].value;

    var body_xml = '<req:exposeServiceViaTransportRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<serviceId>' + getServiceSpecificName() + '</serviceId>\n' +
                   '<transportProtocol>' + protocol + '</transportProtocol>\n' +
                   '</req:exposeServiceViaTransportRequest>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" ;
    new wso2.wsf.WSRequest(callURL,"addTransportBinding",body_xml,addNewTransportForServiceCallback);
}

function addNewTransportForServiceCallback() {

    wso2.wsf.Util.showResponseMessage(this.req.responseXML);
    getExposedTransports(getServiceSpecificName());
}

function removeTransportBinding(protocol) {

    var conf = confirm("Do you want to remove the " + protocol +
                       " transport binding for this service?");
    if (!conf) {
        return true;
    }
    var body_xml = '<req:removeTransportBindingRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<serviceId>' + getServiceSpecificName() + '</serviceId>\n' +
                   '<transportProtocol>' + protocol + '</transportProtocol>\n' +
                   '</req:removeTransportBindingRequest>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" ;
    new wso2.wsf.WSRequest(callURL,"removeTransportBinding",body_xml,removeTransportBindingCallback);
}

function removeTransportBindingCallback() {

    wso2.wsf.Util.showResponseMessage(this.req.responseXML);
    getExposedTransports(getServiceSpecificName());
}

function openExtraWindowHTTPForWebResources(firstValue, lastValue) {

    /*stopping the refreshing first */
    stoppingRefreshingMethodsHook();

    window.open(URL + '/' + firstValue + "/" + lastValue);
}

var SPRING_BEANS_UUID;
var SPRING_CONTEXT_UUID;
function getSpringBeansFromArchive(springBeansUUID, springContextUUID) {
    SPRING_BEANS_UUID = springBeansUUID;
    SPRING_CONTEXT_UUID = springContextUUID;
    var body_xml = '<req:getSpringBeanNames xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<springContextId>' + springContextUUID + '</springContextId>\n' +
                   '<springBeanId>' + springBeansUUID + '</springBeanId>\n' +
                   '</req:getSpringBeanNames>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" ;
    new wso2.wsf.WSRequest(callURL,"getSpringBeanNames",body_xml,getSpringBeansFromArchiveCallback);

}

function getSpringBeansFromArchiveCallback() {
    var xslAbsPath = URL + "/extensions/core/xslt/spring_beans_selection_wizard.xsl";
    wso2.wsf.Util.callbackhelper(this.req.responseXML,xslAbsPath, document.getElementById("divBeanGenerationWizard"),false,true);
}

function generateBeansForAARSelectClasses(uuid) {
    var classes = document.getElementsByName("chkBeans");
    var arrayString = '';
    var isClassSelected = false;
    for (var i = 0; i < classes.length; i++) {
        if (classes[i].checked) {
            isClassSelected = true;
            arrayString += ' <beanClasses>' + classes[i].value + '</beanClasses>\n';
        }
    }
    if (!isClassSelected) {
        wso2.wsf.Util.alertWarning("Please select at least one Spring bean");
        return;
    }

    var body_xml = '<req:createAndDeploySpringBean xmlns:req="http://org.apache.axis2/xsd">\n' +
                   '<springContextId>' + uuid + '</springContextId>\n' +
                   '<springBeanId>' + SPRING_BEANS_UUID + '</springBeanId>\n' +
                   arrayString +
                   '</req:createAndDeploySpringBean>\n';

    //    alert(body_xml);
    var callURL = serverURL + "/" + "ServiceAdmin" ;
    new wso2.wsf.WSRequest(callURL,"createAndDeploySpringBean",body_xml,completeAARGenerationCB);
}

function codegenUnwrappingSelectorHelper(obj) {
    var uwSelect = document.getElementById('unwrap');
    uwSelect.options.length = 0;
    var selection = obj.options[obj.selectedIndex].value;
    if (selection == "none" || selection == "xmlbeans") {
        uwSelect.options[0] = new Option('False','false');
    } else {
        uwSelect.options[0] = new Option('False','false');
        uwSelect.options[1] = new Option('True','true');
    }
}

function getEJBRemoteInterfaceClassListFromArchive(archiveId) {
    genFileKey = archiveId;

    var dynamicServiceObj = document.getElementById('divDynamicService');
    wso2.wsf.Util.showOnlyOneMain(dynamicServiceObj);

    var body_xml = '<req:getClassNamesRequest xmlns:req="http://org.apache.axis2/xsd">\n' +
                   ' <req:archiveId>' + genFileKey + '</req:archiveId>\n' +
                   ' </req:getClassNamesRequest>\n';

    var callURL = serverURL + "/" + "ServiceAdmin" ;
    new wso2.wsf.WSRequest(callURL, "getClassNames", body_xml, function() {
        var xslAbsPath = URL + "/extensions/core/xslt/ejb_provider_wizard_step2.xsl";
        wso2.wsf.Util.callbackhelper(this.req.responseXML, xslAbsPath, document.getElementById("divDynamicService"), false, true);

    });
}

//functions to call different type of service creation screens
/**
 * @param xslFileName name of the xsl file.
 */
function showPOJOArchieveUploadScreen(xslFileName) {
    var tmpTransformationNode;
    if (window.XMLHttpRequest && !wso2.wsf.Util.isIE()) {
        tmpTransformationNode =
        document.implementation.createDocument("", "serviceUploadTemplate", null);
    } else if (window.ActiveXObject) {
        tmpTransformationNode = new ActiveXObject("Microsoft.XmlDom");
        var sXml = "<serviceUploadTemplate></serviceUploadTemplate>";
        tmpTransformationNode.loadXML(sXml);
    }
    var objDiv = document.getElementById("divNewPOJOService");
    wso2.wsf.Util.processXML(tmpTransformationNode, xslFileName, objDiv);
    wso2.wsf.Util.showOnlyOneMain(objDiv);
}


function showSpringArchieveUploadScreen() {
    var tmpTransformationNode;
    if (window.XMLHttpRequest && !wso2.wsf.Util.isIE()) {
        tmpTransformationNode =
        document.implementation.createDocument("", "springServiceUploadTemplate", null);
    } else if (window.ActiveXObject) {
        tmpTransformationNode = new ActiveXObject("Microsoft.XmlDom");
        var sXml = "<springServiceUploadTemplate></springServiceUploadTemplate>";
        tmpTransformationNode.loadXML(sXml);
    }
    var objDiv = document.getElementById("divNewSpringService");
    wso2.wsf.Util.processXML(tmpTransformationNode, "add_new_spring_service.xsl", objDiv);
    wso2.wsf.Util.showOnlyOneMain(objDiv);
}

function sortOperationsByName() {
	var table = document.getElementById("published_operations_table");
	var tBody = document.getElementById("published_operations_table_body");
	var rows = tBody.childNodes;
	for(var index = 0; index < row.length; index ++) {
			
	}
}

/**
 * This method will be used, when wsdd need to upload to create an Axis1 service ontop of Axis2
 * environment.
 */
function showAxis1WSDDUploadScreen() {
    var tmpTransformationNode;
    if (window.XMLHttpRequest && !wso2.wsf.Util.isIE()) {
        tmpTransformationNode =
        document.implementation.createDocument("", "wsddUploadTemplate", null);
    } else if (window.ActiveXObject) {
        tmpTransformationNode = new ActiveXObject("Microsoft.XmlDom");
        var sXml = "<wsddUploadTemplate></wsddUploadTemplate>";
        tmpTransformationNode.loadXML(sXml);
    }
    var objDiv = document.getElementById("divNewAxis1Service");
    wso2.wsf.Util.processXML(tmpTransformationNode, "add_new_axis1_service.xsl", objDiv);
    wso2.wsf.Util.showOnlyOneMain(objDiv);

}

/**
 * This method will dynamically add a file uplod input element to the given objDiv.
 * @param objDiv
 */
function addLibraryFileuplod(objDiv) {
    var blankLabelElem = document.createElement('label');
    blankLabelElem.innerHTML = "&nbsp;";
    var elem = document.createElement('input');
    var brElem = document.createElement('br');
    var nameAttr = document.createAttribute('name');
    nameAttr.value = "jarResource";
    var sizeAttr = document.createAttribute('size');
    sizeAttr.value = "50";
    var typeAttr = document.createAttribute('type');
    typeAttr.value = "file";
    elem.attributes.setNamedItem(nameAttr);
    elem.attributes.setNamedItem(sizeAttr);
    elem.attributes.setNamedItem(typeAttr);
    objDiv.appendChild(brElem);
    objDiv.appendChild(blankLabelElem);
    objDiv.appendChild(elem);
}
