﻿var DownloadOptions = {
    Page_Load: function () {

        if ( !ValidateLicense() ) {
            window.parent.Xrm.Utility.alertDialog( "OneClickPdf : Invalid License" );
            window.close();
        }

        //setting Button Text based on language code
        var btnGenerate = document.getElementById( 'Button1' );
        var userLanguageCode = Xrm.Page.context.getUserLcid();
        if ( userLanguageCode == "1031" )
        {
            btnGenerate.innerHTML = 'benutzerdefiniert';
        } else
        {
            btnGenerate.innerHTML = 'Generate';
        }
        

        jQuery.fn.center = function () {
            this.css("position", "absolute");
            this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
            this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
            return this;
        }

        // Global Variables
        window.log = new StringBuilder();
        window.serverUrl = getSUrl();

        //Log Start Time 
        var currentdate = new Date();
        var datetime = currentdate.getDate() + "/"
                        + (currentdate.getMonth() + 1) + "/"
                        + currentdate.getFullYear() + " @ "
                        + currentdate.getHours() + ":"
                        + currentdate.getMinutes() + ":"
                        + currentdate.getSeconds();
        log.appendLine("Start Time : - " + datetime);

        // Get Browser Details
        BrowserDetails();

        ConfigureAjaxLoading('Generating, Please wait');
        $('#loadingDiv').css('display', 'none');

        ParseQueryString();
       
        ddlReport_Bind();
    },
    primaryEntityName: null,
    recordGuid: null
};


function ConfigureAjaxLoading(text, otherText) {
    $('#formDownloadOptions').append('<div id="loadingDiv" style="z-index:100; top:0; left:10px;top:10px;vertical-align:center;align:middle"></div>');
    $('#loadingDiv').append('<p id="loadingText">' + text + '</p>')
                                          .css('background', 'url(iotap_loading.gif) no-repeat center')
                                          .css('background-color', '#e2e6eb')
                                          .css('height', '100%')
                                          .css('width', '100%')
                                          .css('vertical-align', 'middle')
                                          .css('display', 'none')
    .center();

    $('#loadingText').css('text-align', 'center')
                                          .css('font', '18px bolder')
                                          .css('font-family', 'Segoe UI, Tahoma, Arial');
}

function AutoSubmit(_primaryEntityTypeName, _firstPrimaryItemId, SourceControlId, _action, _fileFormat)
{
    var actionName, fileFormatId;
    var reportButtonId = SourceControlId.split("_");

    if (_action == "123030000")
        actionName = "Download";
    else if (_action == "123030002")
        actionName = "Attach To Email";
    else if (_action == "123030003")
        actionName = "Save To Notes";
    else if ( _action == "123030004" )
        actionName = "Embed in Email";

    if (_fileFormat == "PDF")
        fileFormatId = 123030000;
    else if (_fileFormat == "EXCEL")
        fileFormatId = 123030001;
    else if (_fileFormat == "WORD")
        fileFormatId = 123030002;

    if (reportButtonId == null) return;

    var reportId = reportButtonId[0];
    var reportName = reportButtonId[1];
    var action = _action;
    var fileFormat = _fileFormat;

    document.getElementById("ddlReports")[0].value = reportId;
    document.getElementById("ddlReports")[0].innerHTML = reportName;


    document.getElementById("ddlAction")[0].value = action;
    document.getElementById("ddlAction")[0].innerHTML = actionName;

    document.getElementById("ddlFileFormat")[0].value = fileFormatId;
    document.getElementById("ddlFileFormat")[0].innerHTML = fileFormat;

    document.getElementById("txtFileName").value = reportName;

    setTimeout( function ()
    {
        Download_OnClick();
    }, 1000 );
}

function ddlReport_Bind() {

    log.appendLine( "Start Report Binding to the pop-up" );

    var httpReq = new XMLHttpRequest();
    httpReq.open( "GET", getSUrl() + "/api/data/v8.0/" + "iotap_1clickdocs?$select=iotap_name,iotap_report,iotap_displayname,iotap_actionid&$filter=iotap_entityname eq '" + DownloadOptions.primaryEntityName.toLowerCase() + "' and iotap_displayinpopup eq true", false );
    httpReq.setRequestHeader( "Accept", "application/json" );
    httpReq.setRequestHeader( "Content-Type", "application/json; charset=utf-8" );
    httpReq.setRequestHeader( "OData-MaxVersion", "4.0" );
    httpReq.setRequestHeader( "OData-Version", "4.0" );
    httpReq.send( null );
    
    var ddlReports = document.getElementById( 'ddlReports' );
    if ( httpReq.status === 200 ) {
        coll = JSON.parse( httpReq.responseText ).value;
      
        log.appendLine( "Number of configuration records present for the entity is : - " + coll.length );

        if ( coll.length > 1 ) {
            for ( var i = 0; i < coll.length; i++ ) {
                $( '#ddlReports' ).append( '<option value="' + coll[i].iotap_report + '|' + coll[i].iotap_actionid + '">' + coll[i].iotap_displayname + '</option>' )
                log.appendLine( "Reports Fetched are : - " + coll[i].iotap_displayname );
            }
        }
        else
        {
            ddlReports[0].innerHTML = coll[0].iotap_displayname;
            ddlReports[0].setAttribute( "selected", "selected" );
            ddlReports[0].value = coll[0].iotap_report + '|' + coll[0].iotap_actionid;
            log.appendLine( "Report Fetched is :- " + coll[0].iotap_displayname );
            ddlReports_OnChange();
        }       

    }     
    DdlHelper.Sort(ddlReports);
}

