// JS Mechanisms for the Quote Entity (quote)
function addProcessOnStateChange()
{
	Xrm.Page.data.process.addOnStageChange(testFunct());
}
function testFunct()
{
	return;
}

function setProcessStep()
{	
	debugger;
	var step = Xrm.Page.getAttribute("ocl_quotecreationprocessstep").getValue();
	var bpf = Xrm.Page.data.process.getActiveProcess();
	var processName = bpf.getName();
	var processStage = bpf.getStages().getByIndex(step).getName();
	var actionName = "ocl_setBusinessProcessFlowStage";	

	var traversed = new Array();
	for (var i = 0; i <= step; i++) {
		traversed.push(bpf.getStages().getByIndex(i).getId());
	}
	var params = [{name:"BusinessProcessFlow", value: processName},{ name:"BusinessProcessFlowStage", value: processStage},{name:"TraversedPath", value:traversed.join(',')},{name:"Entity", value:"quote"},{name:"EntityId",value:Xrm.Page.data.entity.getId()}];
	InvokeGlobalAction(actionName, "OKMessage", "ErrorMessage", params);
	
	Xrm.Page.data.process.setActiveStage(bpf.getStages().getByIndex(step).getId());
	
	getDirtyFields();
	Xrm.Page.data.entity.save();

}

function clearAllNotifications()
{
	var notifications = parent.document.getElementById("crmNotifications").getElementsByClassName("Notification");
			for (var i = notifications.length - 1; i >= 0; i--) {
				Xrm.Page.ui.clearFormNotification(notifications[i].getAttribute("notificationid"));
			}
}

