// This will have all the functionality for data services.

var dataServiceObj = null;

var dataServiceQueryObj = null;

var curDataServiceName = null;

var dataServiceCurOpObj = null;

var curDataServiceOutputMappingType = null;

var newDataService = false;
var rootDocument;
var xslToReload;

var ds_collectdata = new Array();

var serviceSpecificName = null;

var newDataObject;

function addNewDataService() {
    newDataService = true;
    var browser = wso2.wsf.Util.getBrowser();
    //var newDataObject;

    switch (browser) {
        case "ie":
        case "ie7": {
            rootDocument = new ActiveXObject("Microsoft.XMLDOM");
            rootDocument.async = false;
            rootDocument.loadXML("<foo><return></return></foo>");
            newDataObject = rootDocument.getElementsByTagName("return")[0];
            break;
        }
        case "gecko":
        case "opera":
        case "safari": {
            rootDocument = document.implementation.createDocument("", "", null);
            newDataObject = rootDocument.createElement("return");
            break;
        }
        default: {
            wso2.wsf.Util.alertWarning("DOM document can not be created");
            return;
        }
    }

    var dataRowObj = rootDocument.createElement("data");

    var configObj = rootDocument.createElement("config");
    //configObj.appendChild(createPropelement("org.wso2.ws.dataservice.driver", ""));
    //configObj.appendChild(createPropelement("org.wso2.ws.dataservice.protocol", ""));
    //configObj.appendChild(createPropelement("org.wso2.ws.dataservice.user", ""));
    //configObj.appendChild(createPropelement("org.wso2.ws.dataservice.password", ""));

    dataRowObj.appendChild(configObj);

    newDataObject.appendChild(dataRowObj);

    var tempDataServiceObj = rootDocument.createElement("temp");
    tempDataServiceObj.appendChild(newDataObject);
    xslToReload = "data_service.xsl";
    serviceSpecificName = null;
    addNewDataServiceEchoDataElement(tempDataServiceObj);
}

// todo: do we realy need to do this, we can skip this - ruwan
function addNewDataServiceEchoDataElement(tempDataServiceObj) {
	var dataServiceContents = prettyPrintDOMNode(tempDataServiceObj.getElementsByTagName("data").item(0), "", "    ", true);
	    var body_xml = '<req:echoDataElement xmlns:req="http://org.apache.axis2/xsd">\n' +
				   		' <arg0><![CDATA[' + dataServiceContents +']]></arg0>\n' +
                   ' </req:echoDataElement>\n';

    var callURL = serverURL + "/" + "DataServiceAdmin" + "/echoDataElement" ;

    new wso2.wsf.WSRequest(callURL,"echoDataElement",body_xml,addNewDataServiceEchoDataElementCallback);
}

function addNewDataServiceEchoDataElementCallback(){

    dataServiceObj = this.req.responseXML.getElementsByTagName("return").item(0);
    dataServiceObj.setAttribute("ds_step", 0);
    newDataService = true;
	//refreshDataServiceScreen.call(this,true);
	refreshDataServiceScreen.call(this,false);
}


function configureDataservice(serviceName){
	curDataServiceName = serviceName;
	newDataService = false;

    var browser = wso2.wsf.Util.getBrowser();

    switch (browser) {
        case "ie":
        case "ie7": {
            rootDocument = new ActiveXObject("Microsoft.XMLDOM");
            rootDocument.async = false;
            rootDocument.loadXML("<foo><return></return></foo>");
            break;
        }
        case "gecko":
        case "opera":
        case "safari": {
            rootDocument = document.implementation.createDocument("", "", null);
            break;
        }
        default: {
            wso2.wsf.Util.alertWarning("DOM document can not be created");
            return;
        }
    }

    getDataServiceContents(serviceName);
}

function getDataServiceContents(serviceName) {

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

    var callURL = serverURL + "/" + "DataServiceAdmin" + "/getDataServiceContents" ;

    new wso2.wsf.WSRequest(callURL,"getAxisConfigData",body_xml,getDataServiceContentsCallback);
}

function getDataServiceContentsCallback(){

    dataServiceObj = this.req.responseXML.getElementsByTagName("return").item(0);
    dataServiceObj.setAttribute("ds_step", 0);
    dataServiceObj.setAttribute("disable_name", true);
    xslToReload = "data_service.xsl";
    serviceSpecificName
                = this.req.responseXML.getElementsByTagName("data")[0].getAttribute("name");
    refreshDataServiceScreen.call(this);

}

function refreshDataServiceScreen(boolValue) {

    wso2.wsf.Util.callbackhelper(dataServiceObj,
            "data_service.xsl", document.getElementById("divDataServiceDetails"));
    if (boolValue) {
        loadDatabaseUrlDriverComboBox();
    }


    _refreshDataServiceScreenHelper(boolValue);
}

function _refreshDataServiceScreenHelper(boolValue) {
    if (serviceSpecificName == null || serviceSpecificName == "") {
        showNewDataServiceHeader(document.getElementById('dataServiceHeader'), dataServiceObj.getAttribute("ds_step"));
    } else {
        showDataServiceHeader(document.getElementById('dataServiceHeader'), dataServiceObj.getAttribute("ds_step"));
    }
    
    if (dataServiceObj.getAttribute("ds_step") == "0") {
        //addNewConfigParameter();
    } else if (dataServiceObj.getAttribute("ds_step") == "1") {
        addDataServiceQuery();
    } else if (dataServiceObj.getAttribute("ds_step") == "2") {
        displayAddDataServiceOperation();
        displayOperationWithParams();
    }
    
    if (!boolValue) {
    document.getElementById("dsPreviewDiv").appendChild(document.createTextNode(
            prettyPrintDOMNode(dataServiceObj.getElementsByTagName("data").item(0), "", "    ", true)));
            }

}

function addEditDataServiceQueryDone(){
	var dataServiceSQL = document.getElementById('txtDataServiceSQL').value;
	var dataServiceWrapElement = document.getElementById('txtDataServiceWrapElement').value;
	var dataServiceRowName = document.getElementById('txtDataServiceRowName').value;

	var sqlObj = dataServiceQueryObj.getElementsByTagName("sql").item(0);
	sqlObj.removeChild(sqlObj.childNodes.item(0));
	sqlObj.appendChild(rootDocument.createTextNode(dataServiceSQL));

	var resultObj = dataServiceQueryObj.getElementsByTagName("result").item(0);
	resultObj.setAttribute("element", dataServiceWrapElement);
	resultObj.setAttribute("rowName", dataServiceRowName);


    // TODO fill this; get the info from server
	xslToReload = 'data_service.xsl';
	addNewDataServiceEchoDataElement(dataServiceObj);
    //refreshDataServiceScreen();
    //showGeneratedConfigFile();
}

