/**
 * This source is part of the Oracle Banking Software Product.
 * Copyright (c) 2018, 2021, Oracle and/or its affiliates.  All rights reserved.
 * No part of this work may be reproduced, stored in a retrieval system, adopted or transmitted in any form or by any means, electronic, mechanical, photographic, graphic, optic recording or otherwise, translated in any language or computer language, without the prior written permission of Oracle and/or its affiliates.
 * Oracle Financial Services Software Limited.
 * Oracle Park, Off Western Express Highway,
 * Goregaon (East),
 * Mumbai - 400 063, India.
 */
define(['ojs/ojcore', 'knockout', 'ojL10n!obtfpm/resources/obtfpm/nls/bundle', 'jquery', "cmn-util/applicationContext", 'cmn-util/model/trade/tradeModel', 'ojs/ojarraydataprovider', 'cmn-util/commonFunction', 'ojs/ojknockout', 'ojs/ojlabel', 'ojs/ojswitch', 'ojs/ojbutton',
        'ojs/ojcollapsible', 'ojs/ojdatetimepicker', 'ojs/ojinputtext', 'ojs/ojtimezonedata', 'ojs/ojselectcombobox', 'ojs/ojdatagrid', 'ojs/ojcollectiondatagriddatasource', 'ojs/ojvalidation-datetime', 'ojs/ojcheckboxset',
        'ojs/ojvalidation-number', 'ojs/ojdialog', 'ojs/ojtable', 'ojs/ojinputnumber', 'scc/fsgbu-ob-cmn-fd-lov/loader', 'scc/fsgbu-ob-cmn-fd-amount/loader'
    ],
    function (oj, ko, labels, $, applicationContext, tfpmvpassigneemodel, ArrayDataProvider, commonFunction) {
    function mainContentViewModel(context) {
        var self = this;
        self.labels = labels.fsgbuobtfpmvpassignee;
        self.cmnLabels = labels.common;
        self.cmnMessageLabels = labels.commonmessage;
        var element = context.element;
        self.name = ko.observable('tfpm-vp-assignee');
        self.tfpmvpassigneemodel = new tfpmvpassigneemodel();
        self.alert = $("#cmn_alert");
        self.loader = $("#cmn_loader");
        self.notification = $("#cmn_notification");
        self.transactionContextData = null;
        self.overrideAccept = ko.observable(false);
        self.viewMode = ko.observable(false);
        self.accountResourceUrl = ko.observable("");
        self.accountTabout = ko.observable(true);
        self.deletedAssigneeRecords = ko.observableArray();
        self.dialogElm = ko.observable();
        self.assigneeId = ko.observable();
        self.account = ko.observable();
        self.assigneeName = ko.observable();
        self.sequence = ko.observable();
        self.assignmentPercentage = ko.observable();
        self.assignedamount = ko.observable();
        self.accountCurrency = ko.observable();
        self.id = ko.observable();
        self.isCalculated = false;
        self.readonly = ko.observable(false);
        self.baseComputationAmount = 0;
        self.isDefaultRecord = ko.observable(false);
        self.assignedByUs = ko.observable(false);
        self.disableAssignedByUs = ko.observable(false);
        self.disableAssigneeName= ko.observable(true);
        self.disableAddressLine4= ko.observable(true);
        self.disableAddressLine3= ko.observable(true);
        self.disableAddressLine2= ko.observable(true);
        self.disableAddressLine1= ko.observable(true);
        self.drawings = ko.observable();
        self.addressLine1 = ko.observable();
        self.addressLine2 = ko.observable();
        self.addressLine3 = ko.observable();
        self.addressLine4 = ko.observable();
        self.editMode = ko.observable(false);
        context.props.then(function (properties) {
            self.transactionContextData = properties.data;
            if (self.transactionContextData.processCode === "ELCLIQ") {
                self.disableAssignedByUs(true);

            }

            self.viewMode(properties.readonly);
            self.readonly(properties.readonly);

        });
        self.assigneeLovConf = [{
                id: "otherPtyId",
                label: "Assignee ID",
            default:
                true
            }, {
                id: "ptyName",
                label: "Assignee Name",
                bind: self.assigneeName,
                filter: true,
            }, {
                id: "addressLine1",
                label: "Address Line1",
                bind: self.addressLine1,
                filter: true,
            },
            {
                id: "addressLine2",
                label: "Address Line2",
                bind: self.addressLine2,
                filter: false,
            },
            {
                id: "addressLine3",
                label: "Address Line3",
                bind: self.addressLine3,
                filter: false,
            },
            {
                id: "addressLine4",
                label: "Address Line4",
                bind: self.addressLine4,
                filter: false,
            }
        ];
        self.accountLovConf = ko.observableArray([{
                        id: "custAccountNo",
                        label: "Account",
                    default:
                        true
                    }, {
                        id: "custAcName",
                        label: "Account Name"
                    }, {
                        id: "customerNo",
                        label: "Customer Number"

                    }, {
                        id: "custAcCcy",
                        label: "Currency",
                        bind: self.accountCurrency

                    }, {
                        id: "sourceSystemAccBrn",
                        label: "Branch"
                    }
                ]);

        self.ccyLovConfig = ko.observableArray([{
                        id: "currencyCode",
                        label: "Currency Code",
                    default:
                        true
                    }, {
                        id: "currencyName",
                        label: "Currency Name"

                    }
                ]);

        self.customerResourceUrl = "";
        self.assigneeArray = ko.observableArray([]);
        self.datasource = new ArrayDataProvider(self.assigneeArray);
        self.columnArray = [{
                "renderer": oj.KnockoutTemplateUtils.getRenderer("tfpm-vp-assignee_checkbox_tmpl", true),
                "field": "select",
                "id": "column1",
                "style": "width: 2em;max-width:2em"
            }, {
                "headerText": self.labels.sequence,
                "field": "sequence",
                "id": "column2"
            }, {
                "headerText": self.labels.assigneeId,
                "field": "assigneeId",
                "id": "column3"
            }, {
                "headerText": self.labels.assigneeName,
                "field": "assigneeName",
                "id": "column4"
            }, {
                "headerText": self.labels.addressLine1,
                "field": "addressLine1",
                "id": "column5"
            }, {
                "headerText": self.labels.addressLine2,
                "field": "addressLine2",
                "id": "column6"
            }, {
                "headerText": self.labels.addressLine3,
                "field": "addressLine3",
                "id": "column7"
            }, {
                "headerText": self.labels.addressLine4,
                "field": "addressLine4",
                "id": "column8"
            }, {
                "headerText": self.labels.assignmentPercentage,
                "field": "assignmentPercentage",
                "id": "column9"
            }, {
                "headerText": self.labels.assignedamount,
                "field": "assignedamount",
                "id": "column10"
            }, {
                "headerText": self.labels.accountCurrency,
                "field": "accountCurrency",
                "id": "column11"
            }, {
                "headerText": self.labels.accountnumber,
                "field": "account",
                "id": "column12"
            }

        ];

        self.assignmentPercentage.subscribe(function (value) {
            if (value !== "" && value !== null && !self.isCalculated) {
                self.isCalculated = true;
                self.assignedamount(self.baseComputationAmount * (value / 100));
            }
            self.isCalculated = false;

        });

        self.assignedamount.subscribe(function (value) {
            if (value !== "" && value !== null && !self.isCalculated) {
                self.isCalculated = true;
                self.assignmentPercentage((value / self.baseComputationAmount) * 100);
            }
            self.isCalculated = false;

 });
          self.assigneeId.subscribe(function (value) { 
           if(value !== "" && value !== null && value === applicationContext.walkinCustomer)
           {
            self.disableAssigneeName(false);
            self.disableAddressLine4(false);
            self.disableAddressLine3(false);
            self.disableAddressLine2(false);
            self.disableAddressLine1(false);
           }
           else{
            self.disableAssigneeName(true);
            self.disableAddressLine4(true);
            self.disableAddressLine3(true);
            self.disableAddressLine2(true);
            self.disableAddressLine1(true);
           } 
        });
        self.action = null;

        var selectdRecord = null;
        self.edit = function (data, eve) {
            selectdRecord = self.assigneeArray();
            selectdRecord = selectdRecord.filter(function (item) {
                return (item.select().length !== 0);
            });
            if (selectdRecord.length === 1) {
                selectdRecord = selectdRecord[0];
                self.action = "edit";
                self.assigneeId(selectdRecord.assigneeId);
                self.sequence(selectdRecord.sequence);
                self.assignmentPercentage(selectdRecord.assignmentPercentage);
                self.assigneeName(selectdRecord.assigneeName);
                self.addressLine1(selectdRecord.addressLine1);
                self.addressLine2(selectdRecord.addressLine2);
                self.addressLine3(selectdRecord.addressLine3);
                self.addressLine4(selectdRecord.addressLine4);
                self.accountCurrency(selectdRecord.accountCurrency);
                self.assignedamount(selectdRecord.assignedamount);
                self.account(selectdRecord.account);
                self.id(selectdRecord.id);
                self.dialogElm().ojDialog("open");
            } else if (selectdRecord.length === 0) {
                self.alert.get(0).alert("error", "Error", self.cmnMessageLabels.selRec4Edit);
            } else if (selectdRecord.length > 1) {
                self.alert.get(0).alert("error", "Error", self.cmnMessageLabels.mulRecEditViolation);
            }
        };
        self.view = function (data, eve) {
            selectdRecord = self.assigneeArray();
            selectdRecord = selectdRecord.filter(function (item) {
                return (item.select().length !== 0);
            });
            if (selectdRecord.length === 1) {
                selectdRecord = selectdRecord[0];
                self.action = "view";
                self.assigneeId(selectdRecord.assigneeId);
                self.sequence(selectdRecord.sequence);
                self.assignmentPercentage(selectdRecord.assignmentPercentage);
                self.assigneeName(selectdRecord.assigneeName);
                self.addressLine1(selectdRecord.addressLine1);
                self.addressLine2(selectdRecord.addressLine2);
                self.addressLine3(selectdRecord.addressLine3);
                self.addressLine4(selectdRecord.addressLine4);
                self.accountCurrency(selectdRecord.accountCurrency);
                self.assignedamount(selectdRecord.assignedamount);
                self.account(selectdRecord.account);
                self.id(selectdRecord.id);
                self.dialogElm().ojDialog("open");
            } else if (selectdRecord.length === 0) {
                self.alert.get(0).alert("error", "Error", self.cmnMessageLabels.selRec4View);
            } else if (selectdRecord.length > 1) {
                self.alert.get(0).alert("error", "Error", self.cmnMessageLabels.mulRecViewViolation);
            }
        };
        self.remove = function (data, eve) {
            var array = self.assigneeArray();
            array = array.filter(function (item) {
                return (item.select().length === 0);
            });
            var deletedRecordArray = self.assigneeArray().filter(function (item) {
                return (item.select().length !== 0 && item.id !== "");
            });
            self.deletedAssigneeRecords(deletedRecordArray);
            $.each(self.deletedAssigneeRecords(), function () {
                this.recordStat = "D";
            });
            self.assigneeArray(array);
            self.refreshTable();
        };
        self.add = function () {
            self.action = "add";
            self.sequence("");
            self.assigneeId("");
            self.assignmentPercentage(null);
            self.assigneeName("");
            self.addressLine1("");
            self.addressLine2("");
            self.addressLine3("");
            self.addressLine4("");
            self.accountCurrency("");
            self.assignedamount(null);
            self.account(null);
            self.id("");
            self.isDefaultRecord(false);
            self.dialogElm().ojDialog("open");
        };
        self.viewOverrides = function () {
            $(element).parents().find("fsgbu-ob-tfpm-ct-process-flow")[0].saveOverrides(self.wizard, self.transactionContextData, function () {
                self.submitOverrides();
            });
        };
        self.submitOverrides = function () {
            self.overrideAccept(true);
            self._save();
        };

        self._save = function () {
            self.assigneedata = self.getModelData();
            self.getRequest();

            return new Promise(function (resolve, reject) {
                var assigneePostEntity = self.tfpmvpassigneemodel.post("OBTFPM.POST_FACADE", "", request);
                assigneePostEntity.then(function (result) {
                    resolve(result);
                    if (self.transactionContextData.processCode === "ELCAMD" || self.transactionContextData.processCode === "ELCDRW") {
                        self.dialog($(element).parents().find("#additionalDialog"));
                    }
                    if (self.transactionContextData.processCode === "ILCUDR") {
                        self.dialog($(element).parents().find("#tfpm_vp_ilcudr_additional_Dialog"));
                    }
                    if (self.transactionContextData.processCode === "ILCDRW") {
                        self.dialog($(element).parents().find("#tfpm_vp_ilcdrw_additional_Dialog"));
                    }
                    if (self.transactionContextData.processCode === "ILCLIQ") {
                        self.dialog($(element).parents().find("#tfpm_vp_ilcliq_additional_Dialog"));
                    }
                    if (self.dialog())
                        self.dialog().ojDialog('close');
                    self.notification.get(0).notify("success", "", self.cmnMessageLabels.additionalTileSave, 3000);
                }).catch(function (error) {
                    reject(error);
                });
            });
        }

        self.save = function () {
            self.assigneedata = self.getModelData();
            self.getRequest();

            return new Promise(function (resolve, reject) {
                var assigneePostEntity = self.tfpmvpassigneemodel.post("OBTFPM.POST_FACADE", "", request);
                assigneePostEntity.then(function (result) {
                    if (result.messages.status === "WARNING" && result.messages.codes.length > 0) {
                        self.viewOverrides();
                        self.loader.hide();
                    } else {
                        resolve(result);
                    }
                }).catch(function (error) {
                    reject(error);
                });
            });

        }

        self.saveAndClose = function () {
            self.validateassignee().then(function (values) {
                for (var j = 0; j < values.length; j++) {
                    if (values[j] === "invalid") {
                        return;
                    }
                }
                var rec = {
                    "select": ko.observableArray([]),
                    "sequence": self.sequence(),
                    "assigneeId": self.assigneeId(),
                    "assigneeName": self.assigneeName(),
                    "addressLine1": self.addressLine1(),
                    "addressLine2": self.addressLine2(),
                    "addressLine3": self.addressLine3(),
                    "addressLine4": self.addressLine4(),
                    "assignmentPercentage": self.assignmentPercentage(),
                    "accountCurrency": self.accountCurrency(),
                    "assignedamount": self.assignedamount(),
                    "account": self.account(),
                    "recordStat": "W",
                    "id": self.id()
                };

                if (self.action === "edit") {
                    self.assigneeArray.replace(selectdRecord, rec);
                } else if (self.action === "add") {
                    self.assigneeArray.push(rec);
                }
                self.refreshTable();
                self.closeDialog();
            });

        };
        self.validateassignee = function () {
            var promises = [];
            promises.push($("#tfpm-vp-assignee_assignmentPercentage").get(0).validate());
            promises.push($("#tfpm-vp-assignee_assignedamount").get(0).validate());
            promises.push($("#tfpm-vp-assignee_assigneeId").get(0).validate());
            promises.push($("#tfpm-vp-assignee-accountnumber").get(0).validate());
            promises.push($("#tfpm-vp-assignee_sequence").get(0).validate());
            promises.push($("#tfpm-vp-assignee_accountCurrency").get(0).validate());
            return Promise.all(promises);
        };
        self.lcAssignee = function () {
            self.setLcAssignedData = null;
            var entityUrl = "?&offset=0&limit=0&contractReferenceNumber=" + self.drawings().lcDetails.boReferenceNumber;
            var promise = self.tfpmvpassigneemodel.fetchEntity("OBTFPM.GET_LC_QUERY", entityUrl);
            promise.then(function (response) {
                if (response.contractDetails !== null && response.contractDetails.assigneeDtls.assignees !== null) {
                    self.setLcAssignedData = response.contractDetails.assigneeDtls;
                }
            }).catch(function (error) {
                self.loader.hide();
                self.alert.get(0).alert("error", "Error", self.cmnMessageLabels.fetchLCDetailFail);
                return Promise.reject(self.cmnMessageLabels.errContract + error);
            });
        }

        self.isNullOrUndefined = function (value) {
            if (value === undefined || value === null || value === "") {
                return true;
            }
            return false;
        };

        self.validate = function () {
            self.errorMessageArray = [];
            var assignedamountSum = 0;
            var assignedpercentageSum = 0;
            self.assigneedata = self.getModelData();
            $.each(self.assigneedata, function () {
                if (this.recordStat !== "D") {
                    assignedamountSum += this.assignedamount;
                    assignedpercentageSum += this.assignmentPercentage;
                }
            });
            if (self.baseComputationAmount < assignedamountSum) {
                self.errorMessageArray.push({
                    "errorMessage": "Total Assigned Amount should not be greater than Bill Amount",
                    "errorType": "E"
                });
            }
            if (assignedpercentageSum > 100) {
                self.errorMessageArray.push({
                    "errorMessage": "Assigned Percentage is more than 100% of Contract Amount",
                    "errorType": "E"
                });
            }
            if (self.transactionContextData.processCode === "ILCDRW" ||
                self.transactionContextData.processCode === "ILCUDR") {
                self.assigneeBcData = self.assigneeArray();
                if (self.assigneeBcData.length > 0 && (!self.assignedByUs() || self.assignedByUs() === "N")) {
                    self.errorMessageArray.push({
                        "errorMessage": "If Assignee details captured then Assignment Paid by Importer flag should be checked",
                        "errorType": "E"
                    });
                }
            }

            if (self.transactionContextData.processCode === "ELCDRW" ||
                self.transactionContextData.processCode === "ELCUDR" || self.transactionContextData.processCode === "ELCLIQ") {
                self.assigneeBcData = self.assigneeArray();
                if (self.setLcAssignedData.length !== self.assigneeBcData.length && self.setLcAssignedData.length > 0) {
                    self.errorMessageArray.push({
                        "errorMessage": "Defaulted Assignee Id cannot be deleted or changed",
                        "errorType": "E"
                    });
                }
                if (self.assigneeBcData.length < self.setLcAssignedData.length && self.setLcAssignedData.length > 0) {
                    self.errorMessageArray.push({
                        "errorMessage": "Deletion of defaulted id is Not Allowed in Bills ",
                        "errorType": "E"
                    });
                }
                if (self.setLcAssignedData.length > 0 && self.assigneeBcData.length > 0) {
                    for (var i = 0; i < self.setLcAssignedData.length; i++) {
                        if (!self.isNullOrUndefined(self.assigneeBcData[i]) && self.setLcAssignedData[i].assigneeId !== self.assigneeBcData[i].assigneeId) {
                            self.errorMessageArray.push({
                                "errorMessage": "Defaulted Assignee Id cannot be deleted or changed",
                                "errorType": "E"
                            });
                        }
                    }
                 }

                 if (self.setLcAssignedData.length > 0 && self.assigneeBcData.length > 0) {
                    for (var k = 0; k < self.setLcAssignedData.length; k++) {
                        if (!self.isNullOrUndefined(self.assigneeBcData[k]) && self.setLcAssignedData[k].assigneeId === self.assigneeBcData[k].assigneeId && self.assigneeBcData[k].assignedamount > self.setLcAssignedData[k].assignedamount) {
                            self.errorMessageArray.push({
                                "errorMessage": "Assigned Amount is more than available amount. ",
                                "errorType": "E"
                            });
                        }
                    }

                }
            }
            return self.errorMessageArray;
        };

        self.refreshTable = function () {
            var element = document.getElementById("tfpm-vp-assignee-assigneeTable");
            element.refresh();
        };
        self.closeDialog = function () {
            self.dialogElm().ojDialog("close");
        };
        //  var defaultRecord = [];
        self.setModelData = function (data) {
            if (data !== null && data.assignees && data.assignees.length !== 0) {
                //self.disableViewButton(false);
                $.each(data.assignees, function () {
                    var currRec = {
                        "select": ko.observableArray([]),
                        "sequence": this.sequence,
                        "assigneeId": this.assigneeId,
                        "assigneeName": this.assigneeName,
                        "addressLine1": this.addressLine1,
                        "addressLine2": this.addressLine2,
                        "addressLine3": this.addressLine3,
                        "addressLine4": this.addressLine4,
                        "assignmentPercentage": this.assignmentPercentage,
                        "accountCurrency": this.accountCurrency,
                        "assignedamount": self.baseComputationAmount * (this.assignmentPercentage / 100),
                        "account": this.account,
                        "recordStat": this.recordStat,
                        "id": this.id
                    };
                    self.assigneeArray.push(currRec);
                });
            }
        };
        self.getModelData = function () {
            var assigneeDtls = [];
            $.each(self.assigneeArray(), function () {
                var rec = self.getRecord(this);
                assigneeDtls.push(rec);
            });
            $.each(self.deletedAssigneeRecords(), function () {
                var rec = self.getRecord(this);
                assigneeDtls.push(rec);
            });
            return assigneeDtls;
        };
        self.assigneedata = null;
        self.getRequest = function () {

            request.processCode = self.transactionContextData.processCode;
            request.eventCode = self.transactionContextData.stageId;
            request.domainId = self.transactionContextData.parentId;
            request.applicationCategoryCode = self.transactionContextData.processCode;
            request.taskOutcome = null;
            request.dataSegmentCode = "fsgbu-ob-tfpm-vp-assignee";
            request.dataSegmentName = "Assignment of proceeds";
            request.applicationNumber = self.transactionContextData.applicationNumber;
            request.hopId = "ASSIGNEE";
            request.overrideAccept = self.overrideAccept();
            request.assigneeDtls.domainId = self.transactionContextData.parentId;
            request.assigneeDtls.assignees = self.assigneedata;
            if (self.transactionContextData.processCode !== "ELCAMD") {
                request.drawings = self.drawings();
                request.drawings.additionalDetails.assignedByUs = self.assignedByUs() ? "Y" : "N";
            }
        };
        var request = {};
        request.assigneeDtls = {};
        request.drawings = {};
        self.getRecord = function (currentRecord) {
            return {
                "sequence": currentRecord.sequence,
                "assigneeId": currentRecord.assigneeId,
                "assigneeName": currentRecord.assigneeName,
                "addressLine1": currentRecord.addressLine1,
                "addressLine2": currentRecord.addressLine2,
                "addressLine3": currentRecord.addressLine3,
                "addressLine4": currentRecord.addressLine4,
                "assignmentPercentage": currentRecord.assignmentPercentage,
                "accountCurrency": currentRecord.accountCurrency,
                "assignedamount": currentRecord.assignedamount,
                "account": currentRecord.account,
                "recordStat": currentRecord.recordStat,
                "id": currentRecord.id
            };
        };

        self.fetch = function () {
            self.loader.show();
            var resourceUrl = "?applicationNumber=" + self.transactionContextData.applicationNumber + "&eventCode=" + self.transactionContextData.stageId + "&dataSegmentCode=fsgbu-ob-tfpm-vp-assignee&referenceId=" + self.transactionContextData.parentId;
            var assigneeEntity = self.tfpmvpassigneemodel.fetchEntity("OBTFPM.GET_FACADE", resourceUrl);
            assigneeEntity.then(function (result) {
                if (self.readonly() && (result.assigneeDtls === null || result.assigneeDtls.assignees.length === 0)) {
                    self.alert.get(0).alert("information", "Information", self.cmnMessageLabels.AssigneeNotAvl);
                } else {
                    if (self.transactionContextData.processCode === "ELCAMD") {
                        self.baseComputationAmount = result.letterOfCreditDetails.amount;
                    } else {
                        self.baseComputationAmount = result.drawings.amount;
                    }
                    if (result.drawings !== null) {
                        self.assignedByUs(result.drawings.additionalDetails.assignedByUs === "Y" ? true : false);
                        self.drawings(result.drawings);
                    }
                    self.lcAssignee();
                    self.setModelData(result.assigneeDtls);
                }
                self.loader.hide();
            }).catch(function (error) {
                self.loader.hide();
                self.alert.get(0).alert("error", "Error", error);
                return Promise.reject(self.cmnMessageLabels.errAssDetails + error);
            });

        };
        /**
         * This optional method may be implemented on the ViewModel to perform initialization tasks.
         * This method will be invoked only if the ViewModel specified during registration is
         * an object instance as opposed to a constructor function. If the registered ViewModel is
         * a constructor function, the same context object will be passed to the constructor function
         * instead. If this method returns a Promise, activation will be delayed until the Promise is resolved.
         **/
        self.initialize = function (context) { /*optional*/
        };
        /**
         * This optional method may be implemented on the ViewModel and will be invoked after the ViewModel is initialized.
         **/
        self.activated = function (context) { /*optional*/
        };
        /**
         * This optional method may be implemented on the ViewModel and will be invoked after the
         * View is inserted into the document DOM.
         **/
        self.attached = function (context) {
            if (self.transactionContextData && self.transactionContextData.applicationNumber !== "")
                self.fetch();

        };
        /**
         * This optional method may be implemented on the ViewModel and will be invoked after the
         * bindings are applied on this View.
         **/
        self.bindingsApplied = function (context) {
            self.dialogElm($(element).find("#tfpm-vp-assignee_assigneeDetailsDialog"));
        };
        /**
         * This optional method may be implemented on the ViewModel and will be invoked when this
         * composite component is being disposed.
         **/
        self.dispose = function (element) { /*optional*/
        };

    }
    return mainContentViewModel;
}); 