function returnTrue()
{
	return true;
}
function calcTCV_MRR()
{
	debugger;
	var flag = Xrm.Page.getAttribute("ocl_quotecreationprocessfinished").getValue();
	var formType = Xrm.Page.ui.getFormType();
	if (!flag || formType == 3 || formType == 4)
		return;

	var services = getQuoteServices(Xrm.Page.data.entity.getId());
	var mrr = 0;
	var tcv = 0;
	var arr = 0;
	var originalPrice = 0;
	for (var i = 0, len = services.length; i < len; i++) 
	{
		if (!services[i].attributes["ocl_matrice"] || !services[i].attributes["ocl_matrice"].value) {continue;}
		var servName= services[i].attributes["ocl_matrice"].value;
		var quantity = services[i].attributes["ocl_quantity"].value;
		if (endsWith(servName, "_REC"))
		{
			mrr = mrr+(services[i].attributes["ocl_overriddenprice"].value * quantity);
			arr = arr+((services[i].attributes["ocl_overriddenprice"].value*12)*quantity);
			originalPrice = originalPrice + (services[i].attributes["ocl_defaultprice"].value*quantity);
		}
		else
			tcv = tcv+services[i].attributes["ocl_overriddenprice"].value;
	}
	Xrm.Page.getAttribute("ocl_mrr").setValue(mrr);
	Xrm.Page.getAttribute("ocl_arr").setValue(arr);
	Xrm.Page.getAttribute("ocl_originalrecurringprice").setValue(originalPrice);
	Xrm.Page.getAttribute("ocl_tcv").setValue(tcv+(mrr*Xrm.Page.getAttribute("ocl_contractduration").getValue()));

debugger;
	var type = Xrm.Page.getAttribute("ocl_typedevis").getValue();
	if (type == 1) 
	{
		var originalSub = Xrm.Page.getAttribute("ocl_originalsubscription").getValue();
		var sub = getSubscriptionMRR(originalSub[0].id);
		if (sub.length > 0 && sub[0].attributes["ocl_mrr"]) 
		{
			var subMRR = sub[0].attributes["ocl_mrr"].value;
			Xrm.Page.getAttribute("ocl_mrrdelta").setValue(mrr-subMRR);
		}
	}

}
function endsWith(str, suffix) {
	return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

function getSubscriptionMRR(id)
{
	var fetch = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' no-lock='true'>"
+"  <entity name='ocl_subscription'>"
+"    <attribute name='ocl_subscriptionid' />"
+"    <attribute name='ocl_mrr' />"
+"    <filter type='and'>"
+"      <condition attribute='ocl_subscriptionid' operator='eq' value='"+id+"' />"
+"    </filter>"
+"  </entity>"
+"</fetch>";


	var results = null

	try {
		results = XrmServiceToolkit.Soap.Fetch(fetch);

	} catch (e) {
		results = new Object();
	}

	return results;
}
function getQuoteServices(id)
{		
	var fetch = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' no-lock='true'>"
	+"  <entity name='ocl_listofservices'>"
	+"    <attribute name='ocl_listofservicesid' />"
	+"    <attribute name='ocl_name' />"
	+"    <attribute name='ocl_matrice' />"
	+"    <attribute name='ocl_status' />"
	+"    <attribute name='ocl_quote' />"
	+"    <attribute name='ocl_quantity' />"
	+"    <attribute name='ocl_defaultprice'/>"
	+"    <attribute name='ocl_overriddenprice'/>"
	+"    <attribute name='ocl_description' />"
	+"    <order attribute='ocl_name' descending='false' />"
	+"    <filter type='and'>"
	+"      <condition attribute='ocl_quote' operator='eq' value='"+id+"' />"
	+"    </filter>"
	+"  </entity>"
	+"</fetch>";


	var results = null

	try {
		results = XrmServiceToolkit.Soap.Fetch(fetch);

	} catch (e) {
		results = new Object();
	}

	return results;
}

function setPotentialCustomer()
{
	var opportunity = Xrm.Page.getAttribute("opportunityid");

	if (opportunity != null && opportunity.getValue() != null ) 
	{
		var potentialCustomer = Xrm.Page.getAttribute("customerid");

		if (potentialCustomer != null && potentialCustomer.getValue()!= null) 
		{
			return;
		}
		else
		{				
			var customerFromOpp = getCustomerFromOpportunity(opportunity.getValue()[0].id);
			if (customerFromOpp != null)
			{
				potentialCustomer.setValue(customerFromOpp);
				potentialCustomer.setSubmitMode("always");
				Xrm.Page.data.entity.save();
			}
		}
	}
}
function setPriceList()
{	
	var priceList = Xrm.Page.getAttribute("pricelevelid");

	if (priceList != null && priceList.getValue()!= null) 
	{
		priceList.setSubmitMode("always");
		Xrm.Page.data.entity.save();
	}
	else
	{				
		var defaultPriceList = getPriceList();
		if (defaultPriceList != null)
		{
			priceList.setValue(defaultPriceList);
			priceList.setSubmitMode("always");
			Xrm.Page.data.entity.save();
		}

	}
}

function getCustomerFromOpportunity(opp)
{
	var fetch = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true' no-lock='true'>"+
	"  <entity name='account'>"+
	"    <attribute name='name' />"+
	"    <attribute name='accountid' />"+
	"    <order attribute='name' descending='false' />"+
	"    <link-entity name='opportunity' from='parentaccountid' to='accountid' alias='aa'>"+
	"      <filter type='and'>"+
	"        <condition attribute='opportunityid' operator='eq' value='"+opp+"' />"+
	"      </filter>"+
	"    </link-entity>"+
	"  </entity>"+
	"</fetch>";


	var results = null
	try {
		results = XrmServiceToolkit.Soap.Fetch(fetch);

		if (results.length > 0) {
			var lookupItem = new Object();
			lookupItem.id = results[0].id;
			lookupItem.name = results[0].attributes.name.value;
			lookupItem.entityType = results[0].logicalName;

			var acc = new Array();
			acc[0] = lookupItem;
			return acc;
		}
		else return null;

	} catch (e) {
		return null;
	}
}
function getPriceList()
{
	var fetch = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' no-lock='true'>"
+"  <entity name='pricelevel'>"
+"    <attribute name='name' />"
+"    <attribute name='pricelevelid' />"	
+"      <filter type='and'>"
+"        <condition attribute='name' operator='eq' value='OpenCell Default Price List' />"
+"      </filter>"
+"  </entity>"
+"</fetch>";


	var results = null
	try {
		results = XrmServiceToolkit.Soap.Fetch(fetch);

		if (results.length > 0) {
			var lookupItem = new Object();
			lookupItem.id = results[0].id;
			lookupItem.name = results[0].attributes.name.value;
			lookupItem.entityType = results[0].logicalName;

			var acc = new Array();
			acc[0] = lookupItem;
			return acc;
		}
		else return null;

	} catch (e) {
		return null;
	}
}
function formOnLoad()
{
	Xrm.Page.getAttribute("pricelevelid").setSubmitMode("always");
	Xrm.Page.getAttribute("customerid").setSubmitMode("always");
	formVisibilityRules();


	var formType = Xrm.Page.ui.getFormType();
	if (formType == 3 || formType == 4)
		return;

	setProcessStep();
	//addProcessOnStateChange();
}

function formVisibilityRules()
{
	var flag = Xrm.Page.getAttribute("ocl_quotecreationprocessfinished").getValue();
	if (flag) 
	{
		Xrm.Page.ui.tabs.get("Summary_tab").setVisible(true);
		Xrm.Page.ui.tabs.get("tab_CreateQuotation").setVisible(false);
	}
	else
	{
		Xrm.Page.ui.tabs.get("Summary_tab").setVisible(false);
		Xrm.Page.ui.tabs.get("tab_CreateQuotation").setVisible(true);
	}

	Xrm.Page.ui.clearFormNotification();
}

function getDirtyFields()
{
	var attributes = Xrm.Page.getAttribute();
	for (var i in attributes)
	{
		var attribute = attributes[i];
		if (attribute.getIsDirty()){
			console.log("attribute dirty: " + attribute.getName());
			attribute.setSubmitMode("always");
		}
	}	
}

function InvokeGlobalAction(actionLogicalName, OKMessage, errorMessage, params) {
	var parameters ="";
	if (params) {
		if (typeof(params) == "object") 
		{
			if (params.id && params.logicalName) 
			{
				parameters +="<a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
				parameters += "          <a:KeyValuePairOfstringanyType>";
				parameters += "            <b:key>"+params.name+"</b:key>";
				parameters += "            <b:value i:type=\"a:EntityReference\">";
				parameters += "               <a:Id>" + params.id + "</a:Id>";
				parameters += "               <a:LogicalName>" + params.logicalName + "</a:LogicalName>";
				parameters += "               <a:Name i:nil=\"true\" />";
				parameters += "            </b:value>";
				parameters += "          </a:KeyValuePairOfstringanyType>";
				parameters += "        </a:Parameters>";
			}
			else if (params.length > 0) 
			{
				parameters +="<a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
				for (var i = 0, len = params.length; i < len; i++) {
					parameters += "          <a:KeyValuePairOfstringanyType>";
					parameters += "            <b:key>"+params[i].name+"</b:key>";
					parameters += "            <b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">" + params[i].value + "</b:value>";
					parameters += "          </a:KeyValuePairOfstringanyType>";
				}	
				parameters += "        </a:Parameters>";		
			}
		}
		else if(typeof(params) == "string")
		{
			parameters +="<a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
			parameters += "          <a:KeyValuePairOfstringanyType>";
			parameters += "            <b:key>"+params.name+"</b:key>";
			parameters += "            <b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">" + params.value + "</b:value>";
			parameters += "          </a:KeyValuePairOfstringanyType>";
			parameters += "        </a:Parameters>";
		}
	}

	var context = window.parent.Xrm.context;
	var rawError;
	var url = Xrm.Page.context.getClientUrl()
	var OrgServicePath = "/XRMServices/2011/Organization.svc/web";
	url += OrgServicePath;

	var request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
	"<s:Body>" +
	"<Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">" +
	"<request xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">" + parameters+
	"<a:RequestId i:nil=\"true\" />" +
	"<a:RequestName>" + actionLogicalName + "</a:RequestName>" +
	"</request>" +
	"</Execute>" +
	"</s:Body>" +
	"</s:Envelope>";

	var req = new XMLHttpRequest();
	req.open("POST", url, false)

    // Responses will return XML.
    req.setRequestHeader("Accept", "application/xml, text/xml, */*");
    req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");

    req.send(request);
    req.responseXML;

    if (req.statusText == "OK" && OKMessage != null) {

        //Xrm.Utility.alertDialog(OKMessage);
        var response = null;
        if (req.responseXML.getElementsByTagName("a:KeyValuePairOfstringanyType").length > 0)
        	response = req.responseXML.getElementsByTagName("a:KeyValuePairOfstringanyType")[0].childNodes[1].textContent;
        else if(req.responseXML.getElementsByTagName("KeyValuePairOfstringanyType").length > 0)
        	response = req.responseXML.getElementsByTagName("KeyValuePairOfstringanyType")[0].childNodes[1].textContent;    

       // Xrm.Page.getAttribute("ocl_webserviceresponse").setValue(response);
       return response;
        //Xrm.Page.data.refresh(false);
    }
    else if (errorMessage != null) {
    	if (req.responseXML.getElementsByTagName("Message").length > 0) {
    		rawError = req.responseXML.getElementsByTagName("Message")[0].textContent;
    	}

        //Xrm.Utility.alertDialog(errorMessage + "\n" + "Error Details: " + rawError);
        Xrm.Utility.alertDialog(rawError);
    }
}