function addConfigParameter(){
	var newParam = wso2.wsf.Util.getUserInput();
    if (newParam != null) {
    	dataServiceObj.getElementsByTagName("config").item(0).appendChild(createPropelement(newParam[0], newParam[1]));
    }
    refreshDataServiceScreen();
}

function addNewConfigParameter() {
    var quDivObj = document.getElementById("divDSAddParam");
    wso2.wsf.Util.processXML(dataServiceObj, "data_service_add_config_param.xsl", quDivObj);
}

function add_param(validate) {
    if(document.getElementById("txtDataServiceParamName") != null)
    {
      var paramName = document.getElementById("txtDataServiceParamName").value;
      var paramValue = document.getElementById("txtDataServiceParamValue").value;
      if(paramName != "") {
          var isvalid = true;
          var paramset = dataServiceObj.getElementsByTagName("property");
          for(var i=0; i<paramset.length; i++) {
              if(paramset[i].getAttribute("name") == paramName) {
                  if(!validate) {
                      wso2.wsf.Util.alertWarning("Parameter with the name \"" + paramName + "\" already exists");
                      return false;
                  } else {
                      isvalid = false;
                  }
              }
          }
          if(isvalid) {
              dataServiceObj.getElementsByTagName("config")[0].appendChild(createPropelement(paramName, paramValue));
          }
      } else if(!validate) {
          wso2.wsf.Util.alertWarning("Parameter name is required in order to add a configuration parameter");
          return false;
      }
    }
    return true;
}

function add_ds_param() {

    ds_collectdata["ds_step0"](true);
    if(!add_param()) {
        return;
    }
    refreshDataServiceScreen();
}

function remove_ds_param(paramName) {

    var properties = dataServiceObj.getElementsByTagName("config")[0].getElementsByTagName("property");
    for(var i=0; i<properties.length; i++) {
        if(properties[i].getAttribute("name") == paramName) {
            dataServiceObj.getElementsByTagName("config")[0].removeChild(properties[i]);
        }
    }
    refreshDataServiceScreen();
}

function addNewInputMapping(){
	var newParam = wso2.wsf.Util.getUserInputCustum("Please enter the Input Mapping name", "Please enter the SQL Type", false);
    if (newParam != null) {
    	dataServiceQueryObj.appendChild(createInputMappingElement(newParam[0], newParam[1]));
    }
    refresEditDataServiceQueryScreen();
}



function addNewOutputMapping(){
	var opDivObj = document.getElementById("divDataServiceAddOutput");
    wso2.wsf.Util.processXML(dataServiceObj, "data_service_add_output_mapping.xsl", opDivObj);
    wso2.wsf.Util.showOnlyOneMain(opDivObj);
    showDataServiceOutputMappingHeader(document.getElementById('dataServiceOutputMappingHeader'));
}

function addDataServiceOMElementDone(){

    var dataServiceOMElementName = document.getElementById("txtDataServiceOMElementName").value;
	var dataServiceOMColumnName = document.getElementById("txtDataServiceOMColumnName").value;

    if(dataServiceOMElementName == "") {
        wso2.wsf.Util.alertWarning("Name for an output mapping is required");
        return;
    }

//    if(editingOPMapping != "") {
    var mappings = dataServiceQueryObj.getElementsByTagName("element");
    for(var i=0; i<mappings.length; i++) {
        if(mappings[i].getAttribute("column") == editingOPMapping && editingOPMapping != "") {
            mappings[i].parentNode.removeChild(mappings[i]);
        } else {
        if(mappings[i].getAttribute("column") == dataServiceOMColumnName) {
            wso2.wsf.Util.alertWarning("Output mapping for the specified column already exists");
            return false;
        }
            }
    }
//    }

	dataServiceQueryObj.getElementsByTagName("result").item(0).appendChild(createOutputMappingElement(dataServiceOMElementName, dataServiceOMColumnName));
    refresEditDataServiceQueryScreen();
//	refreshWizardScreen('divDataServiceAddOutput','data_service_add_query_output_mapping.xsl',dataServiceQueryObj,'dataServiceOutputMappingHeader');
}

function addDataServiceOMQueryDone(){

    var dsQueries = document.getElementById("cmbDataServiceQueryId");
    var dataServiceQueryId = dsQueries.options[dsQueries.selectedIndex].value;

//    if(editingOPMapping != "") {
    var mappings = dataServiceQueryObj.getElementsByTagName("call-query");
    for(var i=0; i<mappings.length; i++) {
        if(mappings[i].getAttribute("href") == editingOPMapping && editingOPMapping != "") {
            mappings[i].parentNode.removeChild(mappings[i]);
        } else {
            if(mappings[i].getAttribute("href") == dataServiceQueryId) {
            wso2.wsf.Util.alertWarning("Output mapping for the query id \"" + dataServiceQueryId + "\" already present");
            return false;
        }
        }
    }

    var callQuery = createOutputMappingQuery(dataServiceQueryId);
    var dsqueries = dataServiceObj.getElementsByTagName("query");
        for(var j=0; j<dsqueries.length; j++) {
            if(dsqueries[j].getAttribute("id") == dataServiceQueryId) {
                var queryparams = dsqueries[j].getElementsByTagName("param");
                for(var k=0; k<queryparams.length; k++) {
                    var qparaname = queryparams[k].getAttribute("name");
                    callQuery.appendChild(createWithParamElement(qparaname, document.getElementById("mapping_for_" + qparaname).value));
                }
            }
        }
//    }
//    alert(dsQueries.selectedIndex + " " + dataServiceQueryId)
//    var mappings = dataServiceQueryObj.getElementsByTagName("call-query");
//    for(var i=0; i<mappings.length; i++) {
//        if(mappings[i].getAttribute("href") == dataServiceQueryId) {
//            wso2.wsf.Util.alertWarning("Output mapping for the query id \"" + dataServiceQueryId + "\" already present");
//            return false;
//        }
//    }

    dataServiceQueryObj.getElementsByTagName("result").item(0).appendChild(callQuery);
//    dataServiceQueryObj.getElementsByTagName("result").item(0).appendChild(createOutputMappingQuery(dataServiceQueryId));
    refresEditDataServiceQueryScreen();
//	refreshWizardScreen('divDataServiceAddOutput','data_service_add_query_output_mapping.xsl',dataServiceQueryObj,'dataServiceOutputMappingHeader');
}

