//Change the entity name below based on the Add-On adding comment for test
var addOnPrefix = "iotap_e2cm";
var productName = "EmailToCase";
var SolutionName = "EmailToCase";
var iframeURL = "";
//var LicensingURL = "https://demo.iotap.com:8081/LicensingServiceStaging/Licensing.svc";
var LicensingURL = "https://iotap-licensing.azurewebsites.net/Licensing.svc";
var licenseId = null;
var ExpirationDate = null;
var envType = 0;
var depType = 0;
var company = null;
var jobTitle = null;
var now = Date.now();
var SolutionVersion = null;
var ServerVersion = null;
var SerialNo = null;
var LicensXML = null;
var TrialXML = null;
var ProfileXML = null;
var businessphone = null;
var mobilephone = null;
var email = null;
var website = null;
var fname = null;
var lname = null;
var activeusercount = null;
var islicenseexpired = null;
var IOTAPAddOnLicensing = {

    /* 
    * Displays a loading mesage to the user
    */
    ShowProgressBar: function () {
        document.getElementById("divLoading").style.display = "block";

    },

    /* 
    * Removes the loading mesage
    */
    RemoveProgressBar: function () {
        document.getElementById("divLoading").style.display = "none";
    },

    /* 
    * Retrieve the organization name & set into organization textbox.
    */
    GetOrgName: function () {
        return Xrm.Page.context.getOrgUniqueName();
    },

    /* 
    * Retrieve the number of active user count. Private functions
    */
    GetActiveUserCount: function () {
        var successFlag = false;
        XrmSvcToolkit.retrieveMultiple({
            entityName: "SystemUser",
            odataQuery: "?$select=SystemUserId&$filter=IsDisabled eq false",
            successCallback: function (result) {
                // Display no. of active user count by number of records fetched from odata.
                if (result.length > 0) {
                    $("#txtActualUserCount").val(result.length);
                    successFlag = true;
                }
            },
            errorCallback: function (error) {
                // Print complete response error output
                $("#lblSaveMessage").text(error);
            }
        });
        // Change label class to error if license is not successfully retrieved.
        if (!successFlag) {
            this.ChangeHtmlClassName('lblSaveMessage', 'licenseSaveMessage', 'licenseErrorMessage');
        }
    },

    /* 
    * Retrieve the company related information. Private functions
    */
    GetUserInfo: function () {
        var successFlag = false;
        var userId = Xrm.Page.context.getUserId();
        XrmSvcToolkit.retrieve({
            entityName: "SystemUser",
            id: userId,
            select: "Address1_Telephone1,FirstName,InternalEMailAddress,LastName,MobilePhone,Title",
            //odataQuery: "$select=Address1_Telephone1,FirstName,InternalEMailAddress,LastName,MobilePhone,Title&$filter=guid('" + userId + "')",
            successCallback: function (result) {
                // If record found then show user details in relevant controls
                if (result != null) {

                    //$("#txtCompany").val(result.Company);

                    $("#txtFirstName").val(fname ? fname : result.FirstName);
                    $("#txtLastName").val(lname ? lname : result.LastName);
                    $("#txtBusinessPhone").val(businessphone ? businessphone : result.Address1_Telephone1);
                    $("#txtMobilePhone").val(mobilephone ? mobilephone : result.MobilePhone);
                    $("#txtEmail").val(email ? email : result.InternalEMailAddress);
                    $("#txtWebsite").val(website ? website : result.Website);
                    // If website property is not in result then read the website name from email id after @.
                    if (website = "" || website == null || website == true) {
                        if (!result.Website && result.InternalEMailAddress) {
                            var emailId = $("#txtEmail").val();
                            var atSignIndex = emailId.indexOf("@");
                            var webSite = "www." + emailId.substring(atSignIndex + 1, emailId.length);
                            $("#txtWebsite").val(webSite);
                        } else
                            $("#txtWebsite").val(result.Website);
                    }

                    successFlag = true;
                }
            },
            errorCallback: function (error) {
                // Print complete response error output
                $("#lblSaveMessage").text(error);
            }
        });
        // Change label class to error if user info are not successfully retrieved.
        if (!successFlag) {
            this.ChangeHtmlClassName('lblSaveMessage', 'licenseSaveMessage', 'licenseErrorMessage');
        }
    },

    /* 
    * Retrieve the number of license activated count. If greater than 1 then hide the trial activation button from page.
    */
    HideTrialActivationButton: function () {
        var successFlag = false;
        XrmSvcToolkit.retrieveMultiple({
            entityName: addOnPrefix + "_license",
            odataQuery: "?$select=" + addOnPrefix + "_license" + "Id",
            successCallback: function (result) {
                // If count is greater than 1 then hide the trial activation button from page.
                if (result.length > 0) {
                    $("#btnSaveTrial").hide();
                    $("#btnUpdateProfile").show();
                    $("#trEULA").hide();
                    licenseId = result.d;
                    $("#btnRefreshLicense").show();
                    successFlag = true;
                }
            },
            errorCallback: function (error) {
                // Print complete response error output
                $("#lblSaveMessage").text(error);
            }
        });
        // Change label class to error if license is not successfully retrieved.
        if (!successFlag) {
            this.ChangeHtmlClassName('lblSaveMessage', 'licenseSaveMessage', 'licenseErrorMessage');
        }
    },
    /* 
    * Create trial xml object in a string. Private functions
    * sets TrialXML string
    */
    CreateTrialXML: function () {
        TrialXML = "<trialactivation>"
                                            + "<organizationname>" + $("#txtOrgName").val() + "</organizationname>"
                                            + "<actualusercount>" + $("#txtActualUserCount").val() + "</actualusercount>"
                                            + "<environmenttype>" + $("#drpEnvironmentType").val() + "</environmenttype>"
                                            + "<deploymenttype>" + $("#drpDeploymentType").val() + "</deploymenttype>"
                                            + "<firstname>" + $("#txtFirstName").val() + "</firstname>"
                                            + "<lastname>" + $("#txtLastName").val() + "</lastname>"
                                            + "<company>" + $("#txtCompany").val() + "</company>"
                                            + "<jobtitle>" + $("#txtJobTitle").val() + "</jobtitle>"
                                            + "<businessphone>" + $("#txtBusinessPhone").val() + "</businessphone>"
                                            + "<mobilephone>" + $("#txtMobilePhone").val() + "</mobilephone>"
                                            + "<email>" + $("#txtEmail").val() + "</email>"
                                            + "<website>" + $("#txtWebsite").val() + "</website>"
                                            + "<productname>" + productName + "</productname>"
                                            + "<version>" + SolutionVersion + "</version>"
                                        + "</trialactivation>";
    },
    /* 
    * Create trial xml object in a string. Private functions
    * sets TrialXML string
    */
    CreateProfileXML: function () {
        ProfileXML = "<profile>"
                    + "<environmenttype>" + $("#drpEnvironmentType").val() + "</environmenttype>"
                    + "<deploymenttype>" + $("#drpDeploymentType").val() + "</deploymenttype>"
                    + "<firstname>" + $("#txtFirstName").val() + "</firstname>"
                    + "<lastname>" + $("#txtLastName").val() + "</lastname>"
                    + "<company>" + $("#txtCompany").val() + "</company>"
                    + "<jobtitle>" + $("#txtJobTitle").val() + "</jobtitle>"
                    + "<businessphone>" + $("#txtBusinessPhone").val() + "</businessphone>"
                    + "<mobilephone>" + $("#txtMobilePhone").val() + "</mobilephone>"
                    + "<email>" + $("#txtEmail").val() + "</email>"
                    + "<website>" + $("#txtWebsite").val() + "</website>"
                    + "<serialno>" + $("#txtSerialNo").val() + "</serialno>"
                    + "</profile>";

    },
    /* 
    * Create license xml object in a string. Private functions
    * @returns auto activation object which contains user information in xml string form.
    */
    CreateLicenseXmlObject: function (XML) {
        var xmlObj = IOTAPAddOnLicensing.loadXMLString(XML.replace(/^\s+|\s+$/g, ''));
        var ExpiryDate = xmlObj.getElementsByTagName('expirydate')[0].firstChild.nodeValue;
        var LicenseType = xmlObj.getElementsByTagName('licensetype')[0].firstChild.nodeValue;
        var SerialNo = xmlObj.getElementsByTagName('licenseid')[0].firstChild.nodeValue;
        var version = xmlObj.getElementsByTagName('version')[0].firstChild.nodeValue
        var objTrialAutoActivation = {};
        objTrialAutoActivation["iotap_licensename"] = productName + "_license";
        if ($("#txtOrgName").val() != "") { objTrialAutoActivation["iotap_organizationname"] = $("#txtOrgName").val(); }
        if ($("#txtActualUserCount").val() != "") { objTrialAutoActivation["iotap_actualusercount"] = $("#txtActualUserCount").val(); }
        if ($("#drpEnvironmentType").val() != 0) { objTrialAutoActivation["iotap_environmenttype"] = { Value: parseInt($("#drpEnvironmentType").val()) }; }
        if ($("#drpDeploymentType").val() != 0) { objTrialAutoActivation["iotap_deploymenttype"] = { Value: parseInt($("#drpDeploymentType").val()) }; }
        if ($("#txtFirstName").val() != "") { objTrialAutoActivation["iotap_firstname"] = $("#txtFirstName").val(); }
        if ($("#txtLastName").val() != "") { objTrialAutoActivation["iotap_lastname"] = $("#txtLastName").val(); }
        if ($("#txtCompany").val() != "") { objTrialAutoActivation["iotap_company"] = $("#txtCompany").val(); }
        if ($("#txtJobTitle").val() != "") { objTrialAutoActivation["iotap_jobtitle"] = $("#txtJobTitle").val(); }
        if ($("#txtBusinessPhone").val() != "") { objTrialAutoActivation["iotap_businessphone"] = $("#txtBusinessPhone").val(); }
        if ($("#txtMobilePhone").val() != "") { objTrialAutoActivation["iotap_mobilephone"] = $("#txtMobilePhone").val(); }
        if ($("#txtEmail").val() != "") { objTrialAutoActivation["iotap_email"] = $("#txtEmail").val(); }
        if ($("#txtWebsite").val() != "") { objTrialAutoActivation["iotap_website"] = $("#txtWebsite").val(); }
        objTrialAutoActivation["iotap_licensexml"] = XML;
        objTrialAutoActivation["iotap_licenseenddate"] = ExpirationDate;
        objTrialAutoActivation["iotap_firstactivationdate"] = IOTAPAddOnLicensing.ConvertDate(now);
        objTrialAutoActivation["iotap_licensestartdate"] = IOTAPAddOnLicensing.ConvertDate(now);
        objTrialAutoActivation["iotap_licensetype"] = { Value: parseInt(LicenseType) };
        objTrialAutoActivation["iotap_SerialNo"] = SerialNo;
        objTrialAutoActivation["iotap_version"] = version;
        if (TrialXML != null) objTrialAutoActivation["iotap_trialactivationxml"] = TrialXML;

        var datpart = ExpiryDate.split('-');
        ExpirationDate = new Date(datpart[0], datpart[1] - 1, datpart[2]);
        IOTAPAddOnLicensing.SetLicenseType(LicenseType)
        return objTrialAutoActivation;
    },

    loadXMLString: function (txt) {
        if (window.DOMParser) {
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(txt, "text/xml");
        }
        else // code for IE
        {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = false;
            xmlDoc.loadXML(txt);
        }
        return xmlDoc;
    },
    /* 
    * Update license xml object in a string. Private functions
    * @returns auto activation object which contains user information in xml string form.
    */
    UpdateCreateLicenseXmlObject: function (XML) {
        var xmlObj = IOTAPAddOnLicensing.loadXMLString(XML.replace(/^\s+|\s+$/g, ''));
        var newExpiryDate = xmlObj.getElementsByTagName('expirydate')[0].firstChild.nodeValue;
        var LicenseType = xmlObj.getElementsByTagName('licensetype')[0].firstChild.nodeValue;
        var SerialNo = xmlObj.getElementsByTagName('licenseid')[0].firstChild.nodeValue;
        var version = xmlObj.getElementsByTagName('version')[0].firstChild.nodeValue;
        var islicenseexpired = xmlObj.getElementsByTagName('islicenseexpired')[0].firstChild.nodeValue;
        var objTrialAutoActivation = {
            iotap_licensexml: XML,
            iotap_licenseenddate: newExpiryDate,
            iotap_firstactivationdate: IOTAPAddOnLicensing.ConvertDate(now),
            iotap_licensestartdate: IOTAPAddOnLicensing.ConvertDate(now),
            iotap_licensetype: { Value: parseInt(LicenseType) },
            iotap_SerialNo: SerialNo,
            iotap_version: version,
            new_islicenseexpired: islicenseexpired,
            iotap_trialactivationxml: TrialXML
        };
        IOTAPAddOnLicensing.SetLicenseType(LicenseType)
        $("#txtLicense").val(XML);
        var datpart = newExpiryDate.split('-');
        ExpirationDate = new Date(datpart[0], datpart[1] - 1, datpart[2]);
        IOTAPAddOnLicensing.RefreshLicensfields();

        return objTrialAutoActivation;
    },
    /* 
    * Update license xml object in a string. Private functions
    * @returns UpdateProfileObject object which contains user information in xml string form.
    */
    UpdateProfileObject: function () {

        var objUserProfile = {
            iotap_environmenttype: { Value: parseInt($("#drpEnvironmentType").val()) },
            iotap_deploymenttype: { Value: parseInt($("#drpDeploymentType").val()) },
            iotap_firstname: $("#txtFirstName").val(),
            iotap_lastname: $("#txtLastName").val(),
            iotap_company: $("#txtCompany").val(),
            iotap_jobtitle: $("#txtJobTitle").val(),
            iotap_businessphone: $("#txtBusinessPhone").val(),
            iotap_mobilephone: $("#txtMobilePhone").val(),
            iotap_email: $("#txtEmail").val(),
            iotap_website: $("#txtWebsite").val()
        };


        return objUserProfile;
    },
    /* 
    * Creates client given information into xml & saves into trial activation license xml field. Private functions
    */
    CreateTrialActivation: function (XML) {
        var successFlag = false;
        XrmSvcToolkit.createRecord({
            entityName: addOnPrefix + "_license",
            entity: IOTAPAddOnLicensing.CreateLicenseXmlObject(XML),
            async: false,
            successCallback: function (result) {
                licenseId = eval("result." + addOnPrefix + "_license" + "Id");
                IOTAPAddOnLicensing.GetLicense();
                IOTAPAddOnLicensing.SetSuccessMSG("Your License has been activated successfully." + " Your license Expires on " + (ExpirationDate.getMonth() + 1) + "/" + ExpirationDate.getDate() + "/" + ExpirationDate.getFullYear() + ".");
                $("#btnSaveTrial").hide();
                IOTAPAddOnLicensing.RefreshLicensfields();
                //$("#txtEndDate").val(ExpirationDate);
            },
            errorCallback: function (error) {
                IOTAPAddOnLicensing.SetErrorMSG("Trial Activation failed : " + error);
            }
        });

    },

    /* 
    * Validate all controls in trial activation page. Will not allow to save until controls are validated.
    * @returns true if all controls are validated otherwise false.
    */
    ValidateTrialActivationControls: function () {
        var orgName = $.trim($("#txtOrgName").val());
        var activeUserCount = $.trim($("#txtActualUserCount").val());
        var environmentType = $.trim($("#drpEnvironmentType").val());
        var deploymentType = $("#drpDeploymentType").val();
        var firstName = $.trim($("#txtFirstName").val());
        var lastName = $.trim($("#txtLastName").val());
        var company = $.trim($("#txtCompany").val());
        var jobTitle = $.trim($("#txtJobTitle").val());
        var businessPhone = $.trim($("#txtBusinessPhone").val());
        var mobilePhone = $.trim($("#txtMobilePhone").val());
        var email = $.trim($("#txtEmail").val());
        var website = $.trim($("#txtWebsite").val());
        var eula = $("#chkEula").is(':checked');
        if (orgName == "") {
            IOTAPAddOnLicensing.SetErrorMSG("Organization Name cannot be blank", "#txtOrgName");
            return false;
        } else if (activeUserCount == "0" || activeUserCount == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Active User Count cannot be blank", "#txtActualUserCount");
            return false;
        } else if (environmentType == "0") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Environment Type cannot be blank", "#drpEnvironmentType");
            return false;
        } else if (deploymentType == "0") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Deployment Type cannot be blank", "#drpDeploymentType");
            return false;
        } else if (firstName == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("First Name cannot be blank", "#txtFirstName");
            return false;
        } else if (lastName == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Last Name cannot be blank", "#txtLastName");
            return false;
        } else if (company == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Company cannot be blank", "#txtCompany");
            return false;
        } else if (jobTitle == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Job Title cannot be blank", "#txtJobTitle");
            return false;
        } else if (businessPhone == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Business Phone cannot be blank", "#txtBusinessPhone");
            return false;
        } else if (businessPhone != "" && isNaN(businessPhone)) {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Business Phone can have only numeric numbers", "#txtBusinessPhone");
            return false;
        } else if (email == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Email cannot be blank", "#txtEmail");
            return false;
        } else if (website == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Website cannot be blank", "#txtWebsite");
            return false;
        }
        else if (eula == false) {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Please accept EULA to continue", "#chkEula");
            return false;
        }

        return true;
    },


    /* 
    * Validate all controls in trial activation page when updating the profile. Will not allow to save until controls are validated.
    * @returns true if all controls are validated otherwise false.
    */
    ValidateUpdateProfileControls: function () {
        var orgName = $.trim($("#txtOrgName").val());
        var activeUserCount = $.trim($("#txtActualUserCount").val());
        var environmentType = $.trim($("#drpEnvironmentType").val());
        var deploymentType = $("#drpDeploymentType").val();
        var firstName = $.trim($("#txtFirstName").val());
        var lastName = $.trim($("#txtLastName").val());
        var company = $.trim($("#txtCompany").val());
        var jobTitle = $.trim($("#txtJobTitle").val());
        var businessPhone = $.trim($("#txtBusinessPhone").val());
        var email = $.trim($("#txtEmail").val());
        var website = $.trim($("#txtWebsite").val());
        if (orgName == "") {
            IOTAPAddOnLicensing.SetErrorMSG("Organization Name cannot be blank", "#txtOrgName");
            return false;
        } else if (activeUserCount == "0" || activeUserCount == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Active User Count cannot be blank", "#txtActualUserCount");
            return false;
        } else if (environmentType == "0") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Environment Type cannot be blank", "#drpEnvironmentType");
            return false;
        } else if (deploymentType == "0") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Deployment Type cannot be blank", "#drpDeploymentType");
            return false;
        } else if (firstName == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("First Name cannot be blank", "#txtFirstName");
            return false;
        } else if (lastName == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Last Name cannot be blank", "#txtLastName");
            return false;
        } else if (company == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Company cannot be blank", "#txtCompany");
            return false;
        } else if (jobTitle == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Job Title cannot be blank", "#txtJobTitle");
            return false;
        } else if (businessPhone == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Business Phone cannot be blank", "#txtBusinessPhone");
            return false;
        } else if (businessPhone != "" && isNaN(businessPhone)) {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Business Phone can have only numeric numbers", "#txtBusinessPhone");
            return false;
        } else if (email == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Email cannot be blank", "#txtEmail");
            return false;
        } else if (website == "") {
            IOTAPAddOnLicensing.SetErrorMSGOnField("Website cannot be blank", "#txtWebsite");
            return false;
        }
        return true;
    },

    /* 
    * Method called on page onload
    */
    OnLoad: function () {

        //load images
        IOTAPAddOnLicensing.SetImages();
        //get Solution information to populate the form if activated
        //hide update profile button
        $("#btnUpdateProfile").hide();
        IOTAPAddOnLicensing.GetVersion();
        //Populate Activation Type
        IOTAPAddOnLicensing.GetLicense();
        //Update Expiration days left
        IOTAPAddOnLicensing.RefreshLicensfields();

        if (company != null) {
            $("#txtCompany").val(company);
            $("#txtCompany").show();
        }
        if (envType != 0) {
            $("#drpEnvironmentType").val(envType);
            $("#drpEnvironmentType").show();
        }
        if (depType != 0) {
            $("#drpDeploymentType").val(depType);
            $("#drpDeploymentType").show();
        }
        if (jobTitle != null) {
            $("#txtJobTitle").val(jobTitle);
            $("#txtJobTitle").show();
        }

        // Hide manual & auto activation controls by default.
        $("#lblManualActivationControls").hide();
        //Hide settings by default
        $("#lblSettingsControls").hide();
        // call action to populate Profile page
        IOTAPAddOnLicensing.OpenActivationLink();
        $("#lblAutoActivationControls").show();
        //hide settings controll
        $("#lblSettingsControls").hide();
        // Open manual activation controls if manual activation is clicked
        $("#lblManualActivationLink").click(function () {
            // Show progress bar
            IOTAPAddOnLicensing.ShowProgressBar();
            // Hide auto activation
            $("#lblAutoActivationControls").hide();
            //hide settings controll
            $("#lblSettingsControls").hide();
            //hide update profile button
            $("#btnUpdateProfile").hide();
            // Change manual activation class
            IOTAPAddOnLicensing.ChangeHtmlClassName('lblManualActivationLink', 'deActivatedLink', 'activatedLink')
            IOTAPAddOnLicensing.ChangeHtmlClassName('lblAutoActivationLink', 'activatedLink', 'deActivatedLink')
            IOTAPAddOnLicensing.ChangeHtmlClassName('lblSettingsControlsLink', 'activatedLink', 'deActivatedLink')
            $("#lblManualActivationControls").show();

            //Retrieves the License xml (if any)
            IOTAPAddOnLicensing.GetLicense();


        });
        // Open manual activation controls if manual activation is clicked
        $("#lblSettingsControlsLink").click(function () {
            // Show progress bar
            IOTAPAddOnLicensing.ShowProgressBar();
            $("#lblAutoActivationControls").hide();
            // Hide auto activation
            $("#lblManualActivationControls").hide();
            // Change manual activation class
            IOTAPAddOnLicensing.ChangeHtmlClassName('lblManualActivationLink', 'activatedLink', 'deActivatedLink')
            IOTAPAddOnLicensing.ChangeHtmlClassName('lblAutoActivationLink', 'activatedLink', 'deActivatedLink')
            IOTAPAddOnLicensing.ChangeHtmlClassName('lblSettingsControlsLink', 'deActivatedLink', 'activatedLink')
            $("#lblSettingsControls").show();
            //Set the ifram source 
            jQuery("#iframe").attr('src', iframeURL);

            IOTAPAddOnLicensing.RemoveProgressBar();

        });
        // Auto activation : Open auto activation controls if auto activation is clicked
        $("#lblAutoActivationLink").click(function () {
            IOTAPAddOnLicensing.OpenActivationLink();

        });

        // Register an event in button save
        $("#btnSave").click(function () {


            var buttonText = $(this).val();
            // Get the button text. Allow saving a license if button text is edit otherwise save.
            if (buttonText.toLowerCase() == "edit") {
                document.getElementById("txtLicense").readOnly = false;

                $(this).val("Save");
                $("#txtLicense").
                $("#txtLicense").val("");
                $("#lblSaveMessage").text("");
            }
            else if (buttonText.toLowerCase() == "save") {
                document.getElementById("txtLicense").readOnly = true;

                var licenseText = $("#txtLicense").val();
                if (licenseText.trim() == "") {
                    alert('Please provide license')

                    return false;
                }

                // Call CreateLicense method if user is first time activating the license otherwise  UpdateLicense method.
                if (licenseId == null) {

                    IOTAPAddOnLicensing.CreateLicense();
                }
                else {
                    IOTAPAddOnLicensing.UpdateLicenseXML(licenseText);
                }

                $(this).val("Edit");

            }
        });
        //Auto activation : Register an event in button save
        $("#btnSaveTrial").click(function () {
            var validateTrialActivation = IOTAPAddOnLicensing.ValidateTrialActivationControls();

            // Proceed to save trial auto license xml if all the controls are validated.
            if (validateTrialActivation) {
                $("#lblSaveMessage").text("");
                //disable button
                $("#btnSaveTrial").attr("disabled", "disabled");
                // Show progress bar
                setTimeout(function () { IOTAPAddOnLicensing.ShowProgressBar(); }, 500);
                //Populates theTrialXML variable
                IOTAPAddOnLicensing.CreateTrialXML();
                //Creates License on server then populates the license
                IOTAPAddOnLicensing.CreateLicenseOnServer();
                //Auto activation : Invoke createTrialActivation private method which will save user provided information in xml string type.
                //IOTAPAddOnLicensing.CreateTrialActivation();

                // Remove progress bar

                IOTAPAddOnLicensing.RemoveProgressBar()

            }
            else {
                IOTAPAddOnLicensing.ChangeHtmlClassName('lblSaveMessage', 'licenseSaveMessage', 'licenseErrorMessage');
            }
        });
        //Update Profile : Register an event in button UpdateProfile
        $("#btnUpdateProfile").click(function () {
            var validateUpdateProfile = IOTAPAddOnLicensing.ValidateUpdateProfileControls();

            if (validateUpdateProfile) {

                $("#lblSaveMessage").text("");

                // Show progress bar
                setTimeout(function () { IOTAPAddOnLicensing.ShowProgressBar(); }, 500);

                IOTAPAddOnLicensing.UpdateProfile();
                IOTAPAddOnLicensing.CreateProfileXML();
                IOTAPAddOnLicensing.UpdateProfileOnServer();
                IOTAPAddOnLicensing.RemoveProgressBar()
            }
            else {
                IOTAPAddOnLicensing.ChangeHtmlClassName('lblSaveMessage', 'licenseSaveMessage', 'licenseErrorMessage');
            }
        });
        //Refresh License :Register event in  button refresh
        $("#btnRefreshLicense").click(function () {
            IOTAPAddOnLicensing.GetLicense();
            $("#lblSaveMessage").text("");
            // Show progress bar
            setTimeout(function () { IOTAPAddOnLicensing.ShowProgressBar(); }, 500);
            IOTAPAddOnLicensing.RefreshLicense(LicensingURL);
        });
        //Check Updatess : Register event for Check Updates
        $("#btnCheckUpdates").click(function () {
            setTimeout(function () { IOTAPAddOnLicensing.ShowProgressBar(); }, 500);
            //get the product version from IOTAP Licensing Server
            IOTAPAddOnLicensing.GetVersionFromServer(productName);
        });
        $('#nav ul li a').click(function (ev) {
            $('#nav ul li').removeClass('selected');
            $(ev.currentTarget).parent('li').addClass('selected');
        });
    },

    /*
    * Creates the License entity Object
    * @licenseText The string license xml
    * @returns License json object 
    */
    CreateLicenseObject: function (licenseText) {
        var blankValue = "";
        var licenseXml = $.parseXML(licenseText);

        var product = $(licenseXml).find('product').text();
        // Store optionset value if it is there in licensexml object
        var licenseType = { Value: $(licenseXml).find('licensetype').text() };
        var organizationName = $(licenseXml).find('organizationname').text();
        var subscriptionType = $(licenseXml).find('subscriptiontype').text() != blankValue ? { Value: $(licenseXml).find('subscriptiontype').text()} : null;
        var expiryDate = $(licenseXml).find('expirydate').text() != blankValue ? $(licenseXml).find('expirydate').text() : null;
        var userLicensedType = $(licenseXml).find('userlicensedtype').text() != blankValue ? { Value: $(licenseXml).find('userlicensedtype').text()} : null;
        var licensedUsers = $(licenseXml).find('licensedusers').text() != blankValue ? { Value: $(licenseXml).find('licensedusers').text()} : null;
        var userTier = $(licenseXml).find('usertier').text() != blankValue ? { Value: $(licenseXml).find('usertier').text()} : null;
        var SerialNo = $(licenseXml).find('licenseid').text() != blankValue ? $(licenseXml).find('licenseid').text() : null;
        var version = $(licenseXml).find('version').text() != blankValue ? $(licenseXml).find('version').text() : null;
        var objLicenseActivationRecords = {
            iotap_licensename: blankValue,
            iotap_licensetype: licenseType,
            iotap_version: version,
            iotap_subscriptiontype: subscriptionType,
            iotap_userlicensetype: userLicensedType,
            iotap_usertier: userTier,
            iotap_organizationname: organizationName,
            iotap_licensestartdate: new Date(),
            iotap_licenseenddate: expiryDate,
            iotap_firstactivationdate: new Date(),
            iotap_SerialNo: SerialNo,
            iotap_licensexml: licenseText
        };
        return objLicenseActivationRecords;
    },

    /*
    * Creates the License entity record    
    */
    CreateLicense: function () {
        var successFlag = false;
        try {
            XrmSvcToolkit.createRecord({
                entityName: addOnPrefix + "_license",
                entity: this.CreateLicenseXmlObject($("#txtLicense").val()),
                async: false,
                successCallback: function (result) {
                    licenseId = eval("result." + addOnPrefix + "_license" + "Id");
                    // Remove progress bar
                    IOTAPAddOnLicensing.SetSuccessMSG("License Activated Successfully." + " Your license Expires on " + ExpirationDate + ".");
                    IOTAPAddOnLicensing.RefreshLicensfields();

                },
                errorCallback: function (error) {
                    // Remove progress bar
                    IOTAPAddOnLicensing.SetErrorMSG(error);
                    IOTAPAddOnLicensing.RemoveProgressBar();
                }
            });
        }
        catch (error) {
            IOTAPAddOnLicensing.SetErrorMSG(error);
            IOTAPAddOnLicensing.RemoveProgressBar();
        }

    },

    /*
    * Updates the License entity record    
    */
    UpdateLicense: function () {
        var successFlag = false;
        XrmSvcToolkit.updateRecord({
            entityName: addOnPrefix + "_license",
            id: licenseId.toLowerCase(),
            entity: this.CreateLicenseXmlObject($("#txtLicense").val()),
            async: false,
            successCallback: function (result) {
                IOTAPAddOnLicensing.SetSuccessMSG("License Activated Successfully");
                IOTAPAddOnLicensing.RemoveProgressBar();
            },
            errorCallback: function (error) {
                // Print complete response error output
                IOTAPAddOnLicensing.RemoveProgressBar();
                IOTAPAddOnLicensing.SetErrorMSG(error);
            }
        });

    },
    /*
    * Updates license xml
    */
    UpdateLicenseXML: function (newLicenseXML) {

        XrmSvcToolkit.updateRecord({
            entityName: addOnPrefix + "_license",
            id: licenseId.toLowerCase(),
            entity: this.UpdateCreateLicenseXmlObject(newLicenseXML),
            async: false,
            successCallback: function (result) {
                // Remove progress bar
                IOTAPAddOnLicensing.SetSuccessMSG("License Updated Successfully");
                setTimeout(function () {
                    IOTAPAddOnLicensing.RemoveProgressBar()
                }, 500);
                return false;

            },
            errorCallback: function (error) {
                // Remove progress bar
                setTimeout(function () {
                    IOTAPAddOnLicensing.RemoveProgressBar()
                }, 500);
                return false;
                // Print complete response error output
                IOTAPAddOnLicensing.SetErrorMSG(error);
            }
        });

    },
    /*
    * Retrieves the License entity record    
    */
    GetLicense: function () {
        var successFlag = false;

        XrmSvcToolkit.retrieveMultiple({
            entityName: addOnPrefix + "_license",
            odataQuery: null,
            successCallback: function (result) {
                // If license found then show license in license texboxt
                if (result.length > 0) {
                    $("#infomsg").hide();
                    $("#txtLicense").text(result[0].iotap_licensexml);
                    licenseId = eval("result[0]." + addOnPrefix + "_license" + "Id");
                    if (result[0].iotap_licenseenddate == null) {
                        var xmlObj = IOTAPAddOnLicensing.loadXMLString(result[0].iotap_licensexml.replace(/^\s+|\s+$/g, ''));
                        var ExpiryDate = xmlObj.getElementsByTagName('expirydate')[0].firstChild.nodeValue;
                        var datpart = ExpiryDate.split('-');
                        ExpirationDate = new Date(datpart[0], datpart[1] - 1, datpart[2]);
                    }
                    else {
                        ExpirationDate = result[0].iotap_licenseenddate;
                    }
                    company = result[0].iotap_company;
                    envType = result[0].iotap_environmenttype.Value;
                    depType = result[0].iotap_deploymenttype.Value;
                    jobTitle = result[0].iotap_jobtitle;
                    SerialNo = result[0].iotap_SerialNo;
                    businessphone = result[0].iotap_businessphone;
                    mobilephone = result[0].iotap_mobilephone;
                    email = result[0].iotap_email;
                    website = result[0].iotap_website;
                    lname = result[0].iotap_lastname;
                    fname = result[0].iotap_firstname;
                    version = result[0].iotap_version;
                    islicenseexpired = result[0].new_islicenseexpired;
                    $("#txtActualUserCount").val(result[0].iotap_actualusercount);
                    $("#txtSerialNo").val(SerialNo);
                    IOTAPAddOnLicensing.SetLicenseType(result[0].iotap_licensetype.Value)

                    // Remove progress bar
                    setTimeout(function () {
                        IOTAPAddOnLicensing.RemoveProgressBar()
                    }, 500);
                    successFlag = true;
                }
                else {
                    setTimeout(function () {
                        IOTAPAddOnLicensing.RemoveProgressBar()
                    }, 500);
                }
            },
            errorCallback: function (error) {
                // Print complete response error output
                IOTAPAddOnLicensing.SetErrorMSG(error);

                // Remove progress bar
                setTimeout(function () {
                    IOTAPAddOnLicensing.RemoveProgressBar()
                }, 500);
            }
        });

    },

    /*
    * Retrieves the  Solutions Version   
    */
    GetVersion: function () {
        var successFlag = false;

        XrmSvcToolkit.retrieveMultiple({
            entityName: "Solution",
            uniquename: SolutionName,
            //odataQuery: null,
            successCallback: function (result) {
                // If license found then show license in license texboxt
                if (result.length > 0) {
                    for (var i = 0; i < result.length; i++) {
                        if (result[i].UniqueName == SolutionName) {
                            SolutionVersion = result[i].Version;
                            $("#lblVersion").text(SolutionVersion);

                            return;
                        }
                    }
                }
            },
            errorCallback: function (error) {
                // Print complete response error output
                IOTAPAddOnLicensing.SetErrorMSG(error);
            }
        });

    },

    /*
    * Updates class for a specified control    
    * @labelId control id
    * @removingClassName Class name to be removed
    * newClassName The new class name
    */
    ChangeHtmlClassName: function (labelId, removingClassName, newClassName) {
        $("#" + labelId + "").removeClass(removingClassName);
        $("#" + labelId + "").addClass(newClassName);
    },
    /*
    * Gets differenc between 2 dates    
    * @date1 first date
    * @date2 second date
    * @interval interval to determine difference
    */
    DateDiff: function (date1, date2, interval) {
        var second = 1000, minute = second * 60, hour = minute * 60, day = hour * 24, week = day * 7;
        newDate1 = new Date(date1);
        newDate1.setHours(0);
        newDate1.setMinutes(0);
        newDate1.setSeconds(0);
        newDate2 = new Date(date2);
        //date2 = new Date(date2);
        var timediff = (newDate2.getTime() + (newDate2.getTimezoneOffset() * 60000)) - (newDate1.getTime() + (newDate1.getTimezoneOffset() * 60000));
        var r = timediff % day;
        if (isNaN(timediff)) return NaN;
        if (r > .5) {
            return Math.floor(timediff / day) + 1;
        }
        else {
            return Math.floor(timediff / day);
        }



    },
    /*
    * Retrieves the Product Version from the IOTAP Server
    *@ProductName name of product bing queried
    *@ProxyURL URL of the licensing Server
    */
    GetVersionFromServer: function (ProductName) {
        $.getJSON(LicensingURL + "/GetProductVersion?callback=?", {
            productName: ProductName,
            format: "jsonp"
        })
        .done(function (data) {
            ServerVersion = data.ProductVersion;
            var ProductURL = data.ProductUrl;
            var ProductGuide = data.ProductUserGuide;
            var ProductReleaseNotes = data.ProductReleaseNotes;
            // comment this out untill we decide how this link will be handled
            //var ProductBuyNow = data.ProductBuyNowURL;
            //$('#buynow').attr('href', ProductBuyNow);
            //$('#buynow').attr('target', '_blank');
            if (ServerVersion.replace(/"/g, "") === SolutionVersion.replace(/"/g, "")) {
                setTimeout(function () {
                    IOTAPAddOnLicensing.RemoveProgressBar()
                }, 500);
            }
            else {
                setTimeout(function () {
                    IOTAPAddOnLicensing.RemoveProgressBar()
                }, 500);
                IOTAPAddOnLicensing.InsertAnchor(ServerVersion, ProductGuide, ProductURL, ProductReleaseNotes);
            }
        })
        .fail(function (jqxhr, textStatus, error) {
            setTimeout(function () {
                IOTAPAddOnLicensing.RemoveProgressBar()
            }, 500);
            IOTAPAddOnLicensing.SetErrorMSG("Unable to retrieve Product Version From Server");

        });


    },
    /*
    * Retrieves license on the server for refresh calling the web service
    *@licenseId license id to refresh
    */
    RefreshLicense: function () {
        //Disable the refresh license button
        $("#btnRefreshLicense").disabled = true;
        $.getJSON(LicensingURL + "/RefreshLicense?callback=?", {
            LicenseID: SerialNo,
            format: "jsonp"
        })
        .done(function (data) {
            var XML = data;
            IOTAPAddOnLicensing.UpdateLicenseXML(XML);
            //Re enable the refresh license button
            $("#btnRefreshLicense").disabled = false;
            // Remove progress bar
            IOTAPAddOnLicensing.RemoveProgressBar();
        })
        .fail(function (jqxhr, textStatus, error) {

            IOTAPAddOnLicensing.SetErrorMSG("Unable to refresh Product product from Server");
            // Remove progress bar
            IOTAPAddOnLicensing.RemoveProgressBar();

        });

    },
    /*
    * Retrieves license on the server for refresh calling the web service
    *@licenseId license id to refresh
    */
    UpdateProfile: function () {
        //Disable the refresh license button
        IOTAPAddOnLicensing.GetLicense();
        $("#btnUpdateProfile").disabled = true;
        XrmSvcToolkit.updateRecord({
            entityName: addOnPrefix + "_license",
            id: licenseId.toLowerCase(),
            entity: this.UpdateProfileObject(),
            async: false,
            successCallback: function (result) {
                // Remove progress bar
                IOTAPAddOnLicensing.SetSuccessMSG("Profile Updated Successfully");
                setTimeout(function () {
                    IOTAPAddOnLicensing.RemoveProgressBar()
                }, 500);
                return false;

            },
            errorCallback: function (error) {
                // Remove progress bar
                setTimeout(function () {
                    IOTAPAddOnLicensing.RemoveProgressBar()
                }, 500);
                return false;
                // Print complete response error output
                IOTAPAddOnLicensing.SetErrorMSG(error);
            }
        });

    },
    /*
    * Creates license on the server calling the web service
    */
    UpdateProfileOnServer: function () {
        $.getJSON(LicensingURL + "/UpdateProfile?callback=?", {
            profileXml: ProfileXML,
            format: "jsonp"
        })
        .done(function (data) {
            if (data.Message) {
                IOTAPAddOnLicensing.SetErrorMSG(data.Message);
                IOTAPAddOnLicensing.RemoveProgressBar();
            }
            else {

                if (data != "") {
                    IOTAPAddOnLicensing.SetSuccessMSG("Profile successfully updated on server");
                }
                else {
                    IOTAPAddOnLicensing.SetErrorMSG("A network error occured, unable to update profile on server");
                    IOTAPAddOnLicensing.RemoveProgressBar();
                }
            }
        })
        .fail(function (jqxhr, textStatus, error) {
            IOTAPAddOnLicensing.SetErrorMSG("Unable to update profile on server");
            IOTAPAddOnLicensing.RemoveProgressBar();

        })


    },
    /*
    * Creates license on the server calling the web service
    */
    CreateLicenseOnServer: function () {
        $.getJSON(LicensingURL + "/CreateServerLicense?callback=?", {
            trialAutoActivationXml: TrialXML,
            format: "jsonp"
        })
        .done(function (data) {
            if (data.Message) {
                IOTAPAddOnLicensing.SetErrorMSG(data.Message);
                IOTAPAddOnLicensing.RemoveProgressBar();
            }
            else {

                if (data != "") {
                    var LicensXML = data;
                    IOTAPAddOnLicensing.CreateTrialActivation(LicensXML)
                }
                else {
                    IOTAPAddOnLicensing.SetErrorMSG("A network error occured, unable to create license on server");
                    IOTAPAddOnLicensing.RemoveProgressBar();
                }
            }
        })
        .fail(function (jqxhr, textStatus, error) {
            IOTAPAddOnLicensing.SetErrorMSG("Unable to create license on server");
            IOTAPAddOnLicensing.RemoveProgressBar();

        })


    },
    /*Converts date for insertion into CRM
    *@inputFormat javascript date
    *
    */
    ConvertDate: function (inputFormat) {
        function pad(s) { return (s < 10) ? '0' + s : s; }
        var d = new Date(inputFormat);
        return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), 0, 0);
    },
    /*ownloadInserts an anchor tag for hyperlink to product d
    *@SolutionVersion version of solution
    *@ProductUserGuide UserGuide URL
    *@ProductURL Product down load URL
    *@ProductReleaseNotes Releas notes text
    */
    InsertAnchor: function (SolutionVersion, ProductUserGuide, ProductURL, ProductReleaseNotes) {
        $("#btnCheckUpdates").hide();
        var mydiv = document.getElementById("tdCheckUpdates");
        var aTag = document.createElement('a');
        aTag.setAttribute('class', "tooltip");
        aTag.setAttribute('href', ProductURL);
        aTag.setAttribute('target', "_blank");
        aTag.setAttribute('title', ProductReleaseNotes);
        aTag.innerHTML = 'Version ' + SolutionVersion + ' is now available';
        mydiv.appendChild(aTag);
    },
    RefreshLicensfields: function () {

        if (ExpirationDate == null) {
            $("#lblEndDate").hide();
            $("#txtEndDate").hide();
            $("#lblDaysLeft").hide();
            $("#txtDaysLeft").hide();
        }
        if (ExpirationDate != null) {
            var daysleft = IOTAPAddOnLicensing.DateDiff(now, ExpirationDate, "days");
            $("#lblExpiry").text((ExpirationDate.getMonth() + 1) + "/" + ExpirationDate.getDate() + "/" + ExpirationDate.getFullYear());
            $("#lblExpiry").show();
            $("#lblEndDate").show();
            $("#lblDaysLeft").show();
            $("#txtEndDate").val(ExpirationDate);
            $("#txtEndDate").show();
            $("#txtDaysLeft").val(daysleft);
            $("#txtDaysLeft").show();
            if (daysleft < 0) {
                IOTAPAddOnLicensing.SetErrorMSG("License Expired : " + productName + "</br>" + "Product Serial No.: " + SerialNo + "</br>" + "Please email support@iotap.com for any support. ");

            }
        }
    },
    SetLicenseType: function (type) {
        if (type == 1) {
            $("#lblActivationType").text("Trial")
        }
        else {
            $("#lblActivationType").text("Paid")
        }
    },
    SetErrorMSG: function (text) {
        var mydiv = document.getElementById("lblErrorMessage");
        mydiv.innerHTML = "<img height='16' width='16' src='" + addOnPrefix + "_errormsg' />" + text;
        // $("#lblErrorMessage").text(text);
        $("#lblErrorMessage").show();
        $("#lblSaveMessage").hide();
    },
    SetErrorMSGOnField: function (text, field) {
        var mydiv = document.getElementById("lblErrorMessage");
        mydiv.innerHTML = "<img height='16' width='16' src='" + addOnPrefix + "_errormsg' />" + text;
        // $("#lblErrorMessage").text(text);
        $("#lblErrorMessage").show();
        $(field).focus();
        $("#lblSaveMessage").hide();
    },
    SetSuccessMSG: function (text) {
        var mydiv = document.getElementById("lblSaveMessage");
        mydiv.innerHTML = "<img height='16' width='16' src='" + addOnPrefix + "_successmsg' />" + text;
        //$("#lblSaveMessage").text(text);
        $("#lblSaveMessage").show();
        $("#lblErrorMessage").hide();

    },
    OpenActivationLink: function () {
        IOTAPAddOnLicensing.ShowProgressBar();

        // Hide manual
        $("#lblManualActivationControls").hide();
        // Hide Settings Control
        $("#lblSettingsControls").hide();
        //Hide refresh
        $("#btnRefreshLicense").hide();
        // Change auto activation class
        IOTAPAddOnLicensing.ChangeHtmlClassName('lblAutoActivationLink', 'deActivatedLink', 'activatedLink')
        IOTAPAddOnLicensing.ChangeHtmlClassName('lblManualActivationLink', 'activatedLink', 'deActivatedLink')
        IOTAPAddOnLicensing.ChangeHtmlClassName('lblSettingsControlsLink', 'activatedLink', 'deActivatedLink')
        $("#lblAutoActivationControls").show();

        // Auto activation : Invoke getOrgName method & set organization name in organization name textbox
        $("#txtOrgName").val(IOTAPAddOnLicensing.GetOrgName());

        // Auto activation : Invoke getActiveUserCount method to get number of active user count.
        IOTAPAddOnLicensing.GetActiveUserCount();

        //Auto activation : Invoke getUserInfo method to fill user information like company name, email id etc.
        IOTAPAddOnLicensing.GetUserInfo();

        //Auto activation : Invoke hideTrialActivationButton method to hide trial activation button if license xml is already present.
        IOTAPAddOnLicensing.HideTrialActivationButton();

        // Remove progress bar
        setTimeout(function () {
            IOTAPAddOnLicensing.RemoveProgressBar()
        }, 500);
    },
    SetImages: function () {
        jQuery("#info").attr('src', addOnPrefix + "_infomsg");
        jQuery("#logo").attr('src', addOnPrefix + "_logo");
        jQuery("#loading").attr('src', addOnPrefix + "_loading.gif");
    }


};