function ParseQueryString() {
    DownloadOptions.primaryEntityName = getDataParam(0);
    log.appendLine("Entity Name :-" + DownloadOptions.primaryEntityName);
    DownloadOptions.recordGuid = getDataParam(1);
}

function ddlReports_OnChange() {
    var actionId = document.getElementById('ddlReports').value.split('|')[1];

    var httpReq = new XMLHttpRequest();
    httpReq.open( "GET", getSUrl() + "/api/data/v8.0/" + "iotap_1clickdocs?$select=iotap_fileformat,iotap_action,iotap_filename,iotap_displayname&$filter=iotap_actionid eq '" + actionId + "'", false );
    httpReq.setRequestHeader( "Accept", "application/json" );
    httpReq.setRequestHeader( "Content-Type", "application/json; charset=utf-8" );
    httpReq.setRequestHeader( "OData-MaxVersion", "4.0" );
    httpReq.setRequestHeader( "OData-Version", "4.0" );
    httpReq.send( null );    

    if ( httpReq.status === 200 ) {
        result = JSON.parse( httpReq.responseText ).value;

        Log( result );
        if ( result == null || result.length != 1 ) {
            DdlHelper.SelectDefault( 'ddlAction', '0' );
            DdlHelper.SelectDefault( 'ddlFileFormat', '0' );
            document.getElementById( 'txtFileName' ).value = '';
            return;
        }

        if ( result[0].iotap_action != null ) {
            DdlHelper.SelectDefault( 'ddlAction', result[0].iotap_action );
        }

        if ( result[0].iotap_fileformat != null ) {
            DdlHelper.SelectDefault( 'ddlFileFormat', result[0].iotap_fileformat );
        }

        if ( result[0].iotap_displayname != null ) {
            document.getElementById( 'txtFileName' ).value = result[0].iotap_filename == null ? '' : result[0].iotap_filename;
        }
    }     
}

function Download_OnClick() {
    log.appendLine("Generate Button Clicked");
    if (!ValidateForm()) return;
    GenerateDocumentRequest();
    $('#loadingDiv').css('display', 'block');
}

function ValidateForm() {
    if (document.getElementById('ddlReports').value == "0") {
        alert(Constant.RequiredDdlReportError);
        return false;
    }
    if (document.getElementById('ddlFileFormat').value == "0") {
        alert(Constant.RequiredDdlFileFormatError);
        return false;
    }
    if (document.getElementById('ddlAction').value == "0") {
        alert(Constant.RequiredDdlActionError);
        return false;
    }
    return true;
}

function GenerateDocumentRequest() {

    log.appendLine("GenerateDocumentRequest function called");

    var reportId = document.getElementById('ddlReports').value.split('|')[0];
    var action = document.getElementById('ddlAction').value;
    var fileFormat = document.getElementById('ddlFileFormat').value;
    var fileName = document.getElementById('txtFileName').value;
    if (reportId == null || action == null || fileFormat == null) return;
    ReportDownloader.ReportId = reportId;
    ReportDownloader.Action = action;
    ReportDownloader.Fileformat = fileFormat;
    ReportDownloader.FileName = fileName;
    log.appendLine("Action :-" + action);
    log.appendLine("File Format :-" + fileFormat);
    log.appendLine("File Name :-" + fileName);
    DownloadReport(); 
}