function dataserviceOMTypeSelected(outputType){
	if (outputType == 'OutputElement'){
		document.getElementById('divOMElement').style.display = "inline";
		document.getElementById('divOMQuery').style.display = "none";
	} else if (outputType == 'Query'){
		document.getElementById('divOMElement').style.display = "none";
		document.getElementById('divOMQuery').style.display = "inline";
        displayOperationWithParams();
    }
	curDataServiceOutputMappingType = outputType;
}

function displayAddDataServiceOperation(){
//	dataServiceCurOpObj = null;
	var opDivObj = document.getElementById("divDSAddOperation");
    wso2.wsf.Util.processXML(dataServiceObj, "data_service_add_operation.xsl", opDivObj);
//    wso2.wsf.Util.showOnlyOneMain(opDivObj);
//    showDataServiceOperationsHeader(document.getElementById('dataServiceAddOperationHeader'));
}

function displayOperationWithParams(){
//	dataServiceCurOpObj = null;
    dataServiceObj.setAttribute("ds_op_query_id", document.getElementById("cmbDataServiceQueryId").value);
    var opDivObj = document.getElementById("divDSOperationParams");
    wso2.wsf.Util.processXML(dataServiceObj, "data_service_operation_params.xsl", opDivObj);
//    wso2.wsf.Util.showOnlyOneMain(opDivObj);
//    showDataServiceOperationsHeader(document.getElementById('dataServiceAddOperationHeader'));
}


function addDataServiceOperation(){
	var opName = document.getElementById("txtDataServiceOpName").value;
	var queryName = document.getElementById("cmbDataServiceQueryId").value;

    if(opName!="") {

    if (dataServiceCurOpObj == null){
        var dsops = dataServiceObj.getElementsByTagName("operation");
        for(var i=0; i<dsops.length; i++) {
            if(dsops[i].getAttribute("name") == opName) {
                wso2.wsf.Util.alertWarning("Operation with the name \"" + opName + "\" already present");
                return false;
            }
        }
        var opObj = createOpElement(opName, queryName);
        var dsqueries = dataServiceObj.getElementsByTagName("query");
        for(var j=0; j<dsqueries.length; j++) {
            if(dsqueries[j].getAttribute("id") == queryName) {
                var queryparams = dsqueries[j].getElementsByTagName("param");
                for(var k=0; k<queryparams.length; k++) {
                    var qparaname = queryparams[k].getAttribute("name");
                    opObj.getElementsByTagName("call-query")[0].appendChild(createWithParamElement(qparaname, document.getElementById("mapping_for_" + qparaname).value));
                }
            }
        }
        dataServiceObj.getElementsByTagName("data").item(0).appendChild(opObj);
	} else {
		var callQueryObj = dataServiceCurOpObj.getElementsByTagName("call-query").item(0);
		callQueryObj.setAttribute("href", queryName);
		dataServiceCurOpObj.setAttribute("name", opName);
        var withparams = callQueryObj.getElementsByTagName("with-param");
        var k = 0;
        while(withparams.length!=0) {
            callQueryObj.removeChild(withparams[k]);
            k++;
        }

        var dsqueries = dataServiceObj.getElementsByTagName("query");
        for(var j=0; j<dsqueries.length; j++) {
            if(dsqueries[j].getAttribute("id") == queryName) {
                var queryparams = dsqueries[j].getElementsByTagName("param");
                for(var k=0; k<queryparams.length; k++) {
                    var qparaname = queryparams[k].getAttribute("name");
                    callQueryObj.appendChild(createWithParamElement(qparaname, document.getElementById("mapping_for_" + qparaname).value));
                }
            }
        }
    }
        } else {
        wso2.wsf.Util.alertWarning("Name of an operation is required");
        return false;
    }
//	addNewDataServiceEchoDataElement(dataServiceObj);
    refreshDataServiceScreen();
    dataServiceCurOpObj = null;
}

function editDataServiceOperation(operationName){
	displayAddDataServiceOperation();
	dataServiceCurOpObj = getNodeWithPropertyFromCollection(dataServiceObj.getElementsByTagName("operation"), "name", operationName);
	document.getElementById("txtDataServiceOpName").value = operationName;
	document.getElementById("cmbDataServiceQueryId").value = getAttbute("href", dataServiceCurOpObj.getElementsByTagName("call-query").item(0));
    displayOperationWithParams();
    var dsqueries = dataServiceObj.getElementsByTagName("query");
    for(var i=0; i<dsqueries.length; i++) {
        if(dsqueries[i].getAttribute("id") == getAttbute("href", dataServiceCurOpObj.getElementsByTagName("call-query").item(0))) {
            var withparams = dataServiceCurOpObj.getElementsByTagName("with-param");
            for(var j=0; j<withparams.length; j++) {
                document.getElementById("mapping_for_" + withparams[j].getAttribute("query-param")).value = withparams[j].getAttribute("name");
            }
        }
    }
}

function dataServiceRemoveOperation(operationName){
	dataServiceCurOpObj = getNodeWithPropertyFromCollection(dataServiceObj.getElementsByTagName("operation"), "name", operationName);
	dataServiceCurOpObj.parentNode.removeChild(dataServiceCurOpObj);
	refreshDataServiceScreen();
    dataServiceCurOpObj = null;
}
function deployDataService(){
	var dataServiceContents = prettyPrintDOMNode(dataServiceObj.getElementsByTagName("data").item(0), "", "    ", true);//document.getElementById("txtDataServiceReviewBox").value;
	    var body_xml = '<req:saveDataServiceContents xmlns:req="http://org.apache.axis2/xsd">\n' +
				   		' <arg0>' + curDataServiceName + '</arg0>\n' +
				   		' <arg1><![CDATA[' + dataServiceContents +']]></arg1>\n' +
                   ' </req:saveDataServiceContents>\n';

    var callURL = serverURL + "/" + "DataServiceAdmin" + "/saveDataServiceContents" ;

    new wso2.wsf.WSRequest(callURL,"getAxisConfigData",body_xml,deployDataServiceCallback);
}


