var app = angular.module('mobile-grid', ['ui.bootstrap', 'ngResource']);
var CRMServerUrl = GetGlobalContext().getClientUrl().replace(/:/g, "\\:");
var crmServerUrlSoap = GetGlobalContext().getClientUrl();
//var crmServerUrlSoap = "http://mum-crm-017:5555/RecordClone-Test"
var settings = [];

//CRUD service for creating case email feed in CRM
app.factory('CaseEmailFeedsService', ['$http', '$q', function ($http, $q) {
    var activities = [];
    var counter = 0, count = 0;

    function generateSOAPRequest(caseGuid) {
        var sFetchXml = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">' +
  '<entity name="iotap_caseemailfeeds">' +
    '<attribute name="iotap_caseemailfeedsid" />' +
    '<attribute name="iotap_description" />' +
    '<attribute name="iotap_caseguid" />' +
    '<attribute name="iotap_attachmentids" />' +
    '<attribute name="iotap_directioncode" />' +
    '<attribute name="iotap_entitytypecode" />' +
    '<attribute name="iotap_fromemailid" />' +
    '<attribute name="iotap_actualenddate" />' +
    '<attribute name="iotap_toemailids" />' +
    '<attribute name="iotap_ccemailids" />' +
    '<attribute name="iotap_subject" />' +
    '<attribute name="iotap_emailguid" />' +
    '<attribute name="iotap_filenames" />' +
    '<attribute name="iotap_public" />' +
    '<attribute name="iotap_public" />' +
    '<attribute name="iotap_customername" />' +
    '<order attribute="iotap_sortbydate" descending="true" />' +
    '<filter type="and">' +
      '<condition attribute="iotap_caseguid" operator="eq" value="' + caseGuid + '" />' +
    '</filter>' +
  '</entity>' +
'</fetch>';

        var request = '<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">' +
    '<s:Body>' +
    '<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services">' +
    '<request i:type="b:RetrieveMultipleRequest" ' +
    ' xmlns:b="http://schemas.microsoft.com/xrm/2011/Contracts" ' +
    ' xmlns:i="http://www.w3.org/2001/XMLSchema-instance">' +
    '<b:Parameters xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic">' +
    '<b:KeyValuePairOfstringanyType>' +
        '<c:key>Query</c:key>' +
        '<c:value i:type="b:FetchExpression">' +
            '<b:Query>';
        request += CrmEncodeDecode.CrmXmlEncode(sFetchXml);
        request += '</b:Query>' +
    '</c:value>' +
    '</b:KeyValuePairOfstringanyType>' +
    '</b:Parameters>' +
    '<b:RequestId i:nil="true"/>' +
    '<b:RequestName>RetrieveMultiple</b:RequestName>' +
    '</request>' +
    '</Execute>' +
    '</s:Body></s:Envelope>';
        return request;
    }

    function handleActivities(data) {
        if (window.DOMParser) {
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(data, "text/xml");
        }
        else // Internet Explorer
        {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = false;
            xmlDoc.loadXML(data);
        }

        var displayData = settings;

        var getData = [];
        var description = "";
        var attachmentIds = "", fromEmailId, toEmailIds = "", subject = "", ccEmailIds = "", inBoundFrom = "", caseEmailFeedGuid = "", entityTypeCode = "",
            inBoundToCc = "", outBoundFrom = "", outBoundToCc = "", emailGuid = "", fileNames = "", dateFormat = "", collapseLineBreaks = "", directionCode = "", selected = "", fullnameFrom = "", customerName;

        var sortByDate = new Date();

        var Entities = (navigator.appName == "Netscape" && (navigator.vendor == "Google Inc." || navigator.vendor == "Apple Computer, Inc.")) ? xmlDoc.getElementsByTagName("Entities")[0].childNodes : xmlDoc.getElementsByTagName("a:Entities")[0].childNodes;
        for (j = 0; j < Entities.length; j++) {
            var getEntity = (navigator.appName == "Netscape" && (navigator.vendor == "Google Inc." || navigator.vendor == "Apple Computer, Inc.")) ? xmlDoc.getElementsByTagName("Entity") : xmlDoc.getElementsByTagName("a:Entity");
            for (i = 0; i <= getEntity[j].childNodes[0].childNodes.length - 1; i++) {
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_caseemailfeedsid")
                    caseEmailFeedGuid = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_directioncode")
                    directionCode = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_entitytypecode")
                    entityTypeCode = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_description")
                    description = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_attachmentids")
                    attachmentIds = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_filenames")
                    fileNames = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_fromemailid")
                    fromEmailId = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_toemailids")
                    toEmailIds = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_subject")
                    subject = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_ccemailids")
                    ccEmailIds = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_sortbydate")
                    sortByDate = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_emailguid")
                    emailGuid = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_public")
                    selected = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent == "true" ? true : false;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_customername")
                    customerName = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;

            }


            inBoundFrom = settings[0].InboundFrom;
            inBoundToCc = settings[0].InboundToCc;
            outBoundFrom = settings[0].OutboundFrom;
            outBoundToCc = settings[0].OutboundToCc;
            dateFormat = settings[0].DateFormat;
            collapseLineBreaks = settings[0].CollapseLineBreaks;
            fullnameFrom = settings[0].FullnameFrom;

            var url = crmServerUrlSoap;

            description = description.replace(/\n\s*\n/g, '\n');
            var attachments = [], fileName = [];
            attachments = attachmentIds.split(';', attachmentIds.split(';').length - 1);
            fileName = fileNames.split(';', fileNames.split(';').length - 1);

            if (fullnameFrom == "true" && customerName != null && customerName != " ")
                fromEmailId = "From :" + customerName + " " + "<" + fromEmailId + ">";
                //fromEmailId = customerName;
            else if (fullnameFrom == "true" && customerName == null && customerName == " ")
                fromEmailId = "From :" + fromEmailId;
                //fromEmailId = fromEmailId;
            else {
                fromEmailId = "From :" + fromEmailId;
            }

            toEmailIds = "To :" + toEmailIds;
            ccEmailIds = "Cc :" + ccEmailIds;

            var date = new Date(sortByDate);
            date = date.toLocaleString().replace(/:\d{2}\s/, ' ');

            this.repeatAttachments = fileName.map(function (fileName, index) {
                return {
                    data: fileName,
                    value: attachments[index]
                }
            });

            if (directionCode == "Incoming" && inBoundFrom == "true") {
                if (inBoundToCc == "true") {
                    var result =
                        {
                            Url: url,
                            CaseEmailFeedGuid: caseEmailFeedGuid,
                            EntityTypeCode: entityTypeCode,
                            Description: description,
                            AttachmentIds: attachments,
                            FromEmailId: fromEmailId,
                            ToEmailIds: toEmailIds,
                            Subject: subject,
                            ActualEndDate: date,
                            EmailGuid: emailGuid,
                            FileNames: fileName,
                            RepeatAttachments: repeatAttachments,
                            Selected: selected,
                            DirectionCode: directionCode
                        };
                }
                else {
                    var result =
                        {
                            Url: url,
                            CaseEmailFeedGuid: caseEmailFeedGuid,
                            EntityTypeCode: entityTypeCode,
                            Description: description,
                            AttachmentIds: attachments,
                            FromEmailId: fromEmailId,
                            Subject: subject,
                            ActualEndDate: date,
                            EmailGuid: emailGuid,
                            FileNames: fileName,
                            RepeatAttachments: repeatAttachments,
                            Selected: selected,
                            DirectionCode: directionCode
                        };
                }
            }
            if (directionCode == "Outgoing" && outBoundToCc == "true") {
                if (outBoundFrom == "true") {
                    var result =
                        {
                            Url: url,
                            CaseEmailFeedGuid: caseEmailFeedGuid,
                            EntityTypeCode: entityTypeCode,
                            Description: description,
                            AttachmentIds: attachments,
                            FromEmailId: fromEmailId,
                            ToEmailIds: toEmailIds,
                            Subject: subject,
                            ActualEndDate: date,
                            EmailGuid: emailGuid,
                            FileNames: fileName,
                            RepeatAttachments: repeatAttachments,
                            Selected: selected,
                            DirectionCode: directionCode
                        };
                }
                else {
                    var result =
                        {
                            Url: url,
                            CaseEmailFeedGuid: caseEmailFeedGuid,
                            EntityTypeCode: entityTypeCode,
                            Description: description,
                            AttachmentIds: attachments,
                            ToEmailIds: toEmailIds,
                            Subject: subject,
                            ActualEndDate: date,
                            EmailGuid: emailGuid,
                            FileNames: fileName,
                            RepeatAttachments: repeatAttachments,
                            Selected: selected,
                            DirectionCode: directionCode
                        };
                }
            }
            counter++;
            activities.push(result);
        }
        return activities;
    }

    function removeProgressBar() {
        angular.element(document.getElementById("divProgress")).remove();
        count = 0;
        setTimeout(document.location.reload(true), 20);
    }

    return {
        index: function (caseNumber, settings) {
            var xml = generateSOAPRequest(caseNumber);
            var url = crmServerUrlSoap + "/XRMServices/2011/Organization.svc/web";
            CRUDOperations('POST', $http, url, xml, retrieveHeaders(), handleActivities, 0);
            //counter = quoteLines.length;
            return activities;
        }
    }
}]);