Javascript Online Compiler

Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.

About Javascript

Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.

Key Features

  • Open-source
  • Just-in-time compiled language
  • Embedded along with HTML and makes web pages alive
  • Originally named as LiveScript.
  • Executable in both browser and server which has Javascript engines like V8(chrome), SpiderMonkey(Firefox) etc.

Syntax help

STDIN Example

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log("Hello, " + line);
});

variable declaration

KeywordDescriptionScope
varVar is used to declare variables(old way of declaring variables)Function or global scope
letlet is also used to declare variables(new way)Global or block Scope
constconst is used to declare const values. Once the value is assigned, it can not be modifiedGlobal or block Scope

Backtick Strings

Interpolation

let greetings = `Hello ${name}`

Multi line Strings

const msg = `
hello
world!
`

Arrays

An array is a collection of items or values.

Syntax:

let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);

Example:

let mobiles = ["iPhone", "Samsung", "Pixel"];

// accessing an array
console.log(mobiles[0]);

// changing an array element
mobiles[3] = "Nokia";

Arrow functions

Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.

Syntax:

() => expression

Example:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
                                    .map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);

De-structuring

Arrays

let [firstName, lastName] = ['Foo', 'Bar']

Objects

let {firstName, lastName} = {
  firstName: 'Foo',
  lastName: 'Bar'
}

rest(...) operator

 const {
    title,
    firstName,
    lastName,
    ...rest
  } = record;

Spread(...) operator

//Object spread
const post = {
  ...options,
  type: "new"
}
//array spread
const users = [
  ...adminUsers,
  ...normalUsers
]

Functions

function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
  console.log(`Hello ${name}!`);
}
 
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar

Loops

1. If:

IF is used to execute a block of code based on a condition.

Syntax

if(condition){
    // code
}

2. If-Else:

Else part is used to execute the block of code when the condition fails.

Syntax

if(condition){
    // code
} else {
    // code
}

3. Switch:

Switch is used to replace nested If-Else statements.

Syntax

switch(condition){
    case 'value1' :
        //code
        [break;]
    case 'value2' :
        //code
        [break;]
    .......
    default :
        //code
        [break;]
}

4. For

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
//code  
} 

5. While

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
  // code 
}  

6. Do-While

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
  // code 
} while (condition); 

Classes

ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.

Syntax:

class className {
  constructor() { ... } //Mandatory Class method
  method1() { ... }
  method2() { ... }
  ...
}

Example:

class Mobile {
  constructor(model) {
    this.name = model;
  }
}

mbl = new Mobile("iPhone");