function deployDataServiceCallback(){
	showServiceInitializer();
}

function createOpElement(opName, queryName){
	var opObj = rootDocument.createElement("operation");
	opObj.setAttribute("name", opName);
	var queryObj = rootDocument.createElement("call-query")
	queryObj.setAttribute("href", queryName);
	opObj.appendChild(queryObj);
	return opObj;
}

function createWithParamElement(queryParamName, paramName){
	var opObj = rootDocument.createElement("with-param");
    if(paramName != null && paramName != "") {
        opObj.setAttribute("name", paramName);
    } else {
        opObj.setAttribute("name", queryParamName);
    }
    opObj.setAttribute("query-param", queryParamName);
	return opObj;
}


function createPropelement(propName, propValue){
	var propObj = rootDocument.createElement("property");
	propObj.appendChild(rootDocument.createTextNode(propValue));
	propObj.setAttribute("name", propName);
	return propObj;
}

function createInputMappingElement(elementName, sqlType){
	var imElement = rootDocument.createElement("param");
	imElement.setAttribute("name", elementName);
	imElement.setAttribute("sqlType", sqlType);
	return imElement;
}


function createOutputMappingElement(elementName, dataColumn){
	var imElement = rootDocument.createElement("element");
	imElement.setAttribute("name", elementName);
	imElement.setAttribute("column", dataColumn);
	return imElement;
}

function createOutputMappingQuery(queryName){
	var imElement = rootDocument.createElement("call-query");
	imElement.setAttribute("href", queryName);
	return imElement;
}

function querySQLOnChange(sqlStatement,form){
	var sqlObj = dataServiceQueryObj.getElementsByTagName("sql").item(0);
	sqlObj.removeChild(sqlObj.childNodes.item(0));
	sqlObj.appendChild(rootDocument.createTextNode(sqlStatement));
	
	if(sqlStatement.length > 0){
	    changeOutputMappingFieldStatus(false);
     	//if sql contains ?, then need to enable input parameter entry box
	    if(sqlStatement.indexOf('?') > -1){
           document.getElementById('name').disabled = false;
           document.getElementById('sqlType').disabled = false;
           document.getElementById('addInputParamMappingButton').disabled = false;
        }
	}else{
	   changeOutputMappingFieldStatus(true);
	}
}

function disableInputMappingFields(){
       if(dataServiceObj.getAttribute("dataSourceType") == "RDBMS"){
         var sqlStatement = document.getElementById("txtDataServiceSQL").value;
    	 //if sql contains ?, then need to enable input parameter entry box
	     if(sqlStatement.indexOf('?') == -1){
            document.getElementById('name').disabled = true;
            document.getElementById('sqlType').disabled = true;
            document.getElementById('addInputParamMappingButton').disabled = true;
         }
       }
}

function disableOutputMappingFields(){
    if("RDBMS" == dataServiceObj.getAttribute("dataSourceType")){
       var sqlStatement = document.getElementById("txtDataServiceSQL").value;
  	   //if sql field contains something, output mappings should be enabled 
	   if(sqlStatement.length == 0){
	       changeOutputMappingFieldStatus(true);
       }
    }
}

function changeOutputMappingFieldStatus(disabled){
     document.getElementById('txtDataServiceWrapElement').disabled = disabled;
     document.getElementById('txtDataServiceRowName').disabled = disabled;
     document.getElementById('cmbDataServiceOMType').disabled = disabled;
     //default selection is Element,following fields are shown for element
     document.getElementById('txtDataServiceOMElementName').disabled = disabled;
     document.getElementById('txtDataServiceOMColumnName').disabled = disabled;
     document.getElementById('addOutputParamMappingButton').disabled = disabled;
     document.getElementById('addQueryButton').disabled = disabled;
     document.getElementById('addQueryRestButton').disabled = disabled;
}


function queryWENOnChange(WEN){
	var resultObj = dataServiceQueryObj.getElementsByTagName("result").item(0);
	resultObj.setAttribute("element", WEN);
}

function queryRNOnChange(RN){
	var resultObj = dataServiceQueryObj.getElementsByTagName("result").item(0);
	resultObj.setAttribute("rowName", RN);
}

function newQueryIdOnChange(queryId){
    dataServiceQueryObj.setAttribute("id",queryId);
}

function showGeneratedConfigFile(){
	var finalScreenHTML = '<h4><div id="divGeneratedConfigHeader"></div></h4>' +
			'<div><label>Review and Deploy Dataservice</label></div>' +
     	'<div id="formset">' +
            '<form>' +
                '<fieldset style="border:none;">' +
                    '<div>' +
                       	'<textarea rows="30" cols="80" id="txtDataServiceReviewBox"></textarea>' +
                    '</div><p>&nbsp;</p>' +
                	'<div>' +
                		'<input type="button" value="Deploy" onclick="javascript:deployDataService();return false;"/>' +
                	'</div>' +
                  '</fieldset>' +
              '</form>' +
		'</div>' +
        '</fieldset>';
    var dataServiceConfigDiv = document.getElementById("divDataServiceDisplayConfig");
	dataServiceConfigDiv.innerHTML = finalScreenHTML;
	document.getElementById("txtDataServiceReviewBox").value = prettyPrintDOMNode(dataServiceObj.getElementsByTagName("data").item(0), "", "    ", true);
	showNewDataServiceHeader(document.getElementById('divGeneratedConfigHeader'));
	wso2.wsf.Util.showOnlyOneMain(dataServiceConfigDiv);
}