app.factory('CaseEmailFeedsDisplayService', ['$http', '$q', 'Headers', function ($http, $q, Headers) {
    //var settings = [];
    var counter = 0, count = 0;
    var deferred = $q.defer();

    function generateSOAPRequestForDisplaySettings() {
        var sFetchXml = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">' +
  '<entity name="iotap_emailfeedsdisplaysetting">' +
   '<attribute name="iotap_emailfeedsdisplaysettingid" />' +
    '<attribute name="iotap_name" />' +
    '<attribute name="createdon" />' +
    '<attribute name="iotap_outboundemailtocheck" />' +
    '<attribute name="iotap_outboundemailfromcheck" />' +
    '<attribute name="iotap_inboundemailfromcheck" />' +
    '<attribute name="iotap_inboundemailtocheck" />' +
    '<attribute name="iotap_dateformat" />' +
    '<attribute name="iotap_collapsewhitespacecheck" />' +
    '<attribute name="iotap_fullnamefrom" />' +
    '<order attribute="iotap_name" descending="false" />' +
  '</entity>' +
'</fetch>';

        var request = '<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">' +
    '<s:Body>' +
    '<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services">' +
    '<request i:type="b:RetrieveMultipleRequest" ' +
    ' xmlns:b="http://schemas.microsoft.com/xrm/2011/Contracts" ' +
    ' xmlns:i="http://www.w3.org/2001/XMLSchema-instance">' +
    '<b:Parameters xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic">' +
    '<b:KeyValuePairOfstringanyType>' +
        '<c:key>Query</c:key>' +
        '<c:value i:type="b:FetchExpression">' +
            '<b:Query>';
        request += CrmEncodeDecode.CrmXmlEncode(sFetchXml);
        request += '</b:Query>' +
    '</c:value>' +
    '</b:KeyValuePairOfstringanyType>' +
    '</b:Parameters>' +
    '<b:RequestId i:nil="true"/>' +
    '<b:RequestName>RetrieveMultiple</b:RequestName>' +
    '</request>' +
    '</Execute>' +
    '</s:Body></s:Envelope>';
        return request;
    }

    function handleSettings(data) {
        if (window.DOMParser) {
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(data, "text/xml");
        }
        else // Internet Explorer
        {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = false;
            xmlDoc.loadXML(data);
        }

        var getData = [];
        var dateFormat = "", createdOn = "", inBoundFrom = "", inBoundToCc = "", outBoundFrom = "", outBoundToCc = "", collapseLineBreaks = "", fullnameFrom = "";
        var Entities = (navigator.appName == "Netscape" && (navigator.vendor == "Google Inc." || navigator.vendor == "Apple Computer, Inc.")) ? xmlDoc.getElementsByTagName("Entities")[0].childNodes : xmlDoc.getElementsByTagName("a:Entities")[0].childNodes;
        for (j = 0; j < Entities.length; j++) {
            var getEntity = (navigator.appName == "Netscape" && (navigator.vendor == "Google Inc." || navigator.vendor == "Apple Computer, Inc.")) ? xmlDoc.getElementsByTagName("Entity") : xmlDoc.getElementsByTagName("a:Entity");
            for (i = 0; i <= getEntity[j].childNodes[0].childNodes.length - 1; i++) {
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_dateformat")
                    dateFormat = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "createdon")
                    createdOn = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_inboundemailfromcheck")
                    inBoundFrom = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_inboundemailtocheck")
                    inBoundToCc = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_outboundemailfromcheck")
                    outBoundFrom = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_outboundemailtocheck")
                    outBoundToCc = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_collapsewhitespacecheck")
                    collapseLineBreaks = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;

                if (getEntity[j].childNodes[0].childNodes[i].childNodes[0].textContent == "iotap_fullnamefrom")
                    fullnameFrom = getEntity[j].childNodes[0].childNodes[i].childNodes[1].textContent;
            }

            var result =
              {
                  DateFormat: dateFormat,
                  CreatedOn: createdOn,
                  InboundFrom: inBoundFrom,
                  InboundToCc: inBoundToCc,
                  OutboundFrom: outBoundFrom,
                  OutboundToCc: outBoundToCc,
                  CollapseLineBreaks: collapseLineBreaks,
                  FullnameFrom: fullnameFrom

              };
            counter++;

            settings.push(result);
        }
        // angular.element( document.getElementById( "divProgress" ) ).remove();
        deferred.resolve(settings);
    }

    return {
        get: function () {
            var xml = generateSOAPRequestForDisplaySettings();
            //var xml = successFn;
            var url = crmServerUrlSoap + "/XRMServices/2011/Organization.svc/web";
            //CRUDOperations('POST', $http, url, xml, retrieveHeaders(), handleSettings, 0);
            CRUDOperations('POST', $http, url, xml, Headers.retrieveHeader(), handleSettings, 0);
            //counter = quoteLines.length;
            return deferred.promise;
        },

        setPublicValueService: function (cbValue, updateid) {
            var checked = document.getElementById("ch" + updateid).checked;
            //var serverUrl = GetGlobalContext().getServerUrl();
            var serverUrl = crmServerUrlSoap;
            if (serverUrl.match("//$/")) {
                serverUrl = serverUrl.substring(0, serverUrl.length - 1);
            }
            var Soap = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>" +
                        "<s:Body>" +
                        "<Update xmlns='http://schemas.microsoft.com/xrm/2011/Contracts/Services' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
                        "<entity xmlns:a='http://schemas.microsoft.com/xrm/2011/Contracts'>" +
                        "<a:Attributes xmlns:b='http://schemas.datacontract.org/2004/07/System.Collections.Generic'>" +
                        "<a:KeyValuePairOfstringanyType>" +
                        "<b:key>iotap_public</b:key>" +
                        "<b:value i:type='c:boolean' xmlns:c='http://www.w3.org/2001/XMLSchema'>" + cbValue + "</b:value>" +
                        "</a:KeyValuePairOfstringanyType>" +
                        "</a:Attributes>" +
                        "<a:EntityState i:nil='true' />" +
                        "<a:FormattedValues xmlns:b='http://schemas.datacontract.org/2004/07/System.Collections.Generic' />" +
                        "<a:Id>" + updateid + "</a:Id>" +
                        "<a:LogicalName>iotap_caseemailfeeds</a:LogicalName>" +
                        "<a:RelatedEntities xmlns:b='http://schemas.datacontract.org/2004/07/System.Collections.Generic' />" +
                        "</entity>" +
                        "</Update>" +
                        "</s:Body>" +
                        "</s:Envelope>";
            var req = new XMLHttpRequest();
            req.open("POST", serverUrl + "/XRMServices/2011/Organization.svc/web", false)
            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/Update");
            req.send(Soap);
        },

        DeleteFeedService: function (deleteid) {
            //var serverUrl = GetGlobalContext().getServerUrl();
            var serverUrl = crmServerUrlSoap;
            if (serverUrl.match("//$/")) {
                serverUrl = serverUrl.substring(0, serverUrl.length - 1);

            }

            var Soap = " <s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>" +
                        "<s:Body>" +
                        "<Delete xmlns='http://schemas.microsoft.com/xrm/2011/Contracts/Services' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>" +
                        "<entityName>iotap_caseemailfeeds</entityName>" +
                        "<id>" + deleteid + "</id>" +
                        "</Delete>" +
                        "</s:Body>" +
                        "</s:Envelope>";

            var req = new XMLHttpRequest();
            req.open("POST", serverUrl + "/XRMServices/2011/Organization.svc/web", false)
            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/Delete");
            req.send(Soap);
        }

    }
}]);