function ValidateLicense()
{
    var isValid = false;

    $.ajax( {
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: getSUrl() + "/api/data/v8.0/" + "sdkmessageprocessingsteps?$filter=startswith(name,'IOTAP.AddOn.OneClickPdf.ValidateLicense.LicenseValidator:') and statecode eq 0",
        async:false,
        data: null,
        beforeSend: function ( XMLHttpRequest )
        {
            XMLHttpRequest.setRequestHeader( "Accept", "application/json" );
            XMLHttpRequest.setRequestHeader( "OData-MaxVersion", "4.0" );
            XMLHttpRequest.setRequestHeader( "OData-Version", "4.0" );
        },
        success: function ( data, textStatus, XmlHttpRequest )
        {
            var results = data.value;
            if ( results.length == 2 ) {
                isValid = true;
            }
        },
        error: function ( XmlHttpRequest, textStatus, errorThrown )
        {
            window.parent.Xrm.Utility.alertDialog( "Error " + textStatus + errorThrown );

        }
    } );

    return isValid;
}


function StringBuilder() {
    var strings = [];

    this.append = function (string) {
        string = verify(string);
        if (string.length > 0) strings[strings.length] = string;
    };

    this.appendLine = function (string) {
        string = verify(string);
        if (this.isEmpty()) {
            if (string.length > 0) strings[strings.length] = string;
            else return;
        }
        else strings[strings.length] = string.length > 0 ? "\r\n" + string : "\r\n";
    };

    this.clear = function () { strings = []; };

    this.isEmpty = function () { return strings.length == 0; };

    this.toString = function () { return strings.join(""); };

    var verify = function (string) {
        if (!defined(string)) return "";
        if (getType(string) != getType(new String())) return String(string);
        return string;
    };

    var defined = function (el) {
        // Changed per Ryan O'Hara's comment:
        return el != null && typeof (el) != "undefined";
    };

    var getType = function (instance) {
        if (!defined(instance.constructor)) throw Error("Unexpected object type");
        var type = String(instance.constructor).match(/function\s+(\w+)/);

        return defined(type) ? type[1] : "undefined";
    };
};

function BrowserDetails()
{
    var nVer = navigator.appVersion;
    var nAgt = navigator.userAgent;
    var browserName = navigator.appName;
    var fullVersion = '' + parseFloat(navigator.appVersion);
    var majorVersion = parseInt(navigator.appVersion, 10);
    var nameOffset, verOffset, ix;

    // In Opera, the true version is after "Opera" or after "Version"
    if ((verOffset = nAgt.indexOf("Opera")) != -1) {
        browserName = "Opera";
        fullVersion = nAgt.substring(verOffset + 6);
        if ((verOffset = nAgt.indexOf("Version")) != -1)
            fullVersion = nAgt.substring(verOffset + 8);
    }
        // In MSIE, the true version is after "MSIE" in userAgent
    else if ((verOffset = nAgt.indexOf("MSIE")) != -1) {
        browserName = "Microsoft Internet Explorer";
        fullVersion = nAgt.substring(verOffset + 5);
    }
        // In Chrome, the true version is after "Chrome" 
    else if ((verOffset = nAgt.indexOf("Chrome")) != -1) {
        browserName = "Chrome";
        fullVersion = nAgt.substring(verOffset + 7);
    }
        // In Safari, the true version is after "Safari" or after "Version" 
    else if ((verOffset = nAgt.indexOf("Safari")) != -1) {
        browserName = "Safari";
        fullVersion = nAgt.substring(verOffset + 7);
        if ((verOffset = nAgt.indexOf("Version")) != -1)
            fullVersion = nAgt.substring(verOffset + 8);
    }
        // In Firefox, the true version is after "Firefox" 
    else if ((verOffset = nAgt.indexOf("Firefox")) != -1) {
        browserName = "Firefox";
        fullVersion = nAgt.substring(verOffset + 8);
    }
        // In most other browsers, "name/version" is at the end of userAgent 
    else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) <
              (verOffset = nAgt.lastIndexOf('/'))) {
        browserName = nAgt.substring(nameOffset, verOffset);
        fullVersion = nAgt.substring(verOffset + 1);
        if (browserName.toLowerCase() == browserName.toUpperCase()) {
            browserName = navigator.appName;
        }
    }

    log.appendLine("Browser Name is :-" + browserName);
    // trim the fullVersion string at semicolon/space if present
    if ((ix = fullVersion.indexOf(";")) != -1)
        fullVersion = fullVersion.substring(0, ix);
    if ((ix = fullVersion.indexOf(" ")) != -1)
        fullVersion = fullVersion.substring(0, ix);

    log.appendLine("Browser Version is :-" + fullVersion);

    majorVersion = parseInt('' + fullVersion, 10);
    if (isNaN(majorVersion)) {
        fullVersion = '' + parseFloat(navigator.appVersion);
        majorVersion = parseInt(navigator.appVersion, 10);


    }
}

function getSUrl() {
    return window.parent.Xrm.Page.context.getClientUrl();   
}