var dataServiceNewQuery = false;
function addDataServiceQuery(){
	dataServiceNewQuery = true;
//	var getQueryIDPrompt = "Enter the name of the query"
//	var tempValue = window.prompt(getQueryIDPrompt);
//    if (tempValue == '' || tempValue == null) {
//        return false;
//    }

	var queryEle = rootDocument.createElement("query");
	

	
	if("EXCEL"==dataServiceObj.getAttribute("dataSourceType")){
	   queryEle.setAttribute("id", "");
	   //sqlEle.appendChild(rootDocument.createTextNode("UseSheet=0:StartReadingFromRow=1"));
       //create excel elements
	   var excelElement = rootDocument.createElement("excel");
	   var workBookNameElement = rootDocument.createElement("workbookname");
	   var hasHeaderElement = rootDocument.createElement("hasheader");	   
	   var startingRowElement = rootDocument.createElement("startingrow");
	   var maxRowCountElement = rootDocument.createElement("maxrowcount");

       //append text box values
	   workBookNameElement.appendChild(rootDocument.createTextNode(""));
	   maxRowCountElement.appendChild(rootDocument.createTextNode(""));
	   hasHeaderElement.appendChild(rootDocument.createTextNode(""));
	   startingRowElement.appendChild(rootDocument.createTextNode(""));

       //add as children to excel element
	   excelElement.appendChild(workBookNameElement);
	   excelElement.appendChild(hasHeaderElement);
	   excelElement.appendChild(startingRowElement);
	   excelElement.appendChild(maxRowCountElement);
	   	   	   	   
       queryEle.appendChild(excelElement);
	   
	   
	}else if("RDBMS"==dataServiceObj.getAttribute("dataSourceType")){
	   var sqlEle = rootDocument.createElement("sql");
	   queryEle.setAttribute("id", "");
	   sqlEle.appendChild(rootDocument.createTextNode(""));
	   queryEle.appendChild(sqlEle);
	}
	
	var resultEle = rootDocument.createElement("result");
	resultEle.setAttribute("element", "");
	resultEle.setAttribute("rowName", "");	
	queryEle.appendChild(resultEle);
	dataServiceObj.getElementsByTagName("data").item(0).appendChild(queryEle);
	dataServiceQueryObj = queryEle;	
	refresEditDataServiceQueryScreen();
}

function editDataServiceQuery(queryName) {
	dataServiceQueryObj = getNodeWithPropertyFromCollection(dataServiceObj.getElementsByTagName("query"), "id", queryName);
	refresEditDataServiceQueryScreen();
}


function refresEditDataServiceQueryScreen(){
    editingIPMapping = "";
    editingOPMapping = "";
    var quDivObj = document.getElementById("divDSAddQuery");
    wso2.wsf.Util.processXML(dataServiceQueryObj, "data_service_add_query.xsl", quDivObj);

//    showDataServiceQueryHeader(document.getElementById('dataServiceAddQueryHeader'));
//	wso2.wsf.Util.showOnlyOneMain(document.getElementById('divDataServiceAddQuery'));
}

var editingIPMapping = "";

function edit_ds_ip_mapping(mappingName, mappingValue) {

    document.dataServiceAddQueryForm.name.value = mappingName;
    document.dataServiceAddQueryForm.sqlType.value = mappingValue;
    editingIPMapping = mappingName;
}

function remove_query(queryId) {

    var queries = dataServiceObj.getElementsByTagName("query");
    var references = dataServiceObj.getElementsByTagName("call-query");

    for(var i=0; i<references.length; i++) {
        if(references[i].getAttribute("href") == queryId) {
            wso2.wsf.Util.alertMessage("Can not delete the query with id \"" + queryId + "\". There are operations refering to this query");
            return;
        }
    }

    for(i=0; i<queries.length; i++) {
        if(queries[i].getAttribute("id") == queryId) {
            dataServiceObj.getElementsByTagName("data")[0].removeChild(queries[i]);
        }
    }
    refreshDataServiceScreen();
}

function remove_ds_query(queryId) {
    add_query(true);
    remove_query(queryId);
}

function getNodeWithPropertyFromCollection(objCollection, propName, propValue){
	for (var i=0;i<objCollection.length;i++){
		var curr = objCollection.item(i);
		var currPropValue = getAttbute(propName, curr);
		if (currPropValue == propValue){
			return curr;
		}
	}
	// Return null if no node is found with the given attribute.
	return null;
}

function ds_next() {
    if(!ds_collectdata["ds_step" + dataServiceObj.getAttribute("ds_step")]()) {
        //refreshDataServiceScreen();
        return;
    }

    if(dataServiceObj.getAttribute("ds_step") == "0") {
        //var ds_dataSourceType = document.getElementById("databaseSourceType").value;
        //alert(ds_dataSourceType);
        add_param(true);
    }

    dataServiceObj.setAttribute("ds_step", parseInt(dataServiceObj.getAttribute("ds_step")) + 1);
    setDataSourceType();
    refreshDataServiceScreen();
}

function ds_back() {
    ds_collectdata["ds_step" + dataServiceObj.getAttribute("ds_step")](true);
//        refreshDataServiceScreen();
//        return;
//    }
    dataServiceObj.setAttribute("ds_step", parseInt(dataServiceObj.getAttribute("ds_step")) - 1);
    refreshDataServiceScreen();
}

function add_ds_query() {
    add_query();
    refreshDataServiceScreen();
}

function remove_query_op_mapping(href) {

    var mappings = dataServiceQueryObj.getElementsByTagName("call-query");
    for(var i=0; i<mappings.length; i++) {
        if(mappings[i].getAttribute("href") == href) {
            mappings[i].parentNode.removeChild(mappings[i]);
        }
    }

    refresEditDataServiceQueryScreen();
}

function remove_element_op_mapping(column) {

    var mappings = dataServiceQueryObj.getElementsByTagName("element");
    for(var i=0; i<mappings.length; i++) {
        if(mappings[i].getAttribute("column") == column) {
            mappings[i].parentNode.removeChild(mappings[i]);
        }
    }

    refresEditDataServiceQueryScreen();
}

var editingOPMapping = "";

function edit_query_op_mapping(href) {

    editingOPMapping = href;
    document.getElementById("cmbDataServiceOMType").options[1].selected = true;
    dataserviceOMTypeSelected("Query");
    var optionset = document.getElementById("cmbDataServiceQueryId").options;
    for(var i=0; i<optionset.length; i++) {
        if(optionset[i].value == href) {
            optionset[i].selected = true;
        }
    }

    var dsqueries = dataServiceObj.getElementsByTagName("query");
    for(var i=0; i<dsqueries.length; i++) {
        if(dsqueries[i].getAttribute("id") == href) {
            var withparams = dataServiceQueryObj.getElementsByTagName("with-param");
            for(var j=0; j<withparams.length; j++) {
                document.getElementById("mapping_for_" + withparams[j].getAttribute("query-param")).value = withparams[j].getAttribute("name");
            }
        }
    }
}