function CRUDOperations(method, $http, url, data, headers, successFn, c) {
    var count = c || 0;
    $http({
        method: method,
        async: false,
        url: url,
        data: data,
        headers: headers
    }).success(successFn).error(function () {
        if (count < 15) {
            var newCount = count + 1;
            setTimeout(CRUDOperations, 50, method, $http, url, data, headers, successFn, newCount);
        }
    });
};

//Header to retrieve the records from CRM
function retrieveHeaders() {
    return {
        'Accept': '"application/xml, text/xml, */*"',
        'Content-Type': 'text/xml; charset=utf-8',
        'X-HTTP-Method': 'MERGE',
        'SOAPAction': "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute"
    }
};

app.factory('Headers', function () {
    return {
        retrieveHeader: function () {//soap headers for retrieve
            return {
                'Accept': '"application/xml, text/xml, */*"',
                'Content-Type': 'text/xml; charset=utf-8',
                'X-HTTP-Method': 'MERGE',
                'SOAPAction': "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute"
            }
        },
        createHeader: function () {//soap headers for create
            return {
                'Accept': '"application/soap+xml,text/xml, */*"',
                'Content-Type': 'text/xml; charset=utf-8',
                'SOAPAction': "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Create"
            }
        },
        updateHeader: function () {// soap headers for update
            return {
                'Accept': '"application/soap+xml,text/xml, */*"',
                'Content-Type': 'text/xml; charset=utf-8',
                'SOAPAction': "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Update"
            }
        },
        deleteHeader: function () {//soap headers for delete
            return {
                'Accept': '"application/soap+xml,text/xml, */*"',
                'Content-Type': 'text/xml; charset=utf-8',
                'SOAPAction': "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Delete"
            }
        }
    }
});

function odataH() {
    return {
        'Accept': 'application/json; odata=verbose',
        'Content-Type': 'application/json; odata=verbose'
    }
};

function StripHTML(html) {
    return html.replace(/<[^>]*>?/g, "");
}