function edit_element_op_mapping(name, column) {

    editingOPMapping = column;
    document.getElementById("cmbDataServiceOMType").options[0].selected = true;
    dataserviceOMTypeSelected("OutputElement");
    document.getElementById("txtDataServiceOMElementName").setAttribute("value", name);
    document.getElementById("txtDataServiceOMColumnName").setAttribute("value", column);
}

ds_collectdata["ds_step0"] = function collect_ds_configure_data(validate) {
    if(newDataService)
    {
	    //validate service name
	    var ds_name = document.getElementById("dataServiceName").value;
	    if(ds_name != null && ds_name != "") {
	        dataServiceObj.getElementsByTagName("data")[0].setAttribute("name", ds_name);
	    } else if(!validate){
	        wso2.wsf.Util.alertWarning("Name of the data service must be provided in order to proceed");
	        return false;
	    }
	    
	    //validate data source type
	    var ds_dataSourceType = document.getElementById("databaseSourceType").value;
	    if(ds_dataSourceType == null || ds_dataSourceType == "") {
	        if(!validate){
	          wso2.wsf.Util.alertWarning("Data source type must be selected.");
	          return false;
	        }
	    } 
	    
	    var ds_dataSourceType = document.getElementById("databaseSourceType").value;
	    if("RDBMS"==ds_dataSourceType){
	       var databaseServerType = document.getElementById("databaseServerType").value;
	       var driver = document.getElementById("org.wso2.ws.dataservice.driver").value;
	       var protocol = document.getElementById("org.wso2.ws.dataservice.protocol").value;
	       
	       if(databaseServerType == " # "){
	          wso2.wsf.Util.alertWarning("Please select a Database type.");
	          return false;         
	       }
	       if(driver == null || driver.replace(/^\s+|\s+$/g,"")==""){
	          wso2.wsf.Util.alertWarning("Please enter a correct driver class.");
	          return false;         
	       }
	       if(protocol == null || protocol.replace(/^\s+|\s+$/g,"")==""){
	          wso2.wsf.Util.alertWarning("Please enter a correct JDBC Url.");
	          return false;         
	       }           
	    }else if("CSV"==ds_dataSourceType){
	       //var val = document.getElementById("csvFileLocation").value;
	       //if(val == null || val.replace(/^\s+|\s+$/g,"")==""){
	       //   wso2.wsf.Util.alertWarning("Please select a correct CSV file location.");
	       //   return false;         
	       //}
	    }else if("EXCEL"==ds_dataSourceType){
	       var val = document.getElementById("excel_datasource").value;
	       if(val == null || val.replace(/^\s+|\s+$/g,"")==""){
	          wso2.wsf.Util.alertWarning("Please select a correct MS Excel file location.");
	          return false;         
	       }    
	    }else if("JNDIDataSource"==ds_dataSourceType){
	          wso2.wsf.Util.alertWarning("JNDI Data source support will be available in near future.");
	          return false;  
	    }
	    
	
	    var properties = dataServiceObj.getElementsByTagName("property");
	    for(var i=0; i<properties.length; i++) {
	        if(document.getElementById(properties[i].getAttribute("name")) != null) {
	            if(properties[i].childNodes.length) {
	                properties[i].removeChild(properties[i].childNodes[0]);
	            }
	            properties[i].appendChild(rootDocument.createTextNode(//"<![CDATA["
	                     document.getElementById(properties[i].getAttribute("name")).value ));//+ "]]>"));
	        }
	    }
    }
    return true;
}

ds_collectdata["ds_step1"] = function collect_ds_query_data(validate) {

    var retval = add_query(true);

    if(dataServiceObj.getElementsByTagName("query").length == 0 && !validate) {
        wso2.wsf.Util.alertWarning("Data service needs at least one Query to proceed");
        return false;
    }

    return retval;
}

function add_query(validate) {

    var queryId = document.getElementById("txtDataServiceQueryId").value;

    var isValidQuery = true;
    if(queryId != "") {
        dataServiceQueryObj.setAttribute("id", queryId);
    } else if(!validate) {
        wso2.wsf.Util.alertWarning("Sql query MUST have an Id associated with it");
        isValidQuery = false;
    } else {
        isValidQuery = false;
    }

    var queries = dataServiceObj.getElementsByTagName("query");
    for(var i=0; i<queries.length; i++) {
       if(queries[i].getAttribute("id") == "") {
           dataServiceObj.getElementsByTagName("data")[0].removeChild(queries[i]);
       }
    }

    var dataSourceType = dataServiceObj.getAttribute("dataSourceType");
    if("RDBMS" == dataSourceType){
	   var sql = document.getElementById("txtDataServiceSQL").value;
	   if(isValidQuery) {
	       dataServiceObj.getElementsByTagName("data")[0].appendChild(dataServiceQueryObj);
	   } else if(!validate) {
	       return false;
	   }
    }else if("EXCEL" == dataSourceType){
       //var workBookName = document.getElementById("txtExcelWorkbookName").value;
       //var hasHeader = document.getElementById("txtExcelHeaderColumns").value;
       //var startingRow = document.getElementById("txtExcelStartingRow").value;
       //var maxRowCount = document.getElementById("txtExcelMaxRowCount").value;

       //create excel elements
	   //var excelElement = rootDocument.createElement("excel");
	   //var workBookNameElement = rootDocument.createElement("workBookName");
	   //var hasHeaderElement = rootDocument.createElement("hasHeader");	   
	   //var startingRowElement = rootDocument.createElement("startingRow");
	   //var maxRowCountElement = rootDocument.createElement("maxRowCount");

       //append text box values
	   //workBookNameElement.appendChild(rootDocument.createTextNode(workBookName));
	   //maxRowCountElement.appendChild(rootDocument.createTextNode(maxRowCount));
	   //hasHeaderElement.appendChild(rootDocument.createTextNode(hasHeader));
	   //startingRowElement.appendChild(rootDocument.createTextNode(startingRow));

       //add as children to excel element
	   //excelElement.appendChild(workBookNameElement);
	   //excelElement.appendChild(hasHeaderElement);
	   //excelElement.appendChild(startingRowElement);
	   //excelElement.appendChild(maxRowCountElement);
	   	   	   	   
       //dataServiceQueryObj.appendChild(excelElement);
       //dataServiceObj.getElementsByTagName("data")[0].appendChild(dataServiceQueryObj);
    }
    return true;
}

ds_collectdata["ds_step2"] = function collect_ds_operation_data() {

    return true;
}

function remove_ds_ip_mapping(mappingName) {

    remove_ip_mapping(mappingName);
    refresEditDataServiceQueryScreen();
}

function remove_ip_mapping(mappingName) {

    var mappings = dataServiceObj.getElementsByTagName("param");
    for(var i=0; i<mappings.length; i++) {
        if(mappings[i].getAttribute("name") == mappingName) {
            mappings[i].parentNode.removeChild(mappings[i]);
        }
    }
}

function remove_ds_op_mapping(mappingName) {

    remove_op_mapping(mappingName);
    refresEditDataServiceQueryScreen();
}

function remove_op_mapping(mappingName) {

    var mappings = dataServiceObj.getElementsByTagName("param");
    for(var i=0; i<mappings.length; i++) {
        if(mappings[i].getAttribute("name") == mappingName) {
            mappings[i].parentNode.removeChild(mappings[i]);
        }
    }
}

function addQueryElementToDS () {
	dataServiceNewQuery = true;

	var queryEle = rootDocument.createElement("query");
	queryEle.setAttribute("id", "");

	var sqlEle = rootDocument.createElement("sql");
	sqlEle.appendChild(rootDocument.createTextNode(""));

	var resultEle = rootDocument.createElement("result");
	resultEle.setAttribute("element", "element");
	resultEle.setAttribute("rowName", "rowName");

	queryEle.appendChild(sqlEle);

	dataServiceQueryObj = queryEle;
	//addInputParamToQuery();
	//addNewInputParamMapping("","");

	dataServiceQueryObj.appendChild(resultEle);


	dataServiceObj.getElementsByTagName("data").item(0).appendChild(dataServiceQueryObj);
	refresEditDataServiceQueryScreen();
}

function addInputParamToQuery(queryId){
	//alert(queryId);
	var paramEle = rootDocument.createElement("param");
	paramEle.setAttribute("name","");
	paramEle.setAttribute("sqlType","");
	dataServiceQueryObj.appendChild(paramEle);

	var tmp = dataServiceObj.getElementsByTagName("data").item(0).getElementsByTagName("query");
    for (i = 0; i < tmp.length; i += 1) {
		//alert(tmp[i].getAttribute("id"));

    }
	if (tmp.length > 0){
		//alert(wso2.wsf.Util.xmlSerializerToString(tmp));
	}



	//alert(wso2.wsf.Util.xmlSerializerToString(dataServiceObj));
	//xslToReload = 'data_service_add_query.xsl';
	//addNewDataServiceEchoDataElement(dataServiceObj);

}


function updateDSWithNewQuery(){
	var dataServiceSQL = document.getElementById('txtDataServiceSQL').value;
	//var dataServiceWrapElement = document.getElementById('txtDataServiceWrapElement').value;
	//var dataServiceRowName = document.getElementById('txtDataServiceRowName').value;

	var sqlObj = dataServiceQueryObj.getElementsByTagName("sql").item(0);
	sqlObj.removeChild(sqlObj.childNodes.item(0));
	sqlObj.appendChild(rootDocument.createTextNode(dataServiceSQL));

	//var resultObj = dataServiceQueryObj.getElementsByTagName("result").item(0);
	//resultObj.setAttribute("element", dataServiceWrapElement);
	//resultObj.setAttribute("rowName", dataServiceRowName);

	xslToReload = 'data_service_add_query.xsl';
	addNewDataServiceEchoDataElement(dataServiceObj);
}

function addNewInputParamMapping(param,sqlType){
    if(param!="" && sqlType !="- select the type -") {
        var params = dataServiceQueryObj.getElementsByTagName("param");
        for(var i=0; i<params.length; i++) {
            if(editingIPMapping != "" && params[i].getAttribute("name") == editingIPMapping) {
                params[i].parentNode.removeChild(params[i]);
            } else {
            if(params[i].getAttribute("name") == param) {
                wso2.wsf.Util.alertWarning("Input mapping with the name \"" + param + "\" already present");
                return false;
            }
                }
        }
        dataServiceQueryObj.appendChild(createInputMappingElement(param, sqlType));
    } else {
        wso2.wsf.Util.alertWarning("Both Name & SQL Type are mandatory for a parameter");
        return false;
    }
    refresEditDataServiceQueryScreen();
}

function refreshWizardScreen(divId,xslFile,domObject){
	var quDivObj = document.getElementById(divId);
    wso2.wsf.Util.processXML(domObject, xslFile, quDivObj);

//    showDataServiceQueryHeader(document.getElementById('dataServiceAddQueryHeader'));
//	wso2.wsf.Util.showOnlyOneMain(document.getElementById(divId));
}


function showDSQueryOutputMappingsScreen(){
    ds_collectdata["ds_step1"]();
    refreshWizardScreen('divAddDSQueryOPMapping','data_service_add_query_output_mapping.xsl',dataServiceObj);
}


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

    var callURL = serverURL + "/" + "DataServiceAdmin" + "/" ;
    new wso2.wsf.WSRequest(callURL,"getDatabaseUrlDriverList",body_xml,loadDatabaseServerListCallback);
}

function loadDatabaseServerListCallback() {
    var comboToLoad = document.getElementById('databaseServerType');
    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].getElementsByTagName("serverId").item(0).firstChild.nodeValue);
		comboToLoad.options[count].text = rets[count].getElementsByTagName("serverId").item(0).firstChild.nodeValue;
        comboToLoad.options[count].value = rets[count].getElementsByTagName("jdbcUrl").item(0).firstChild.nodeValue + "#" +
		                                   rets[count].getElementsByTagName("driverClass").item(0).firstChild.nodeValue;
    }
    comboToLoad.options[count] = new Option('--Select--');
    comboToLoad.options[count].value = ' # ';
    comboToLoad.selectedIndex = count;


    _refreshDataServiceScreenHelper();
}

function setJDBCValues(obj,document){
	var selectedValue = obj[obj.selectedIndex].value;
	var jdbcUrl = selectedValue.substring(0,selectedValue.indexOf("#"));
	var driverClass = selectedValue.substring(selectedValue.indexOf("#")+1,selectedValue.length);
	document.getElementById('org.wso2.ws.dataservice.protocol').value = jdbcUrl;
	document.getElementById('org.wso2.ws.dataservice.driver').value = driverClass;
}

function setConfigurationScreen(dataSourceType){
    //remove all properties
    var properties = dataServiceObj.getElementsByTagName("config").item(0).getElementsByTagName("property");
    var configObj = dataServiceObj.getElementsByTagName("config").item(0);
    while(properties.length != 0){
      configObj.removeChild(properties[0]);
    } 
    
    //preserve data service name 
    var dataServiceName = document.getElementById("dataServiceName").value;
    
    if(dataSourceType == 'EXCEL'){
       dataServiceObj.getElementsByTagName("config").item(0).appendChild(createPropelement('excel_datasource', 'path-to-your-excel-file'));      
       dataServiceObj.setAttribute("dataSourceType", "EXCEL");
       refreshDataServiceScreen.call(this,false);
    }else if (dataSourceType == 'CSV'){
       dataServiceObj.setAttribute("dataSourceType", "CSV");
       dataServiceObj.getElementsByTagName("config").item(0).appendChild(createPropelement('csv_datasource', 'path-to-your-csv-file'));
       dataServiceObj.getElementsByTagName("config").item(0).appendChild(createPropelement('csv_hasheader', ''));
       dataServiceObj.getElementsByTagName("config").item(0).appendChild(createPropelement('csv_columnseperator', ''));
       dataServiceObj.getElementsByTagName("config").item(0).appendChild(createPropelement('csv_columns', ''));
       dataServiceObj.getElementsByTagName("config").item(0).appendChild(createPropelement('csv_columnordinal', ''));
       dataServiceObj.getElementsByTagName("config").item(0).appendChild(createPropelement('csv_startingrow', ''));
       dataServiceObj.getElementsByTagName("config").item(0).appendChild(createPropelement('csv_maxrowcount', ''));
       refreshDataServiceScreen.call(this,false);
    }else if(dataSourceType == 'RDBMS'){
       
       dataServiceObj.getElementsByTagName("config").item(0).appendChild(createPropelement("org.wso2.ws.dataservice.driver", ""));
       dataServiceObj.getElementsByTagName("config").item(0).appendChild(createPropelement("org.wso2.ws.dataservice.protocol", ""));
       dataServiceObj.getElementsByTagName("config").item(0).appendChild(createPropelement("org.wso2.ws.dataservice.user", ""));
       dataServiceObj.getElementsByTagName("config").item(0).appendChild(createPropelement("org.wso2.ws.dataservice.password", ""));
       dataServiceObj.setAttribute("dataSourceType", "RDBMS");
       refreshDataServiceScreen.call(this,true);
    }else if(dataSourceType == 'JNDIDataSource'){
      refreshDataServiceScreen.call(this,false);
    }
    //set the selected value
    document.getElementById("databaseSourceType").value = dataSourceType;
    document.getElementById("dataServiceName").value = dataServiceName;
    //dataServiceObj.getElementsByTagName("data")[0].setAttribute("name", dataServiceName);
}

function setDataSourceType(){
    var properties = dataServiceObj.getElementsByTagName("config").item(0).getElementsByTagName("property");
    for(var a=0;a < properties.length;a++){
      var property = properties[a];      
      if(property.getAttribute("name") == "org.wso2.ws.dataservice.driver"){
         dataServiceObj.setAttribute("dataSourceType", "RDBMS");
      }else if(property.getAttribute("name") == "csv_datasource"){
         dataServiceObj.setAttribute("dataSourceType", "CSV");
      }else if(property.getAttribute("name") == "excel_datasource"){
         dataServiceObj.setAttribute("dataSourceType", "EXCEL");
      }else if(property.getAttribute("name") == "jndi_datasource"){
         dataServiceObj.setAttribute("dataSourceType", "JNDIDataSource");
      }else if(property.getAttribute("name") == "jndi_datasource"){
         dataServiceObj.setAttribute("dataSourceType", "JNDIDataSource");
      }
    } 

}


function addAdditionalParameters(){
   if(document.getElementById('addAdditionalParamaters').checked){
     document.getElementById('divDSAddParam').style.display = "inline";
     
     document.getElementById('addAdditionalParamaters').checked = true;     
   }else{
     document.getElementById('divDSAddParam').style.display = "none";
     //document.getElementById('addAdditionalParamaters').checked = false;
   }
}



function excelWorkbookNameOnChange(workBookName,form){
   var excelObj = dataServiceQueryObj.getElementsByTagName("excel").item(0);
   var workBookObj = excelObj.getElementsByTagName("workbookname").item(0);
   workBookObj.removeChild(workBookObj.childNodes.item(0));
   workBookObj.appendChild(rootDocument.createTextNode(workBookName)); 
}

function excelHeaderColumnsOnChange(headerColumns,form){
   var excelObj = dataServiceQueryObj.getElementsByTagName("excel").item(0);
   var hasHeaderObj = excelObj.getElementsByTagName("hasheader").item(0);
   hasHeaderObj.removeChild(hasHeaderObj.childNodes.item(0));
   hasHeaderObj.appendChild(rootDocument.createTextNode(headerColumns));
}

function excelStartingRowOnChange(startingRow,form){
   var excelObj = dataServiceQueryObj.getElementsByTagName("excel").item(0);
   var startingRowObj = excelObj.getElementsByTagName("startingrow").item(0);
   startingRowObj.removeChild(startingRowObj.childNodes.item(0));
   startingRowObj.appendChild(rootDocument.createTextNode(startingRow));
}

function excelMaxRowCountOnChange(maxRowCount,form){
   var excelObj = dataServiceQueryObj.getElementsByTagName("excel").item(0);
   var maxRowCountObj = excelObj.getElementsByTagName("maxrowcount").item(0);
   maxRowCountObj.removeChild(maxRowCountObj.childNodes.item(0));
   maxRowCountObj.appendChild(rootDocument.createTextNode(maxRowCount));
}

