<commit_before>smartApp.service('ChangeSwapSimService', function($timeout, SystemService) {
    var demo = SystemService.demo;

    this.getSIMData = function(msisdn, fnCallback) {
        var that = this;

        if (utils.isEmpty(msisdn)) {
            msisdn = '';
        }

        var cb = function(result) {
            result.data = that.decorateSIMData(result.data);

            fnCallback(result);
        };

        if (!demo) {
            var target = '/aftersales/tmv/swapsim/validateswapsim?msisdn=' + msisdn;

            SystemService.callServiceGetByPass(target, null, function(result) {
                cb(result);
            });
        } else {
            var data = {
                "status": "SUCCESSFUL",
                "display-messages": [{
                    "message": "Please contact 0891990135 VIP Team Number before swap SIM for VIP Customer ",
                    "message-code": "TMV-SWAPSIM-00001",
                    "message-type": "WARNING",
                    "en-message": "Please contact 0891990135 VIP Team Number before swap SIM for VIP Customer ",
                    "th-message": "เลขหมายนี้เป็นกลุ่ม VIP จะดำเนินการใดๆต้องแจ้งกับทาง ทีม VIP ก่อนเท่านั้น โปรดติดต่อ 0891990135"
                }],
                "trx-id": "3Z1N7RSSP1HYN",
                "process-instance": "tmsapnpr1 (instance: SFF_node4)",
                "response-data": {
                    "customer": {
                        "title": "นางสาว",
                        "title-code": "T3",
                        "firstname": "กุมารีหริลักษณ์",
                        "lastname": "จันทรรัศมี",
                        "contact-number": "",
                        "contact-mobile-number": "",
                        "id-type": "I",
                        "id-number": "1189900130607",
                        "customer-id": "2592",
                        "installed-products": [{
                            "ouId": "921",
                            "ban": "10000543",
                            "product-category": "TMV",
                            "product-type": "PRICEPLAN",
                            "product-status": "",
                            "number-status": "A",
                            "account-category": "I",
                            "account-sub-type": "FVI",
                            "product-id": "RFSMTP01",
                            "product-name": "RFSMTP01",
                            "product-description": "(4G) Smart 999 voice 500mins net7GB",
                            "company-code": "RF",
                            "product-id-name": "MSISDN",
                            "product-id-number": "0939860540",
                            "mobile-servicetype": "POSTPAID",
                            "has-splitcharge": false,
                            "is-childsim": false,
                            "is-softsuspend": false,
                            "company-code-desc": "True Move H - Real Future",
                            "is-4g": false
                        }]
                    }
                }
            };

            var data2 = {
                'status': 'SUCCESSFUL',
                'trx-id': '3BDPN2HLK4TZ',
                'process-instance': 'psaapdv1 (instance: SFF_node1)',
                'status-code': '0',
                'display-messages': [{
                    'message': '',
                    'message-type': 'ERROR',
                    'en-message': 'ERR',
                    'th-message': '',
                    'technical-message': ''
                }]
            };

            $timeout(function() {
                cb({
                    status: true,
                    data: data,
                    error: '',
                    msgErr: ''
                });
            }, 1000);
        }
    };

    this.decorateSIMData = function(data) {
        SystemService.hideLoading();
        var customerProfile = angular.copy(utils.getObject(data, 'response-data.customer'));
        var productDetails = utils.getObject(customerProfile, 'installed-products.0');

        var displayMsg = utils.getObject(data, 'display-messages.0');
        if (!customerProfile || !productDetails || (displayMsg && displayMsg['message-type'])) {
            setTimeout(function() {
                SystemService.showAlert(displayMsg);
            }, 1200);

            //return null;

        }

        delete customerProfile['installed-products'];

        // Prepare product type
        var productType = '';
        var serviceType = productDetails['mobile-servicetype'];
        if (serviceType === 'PREPAID') {
            productType = 'ทรูมูฟเอช เติมเงิน';
        } else {
            productType = 'ทรูมูฟเอช รายเดือน';
        }

        // Prepare current price plan
        var currentPricePlan = [];
        if (productDetails['product-name']) {
            currentPricePlan.push(productDetails['product-name']);
        }
        if (productDetails['product-description']) {
            currentPricePlan.push(productDetails['product-description']);
        }

        var response = {
            'header': {
                'producttype': productType,
                'subscriberno': productDetails['product-id-number'],
                'currpriceplan': currentPricePlan.join(': ')

            },
            'customerProfile': customerProfile,
            'simData': productDetails
        };

        return response;
    };

    this.validateSIM = function(payload, fnCallback) {
        payload['project'] = 'SWAPSIM-' + payload['mobile-servicetype'];

        var params = utils.createParamGet(payload, [
            'sim-serial',
            'dealer-code',
            'company-code',
            'mobile-servicetype',
            'product-code',
            'project',
            'pair-msisdn'
        ]);

        var cb = function(result) {
            fnCallback(result);
        };

        if (!demo) {
            var target = '/aftersales/order/tmv/validateswapsim?' + params;

            SystemService.callServiceGetByPass(target, null, function(result) {
                cb(result);
            });
        } else {
            var data = {
                'status': 'SUCCESSFUL',
                'display-messages': [],
                'trx-id': '3BYUAFJC01W8',
                'process-instance': 'tmsapnpr1 (instance: SFF_node1)',
                'status-code': '0',
                'response-data': {
                    'sim-detail': {
                        'pin1': 'String',
                        'pin2': 'String',
                        'puk1': 'String',
                        'puk2': 'String',
                        'hlr': 'String',
                        'item-id': 'String',
                        'item-desc': 'String',
                        'manuf': 'String',
                        'model': 'String',
                        'imei-status': 'String',
                        'active-ind': 'String',
                        'missing-ind': 'String',
                        'repair-ind': 'String',
                        'ta-ind': 'String',
                        'primary-ctn': 'String',
                        'nl': 'String',
                        'ngp': 'String',
                        'sim-type': 'S',
                        'serial-type': 'String',
                        'serial-no': 'String',
                        'sys-creation-date': 'String',
                        'sys-update-date': 'String',
                        'resource-status': 'AVAILABLE',
                        'activity-code': 'String',
                        'activity-date': 'String',
                        'activity-reason': 'String',
                        'imsi': 'String',
                        'product-type': 'String',
                        'imei-desc': 'String',
                        'dealer-code': 'String',
                        'manf-code': 'String',
                        'item-cat': 'String',
                        'item-subcat': 'String',
                        'cpo-ind': 'String',
                        'init-pin1': 'String',
                        'init-pin2': 'String',
                        'sim-type-desc': 'String',
                        'logical-hlr': 'String',
                        'police-station': 'String',
                        'report-date': 'String',
                        'sim-physical-hlr': 'String',
                        'ctn': 'String',
                        'ctn-status': 'String',
                        'ctn-company-code': 'String',
                        'sim-company-code': 'String',
                        'ctn-pool-code': 'String',
                        'ctn-pool-type': 'String',
                        'transaction-id': 'String',
                        'error-message': 'String',
                        'product-code': '3000014924'
                    }
                }
            };

            var data2 = {
                "status": "UNSUCCESSFUL",
                "display-messages": [{
                    "message": "request sim prefix  is wrong format for company(RM)",
                    "message-code": "",
                    "message-type": "ERROR",
                    "en-message": "request sim prefix  is wrong format for company(RM)",
                    "th-message": "request sim prefix  is wrong format for company(RM)",
                    "technical-message": "request sim prefix  is wrong format for company(RM)"
                }],
                "trx-id": "4Q15KDZCTBQYP",
                "process-instance": "tmsapnpr1 (instance: SFF_node4)",
                "response-data": {}
            };

            $timeout(function() {
                cb({
                    status: true,
                    data: data,
                    error: '',
                    msgErr: ''
                });
            }, 1000);
        }
    };

    this.submitSwapSIMOrder = function(payload, fnCallback) {
        var request = {
            'order': {
                'order-id': payload.orderData.orderId,
                'creator': payload.saleAgent['logInName'],
                //'create-date': moment().format('YYYY-MM-DDTHH:mm:ss+0700'),
                'customer': {
                    'title-code': payload.customerProfile['title-code'],
                    'title': payload.customerProfile['title'],
                    'firstname': payload.customerProfile['firstname'],
                    'lastname': payload.customerProfile['lastname'],
                    //'gender': null,
                    'id-type': payload.customerProfile['id-type'],
                    'id-number': payload.customerProfile['id-number'],
                    //'birthdate': '2015-07-20T00:00:00+0700',
                    //'id-expire-date': null,
                    'contact-number': payload.customerProfile['contact-number'],
                    'contact-mobile-number': payload.customerProfile['contact-mobile-number'],
                    //'contact-email': 'chitchai@cmail.com',
                    //'customer-agents': {
                    //  'AUTH_1': {
                    //      'contact': '0868836665',
                    //      'id-number': '9988877688845',
                    //      'id-type': 'I',
                    //      'firstname': 'สมคิด',
                    //      'lastname': 'คิดมากไป',
                    //      'birthdate': '2015-07-20T00:00:00+0700'
                    //  }
                    //    ,
                    //  'POA': {
                    //      'contact': '0868836664',
                    //      'id-number': '3257588733945',
                    //      'id-type': 'I',
                    //      'firstname': 'สมชาย',
                    //      'lastname': 'ปากสว่าง',
                    //      'birthdate': '2015-07-20T00:00:00+0700'
                    //  },
                    //  'AUTH_2': {
                    //      'contact': '0868836666',
                    //      'id-number': '9988877687723',
                    //      'id-type': 'I',
                    //      'firstname': 'สมฤดี',
                    //      'lastname': 'ดีเกินไป',
                    //      'birthdate': '2015-07-20T00:00:00+0700'
                    //  }
                    //}
                },
                'sale-agent': {
                    'name': payload.saleAgent['engName'],
                    'channel': payload.saleAgent['channel'],
                    'partner-code': (payload.saleAgent["partnerCodes"].length > 0 ? payload.saleAgent["partnerCodes"][0] : null),
                    'partner-name': payload.saleAgent['partnerName'],
                    'sale-code': payload.saleAgent['saleCode'],
                    'sale-assist-code': "",
                    'partner-type': payload.saleAgent['partnerType']
                },
                'order-items': [{
                        'name': 'SWAP_SIM',
                        'product-name': payload.simData['product-id'],
                        'product-id-number': payload.simData['product-id-number'],
                        'product-id-name': payload.simData['product-id-name'],
                        'product-category': payload.simData['product-category'],
                        'product-type': 'PRICEPLAN',
                        'order-type': 'CHANGE',
                        //'reason-code': 'AA02',
                        //'user-memo': 'Customer want to request .',
                        'order-data': {
                            'OU-ID': payload.simData['ouId'],
                            'BAN': payload.simData['ban'],
                            'PREPAID-SUBSCRIBER-ID': payload.simData['prepaid-subscriber-id'],
                            'IMSI': payload.simData['product-id-number'],
                            'CUSTOMER-ID': payload.customerProfile['customer-id'],
                            'SIM-OWNER': payload.simDetail['dealer-code']
                        },
                        'primary-order-data': {
                            'MOBILE-SERVICETYPE': payload.simData['mobile-servicetype'],
                            'ACCOUNT-CATEGORY': payload.simData['account-category'],
                            'ACCOUNT-SUB-TYPE': payload.simData['account-sub-type'],
                            'COMPANY-CODE': payload.simData['company-code'],
                            'PRODUCT-CODE': payload.newSIMData['productCodes'],
                            'SIM': payload.newSIMData['simSerial']
                        }
                    }]
                    //,'last-modify-date': ''
            },
            'ref-id': payload.orderData.TrxID,
            'user-id': payload.saleAgent['logInName'],
            'approver': payload.orderData.approver,
            'target': '/aftersales/order/submit'
        };
        console.log(request);
        var cb = function(result) {
            fnCallback(result);
        };

        if (!demo) {
            //var target = '/aftersales/order/submit';

            SystemService.callServicePost(request, null, function(result) {
                cb(result);
            });
        } else {
            var data = {
                'status': 'SUCCESSFUL',
                'display-messages': [{
                    'message': 'Order ' + payload.orderData.orderId + ' successful saved.',
                    'message-type': 'ERROR',
                    'en-message': 'Order ' + payload.orderData.orderId + ' successful saved.',
                    'th-message': 'บันทึกข้อมูลเรียบร้อย Order ' + payload.orderData.orderId + ' successful saved.'
                }],
                'trx-id': '03J5HVSFXH8R',
                'process-instance': 'tpx61.true.th (instance: sale)'
            };

            $timeout(function() {
                cb({
                    status: true,
                    data: data,
                    error: '',
                    msgErr: ''
                });
            }, 1000);
        }
    };

});
<commit_msg>Update case dealer Input Number again<commit_after>smartApp.service('ChangeSwapSimService', function($timeout, SystemService) {
    var demo = SystemService.demo;

    this.getSIMData = function(msisdn, fnCallback) {
        var that = this;

        if (utils.isEmpty(msisdn)) {
            msisdn = '';
        }

        var cb = function(result) {
            result.data = that.decorateSIMData(result.data);

            fnCallback(result);
        };

        if (!demo) {
            var target = '/aftersales/tmv/swapsim/validateswapsim?msisdn=' + msisdn;

            SystemService.callServiceGetByPass(target, null, function(result) {
                cb(result);
            });
        } else {
            var data = {
                "status": "SUCCESSFUL",
                "display-messages": [{
                    "message": "Please contact 0891990135 VIP Team Number before swap SIM for VIP Customer ",
                    "message-code": "TMV-SWAPSIM-00001",
                    "message-type": "WARNING",
                    "en-message": "Please contact 0891990135 VIP Team Number before swap SIM for VIP Customer ",
                    "th-message": "เลขหมายนี้เป็นกลุ่ม VIP จะดำเนินการใดๆต้องแจ้งกับทาง ทีม VIP ก่อนเท่านั้น โปรดติดต่อ 0891990135"
                }],
                "trx-id": "3Z1N7RSSP1HYN",
                "process-instance": "tmsapnpr1 (instance: SFF_node4)",
                "response-data": {
                    "customer": {
                        "title": "นางสาว",
                        "title-code": "T3",
                        "firstname": "กุมารีหริลักษณ์",
                        "lastname": "จันทรรัศมี",
                        "contact-number": "",
                        "contact-mobile-number": "",
                        "id-type": "I",
                        "id-number": "1189900130607",
                        "customer-id": "2592",
                        "installed-products": [{
                            "ouId": "921",
                            "ban": "10000543",
                            "product-category": "TMV",
                            "product-type": "PRICEPLAN",
                            "product-status": "",
                            "number-status": "A",
                            "account-category": "I",
                            "account-sub-type": "FVI",
                            "product-id": "RFSMTP01",
                            "product-name": "RFSMTP01",
                            "product-description": "(4G) Smart 999 voice 500mins net7GB",
                            "company-code": "RF",
                            "product-id-name": "MSISDN",
                            "product-id-number": "0939860540",
                            "mobile-servicetype": "POSTPAID",
                            "has-splitcharge": false,
                            "is-childsim": false,
                            "is-softsuspend": false,
                            "company-code-desc": "True Move H - Real Future",
                            "is-4g": false
                        }]
                    }
                }
            };

            var data2 = {
                'status': 'SUCCESSFUL',
                'trx-id': '3BDPN2HLK4TZ',
                'process-instance': 'psaapdv1 (instance: SFF_node1)',
                'status-code': '0',
                'display-messages': [{
                    "message": "External service [CCB_INT] response error. ACAHblG10001-Data not found.",
                    "message-code": "WSC-00001",
                    "message-type": "WARNING",
                    "en-message": "External service [CCB_INT] response error. ACAHblG10001-Data not found.",
                    "technical-message": "CCB_INT response ACAHblG10001: Data not found. on service url http://172.19.194.63:8280/SearchCustomerInfoWS/SearchCustomerInfoSI."
                }]
            };

            if (msisdn == "0957730500") {

                $timeout(function() {
                    cb({
                        status: true,
                        data: data,
                        error: '',
                        msgErr: ''
                    });
                }, 1000);
            } else {
                $timeout(function() {
                    cb({
                        status: true,
                        data: data2,
                        error: '',
                        msgErr: ''
                    });
                }, 1000);
            }
        }
    };

    this.decorateSIMData = function(data) {
        SystemService.hideLoading();
        var customerProfile = angular.copy(utils.getObject(data, 'response-data.customer'));
        var productDetails = utils.getObject(customerProfile, 'installed-products.0');

        var displayMsg = utils.getObject(data, 'display-messages.0');
        if (!customerProfile || !productDetails || (displayMsg && displayMsg['message-type'])) {
            setTimeout(function() {
                SystemService.showAlert(displayMsg);
            }, 1200);

            //return null;

        }

        delete customerProfile['installed-products'];

        // Prepare product type
        var productType = '';
        var serviceType = productDetails['mobile-servicetype'];
        if (serviceType === 'PREPAID') {
            productType = 'ทรูมูฟเอช เติมเงิน';
        } else {
            productType = 'ทรูมูฟเอช รายเดือน';
        }

        // Prepare current price plan
        var currentPricePlan = [];
        if (productDetails['product-name']) {
            currentPricePlan.push(productDetails['product-name']);
        }
        if (productDetails['product-description']) {
            currentPricePlan.push(productDetails['product-description']);
        }

        var response = {
            'header': {
                'producttype': productType,
                'subscriberno': productDetails['product-id-number'],
                'currpriceplan': currentPricePlan.join(': ')

            },
            'customerProfile': customerProfile,
            'simData': productDetails
        };

        return response;
    };

    this.validateSIM = function(payload, fnCallback) {
        payload['project'] = 'SWAPSIM-' + payload['mobile-servicetype'];

        var params = utils.createParamGet(payload, [
            'sim-serial',
            'dealer-code',
            'company-code',
            'mobile-servicetype',
            'product-code',
            'project',
            'pair-msisdn'
        ]);

        var cb = function(result) {
            fnCallback(result);
        };

        if (!demo) {
            var target = '/aftersales/order/tmv/validateswapsim?' + params;

            SystemService.callServiceGetByPass(target, null, function(result) {
                cb(result);
            });
        } else {
            var data = {
                'status': 'SUCCESSFUL',
                'display-messages': [],
                'trx-id': '3BYUAFJC01W8',
                'process-instance': 'tmsapnpr1 (instance: SFF_node1)',
                'status-code': '0',
                'response-data': {
                    'sim-detail': {
                        'pin1': 'String',
                        'pin2': 'String',
                        'puk1': 'String',
                        'puk2': 'String',
                        'hlr': 'String',
                        'item-id': 'String',
                        'item-desc': 'String',
                        'manuf': 'String',
                        'model': 'String',
                        'imei-status': 'String',
                        'active-ind': 'String',
                        'missing-ind': 'String',
                        'repair-ind': 'String',
                        'ta-ind': 'String',
                        'primary-ctn': 'String',
                        'nl': 'String',
                        'ngp': 'String',
                        'sim-type': 'S',
                        'serial-type': 'String',
                        'serial-no': 'String',
                        'sys-creation-date': 'String',
                        'sys-update-date': 'String',
                        'resource-status': 'AVAILABLE',
                        'activity-code': 'String',
                        'activity-date': 'String',
                        'activity-reason': 'String',
                        'imsi': 'String',
                        'product-type': 'String',
                        'imei-desc': 'String',
                        'dealer-code': 'String',
                        'manf-code': 'String',
                        'item-cat': 'String',
                        'item-subcat': 'String',
                        'cpo-ind': 'String',
                        'init-pin1': 'String',
                        'init-pin2': 'String',
                        'sim-type-desc': 'String',
                        'logical-hlr': 'String',
                        'police-station': 'String',
                        'report-date': 'String',
                        'sim-physical-hlr': 'String',
                        'ctn': 'String',
                        'ctn-status': 'String',
                        'ctn-company-code': 'String',
                        'sim-company-code': 'String',
                        'ctn-pool-code': 'String',
                        'ctn-pool-type': 'String',
                        'transaction-id': 'String',
                        'error-message': 'String',
                        'product-code': '3000014924'
                    }
                }
            };

            var data2 = {
                "status": "UNSUCCESSFUL",
                "display-messages": [{
                    "message": "request sim prefix  is wrong format for company(RM)",
                    "message-code": "",
                    "message-type": "ERROR",
                    "en-message": "request sim prefix  is wrong format for company(RM)",
                    "th-message": "request sim prefix  is wrong format for company(RM)",
                    "technical-message": "request sim prefix  is wrong format for company(RM)"
                }],
                "trx-id": "4Q15KDZCTBQYP",
                "process-instance": "tmsapnpr1 (instance: SFF_node4)",
                "response-data": {}
            };

            $timeout(function() {
                cb({
                    status: true,
                    data: data,
                    error: '',
                    msgErr: ''
                });
            }, 1000);
        }
    };

    this.submitSwapSIMOrder = function(payload, fnCallback) {
        var request = {
            'order': {
                'order-id': payload.orderData.orderId,
                'creator': payload.saleAgent['logInName'],
                //'create-date': moment().format('YYYY-MM-DDTHH:mm:ss+0700'),
                'customer': {
                    'title-code': payload.customerProfile['title-code'],
                    'title': payload.customerProfile['title'],
                    'firstname': payload.customerProfile['firstname'],
                    'lastname': payload.customerProfile['lastname'],
                    //'gender': null,
                    'id-type': payload.customerProfile['id-type'],
                    'id-number': payload.customerProfile['id-number'],
                    //'birthdate': '2015-07-20T00:00:00+0700',
                    //'id-expire-date': null,
                    'contact-number': payload.customerProfile['contact-number'],
                    'contact-mobile-number': payload.customerProfile['contact-mobile-number'],
                    //'contact-email': 'chitchai@cmail.com',
                    //'customer-agents': {
                    //  'AUTH_1': {
                    //      'contact': '0868836665',
                    //      'id-number': '9988877688845',
                    //      'id-type': 'I',
                    //      'firstname': 'สมคิด',
                    //      'lastname': 'คิดมากไป',
                    //      'birthdate': '2015-07-20T00:00:00+0700'
                    //  }
                    //    ,
                    //  'POA': {
                    //      'contact': '0868836664',
                    //      'id-number': '3257588733945',
                    //      'id-type': 'I',
                    //      'firstname': 'สมชาย',
                    //      'lastname': 'ปากสว่าง',
                    //      'birthdate': '2015-07-20T00:00:00+0700'
                    //  },
                    //  'AUTH_2': {
                    //      'contact': '0868836666',
                    //      'id-number': '9988877687723',
                    //      'id-type': 'I',
                    //      'firstname': 'สมฤดี',
                    //      'lastname': 'ดีเกินไป',
                    //      'birthdate': '2015-07-20T00:00:00+0700'
                    //  }
                    //}
                },
                'sale-agent': {
                    'name': payload.saleAgent['engName'],
                    'channel': payload.saleAgent['channel'],
                    'partner-code': (payload.saleAgent["partnerCodes"].length > 0 ? payload.saleAgent["partnerCodes"][0] : null),
                    'partner-name': payload.saleAgent['partnerName'],
                    'sale-code': payload.saleAgent['saleCode'],
                    'sale-assist-code': "",
                    'partner-type': payload.saleAgent['partnerType']
                },
                'order-items': [{
                        'name': 'SWAP_SIM',
                        'product-name': payload.simData['product-id'],
                        'product-id-number': payload.simData['product-id-number'],
                        'product-id-name': payload.simData['product-id-name'],
                        'product-category': payload.simData['product-category'],
                        'product-type': 'PRICEPLAN',
                        'order-type': 'CHANGE',
                        //'reason-code': 'AA02',
                        //'user-memo': 'Customer want to request .',
                        'order-data': {
                            'OU-ID': payload.simData['ouId'],
                            'BAN': payload.simData['ban'],
                            'PREPAID-SUBSCRIBER-ID': payload.simData['prepaid-subscriber-id'],
                            'IMSI': payload.simData['product-id-number'],
                            'CUSTOMER-ID': payload.customerProfile['customer-id'],
                            'SIM-OWNER': payload.simDetail['dealer-code']
                        },
                        'primary-order-data': {
                            'MOBILE-SERVICETYPE': payload.simData['mobile-servicetype'],
                            'ACCOUNT-CATEGORY': payload.simData['account-category'],
                            'ACCOUNT-SUB-TYPE': payload.simData['account-sub-type'],
                            'COMPANY-CODE': payload.simData['company-code'],
                            'PRODUCT-CODE': payload.newSIMData['productCodes'],
                            'SIM': payload.newSIMData['simSerial']
                        }
                    }]
                    //,'last-modify-date': ''
            },
            'ref-id': payload.orderData.TrxID,
            'user-id': payload.saleAgent['logInName'],
            'approver': payload.orderData.approver,
            'target': '/aftersales/order/submit'
        };
        console.log(request);
        var cb = function(result) {
            fnCallback(result);
        };

        if (!demo) {
            //var target = '/aftersales/order/submit';

            SystemService.callServicePost(request, null, function(result) {
                cb(result);
            });
        } else {
            var data = {
                'status': 'SUCCESSFUL',
                'display-messages': [{
                    'message': 'Order ' + payload.orderData.orderId + ' successful saved.',
                    'message-type': 'ERROR',
                    'en-message': 'Order ' + payload.orderData.orderId + ' successful saved.',
                    'th-message': 'บันทึกข้อมูลเรียบร้อย Order ' + payload.orderData.orderId + ' successful saved.'
                }],
                'trx-id': '03J5HVSFXH8R',
                'process-instance': 'tpx61.true.th (instance: sale)'
            };

            $timeout(function() {
                cb({
                    status: true,
                    data: data,
                    error: '',
                    msgErr: ''
                });
            }, 1000);
        }
    };

});
<|endoftext|>


<commit_before>// Leaflet Map js
var lats_longs;
function placeMarkers(dataArray) {
	lats_longs = dataArray;
  if(monroePilot) {
    for(var i = 0; i < dataArray.length; i++) {
      var a = dataArray[i];
      var address = a[0];
      var mapIcon = L.icon({
          iconUrl: '/assets/marker-icon-vacant.png',
          shadowUrl: '/assets/marker-shadow.png',
          iconAnchor:   [0, 0], // point of the icon which will correspond to marker's location
          shadowAnchor: [4, 62],  // the same for the shadow
          popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
      });
      // Turn on below once we've fixed the positioning and have implemented color icons
      //var marker = L.marker(new L.LatLng(a[1],a[2]) , {icon: mapIcon} , { address: address });
      var marker = L.marker(new L.LatLng(a[1],a[2]) , { address: address });
      marker.bindPopup("" + address + "");
      marker.addTo(map);
    }
  }
  else {
    var markers = new L.MarkerClusterGroup( { showCoverageOnHover: false } );
    for(var i = 0; i < dataArray.length; i++) {
      var a = dataArray[i];
      var address = a[0];
      var mapIcon = L.icon({
          iconUrl: '/assets/marker-icon-vacant.png',
          shadowUrl: '/assets/marker-shadow.png',
          iconAnchor:   [10, 7], // point of the icon which will correspond to marker's location
          shadowAnchor: [10, 7]
      });
      // Turn on below once we've fixed the positioning and have implemented color icons
      //var marker = L.marker(new L.LatLng(a[1],a[2]) , {icon: mapIcon} , { address: address } );
      var marker = L.marker(new L.LatLng(a[1],a[2]) , { address: address } );
      marker.bindPopup("" + address + "" + "
" + "call-in code:");
      markers.addLayer(marker);
    }
    map.addLayer(markers);
  }
}

$(document).ready(function() {
  drawMap();
  audiojs.events.ready(function() {
    var as = audiojs.createAll();
  });
});

function drawMap () {
	console.log('drawMap')
  if(monroePilot) {
    window.map = L.mapbox.map('map','codeforamerica.map-stwhr1eg').setView([41.6696, -86.246], 16);
  }
  else {
    window.map = L.mapbox.map('map','codeforamerica.map-stwhr1eg').setView([41.665, -86.28], 13);
  }
	$.getJSON('assets/lats_longs.json', success = placeMarkers);
	$( "#dialog" ).dialog();
	$( "#dialog" ).dialog({ width: 295 });
	$( "#dialog" ).dialog({ position: { my: "left top", at: "left+50 bottom+60", of: "head"} });
}

// Expand Section js

(function($){"use strict";function e(){var e=this;e.defaults={hideMode:"fadeToggle",defaultSearchMode:"parent",defaultTarget:".content",throwOnMissingTarget:!0,keepStateInCookie:!1,cookieName:"simple-expand"},e.settings={},$.extend(e.settings,e.defaults),e.findLevelOneDeep=function(e,t,n){return e.find(t).filter(function(){return!$(this).parentsUntil(e,n).length})},e.setInitialState=function(t,n){var r=e.readState(t);r?(t.removeClass("collapsed").addClass("expanded"),e.show(n)):(t.removeClass("expanded").addClass("collapsed"),e.hide(n))},e.hide=function(t){e.settings.hideMode==="fadeToggle"?t.hide():e.settings.hideMode==="basic"&&t.hide()},e.show=function(t){e.settings.hideMode==="fadeToggle"?t.show():e.settings.hideMode==="basic"&&t.show()},e.checkKeepStateInCookiePreconditions=function(){if(e.settings.keepStateInCookie&&$.cookie===undefined)throw new Error("simple-expand: keepStateInCookie option requires $.cookie to be defined.")},e.readCookie=function(){var t=$.cookie(e.settings.cookieName);return t===null||t===""?{}:JSON.parse(t)},e.readState=function(t){if(!e.settings.keepStateInCookie)return!1;var n=t.attr("Id");if(n===undefined)return;var r=e.readCookie(),i=r[n]===!0||!1;return i},e.saveState=function(t,n){if(!e.settings.keepStateInCookie)return;var r=t.attr("Id");if(r===undefined)return;var i=e.readCookie();i[r]=n,$.cookie(e.settings.cookieName,JSON.stringify(i),{raw:!0,path:window.location.pathname})},e.toggle=function(t,n){var r=e.toggleCss(t);return e.settings.hideMode==="fadeToggle"?n.fadeToggle(150):e.settings.hideMode==="basic"?n.toggle():$.isFunction(e.settings.hideMode)&&e.settings.hideMode(t,n,r),e.saveState(t,r),!1},e.toggleCss=function(e){return e.hasClass("expanded")?(e.toggleClass("collapsed expanded"),!1):(e.toggleClass("expanded collapsed"),!0)},e.findTargets=function(t,n,r){var i=[];if(n==="absolute")i=$(r);else if(n==="relative")i=e.findLevelOneDeep(t,r,r);else if(n==="parent"){var s=t.parent();do i=e.findLevelOneDeep(s,r,r),i.length===0&&(s=s.parent());while(i.length===0&&s.length!==0)}return i},e.activate=function(t,n){$.extend(e.settings,n),e.checkKeepStateInCookiePreconditions(),t.each(function(){var t=$(this),n=t.attr("data-expander-target")||e.settings.defaultTarget,r=t.attr("data-expander-target-search")||e.settings.defaultSearchMode,i=e.findTargets(t,r,n);if(i.length===0){if(e.settings.throwOnMissingTarget)throw"simple-expand: Targets not found";return this}e.setInitialState(t,i),t.click(function(){return e.toggle(t,i)})})}}window.SimpleExpand=e,$.fn.simpleexpand=function(t){var n=new e;return n.activate(this,t),this}})(jQuery);

  $(function() {
    $('.expander').simpleexpand();
    $('.expander').click();
  });

<commit_msg>modify map pop-up on landing page<commit_after>// Leaflet Map js
var lats_longs;
function placeMarkers(dataArray) {
	lats_longs = dataArray;
  if(monroePilot) {
    for(var i = 0; i < dataArray.length; i++) {
      var a = dataArray[i];
      var address = a[0];
      var mapIcon = L.icon({
          iconUrl: '/assets/marker-icon-vacant.png',
          shadowUrl: '/assets/marker-shadow.png',
          iconAnchor:   [0, 0], // point of the icon which will correspond to marker's location
          shadowAnchor: [4, 62],  // the same for the shadow
          popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
      });
      // Turn on below once we've fixed the positioning and have implemented color icons
      //var marker = L.marker(new L.LatLng(a[1],a[2]) , {icon: mapIcon} , { address: address });
      var marker = L.marker(new L.LatLng(a[1],a[2]) , { address: address });
      marker.bindPopup("" + address + "");
      marker.addTo(map);
    }
  }
  else {
    var markers = new L.MarkerClusterGroup( { showCoverageOnHover: false } );
    for(var i = 0; i < dataArray.length; i++) {
      var a = dataArray[i];
      var address = a[0];
      var mapIcon = L.icon({
          iconUrl: '/assets/marker-icon-vacant.png',
          shadowUrl: '/assets/marker-shadow.png',
          iconAnchor:   [10, 7], // point of the icon which will correspond to marker's location
          shadowAnchor: [10, 7]
      });
      // Turn on below once we've fixed the positioning and have implemented color icons
      //var marker = L.marker(new L.LatLng(a[1],a[2]) , {icon: mapIcon} , { address: address } );
      var marker = L.marker(new L.LatLng(a[1],a[2]) , { address: address } );
      marker.bindPopup("" + address + "" + "
" + "" + "Leave Feedback" + "");
      markers.addLayer(marker);
    }
    map.addLayer(markers);
  }
}

$(document).ready(function() {
  drawMap();
  audiojs.events.ready(function() {
    var as = audiojs.createAll();
  });
});

function drawMap () {
	console.log('drawMap')
  if(monroePilot) {
    window.map = L.mapbox.map('map','codeforamerica.map-stwhr1eg').setView([41.6696, -86.246], 16);
  }
  else {
    window.map = L.mapbox.map('map','codeforamerica.map-stwhr1eg').setView([41.665, -86.28], 13);
  }
	$.getJSON('assets/lats_longs.json', success = placeMarkers);
	$( "#dialog" ).dialog();
	$( "#dialog" ).dialog({ width: 295 });
	$( "#dialog" ).dialog({ position: { my: "left top", at: "left+50 bottom+60", of: "head"} });
}

// Expand Section js

(function($){"use strict";function e(){var e=this;e.defaults={hideMode:"fadeToggle",defaultSearchMode:"parent",defaultTarget:".content",throwOnMissingTarget:!0,keepStateInCookie:!1,cookieName:"simple-expand"},e.settings={},$.extend(e.settings,e.defaults),e.findLevelOneDeep=function(e,t,n){return e.find(t).filter(function(){return!$(this).parentsUntil(e,n).length})},e.setInitialState=function(t,n){var r=e.readState(t);r?(t.removeClass("collapsed").addClass("expanded"),e.show(n)):(t.removeClass("expanded").addClass("collapsed"),e.hide(n))},e.hide=function(t){e.settings.hideMode==="fadeToggle"?t.hide():e.settings.hideMode==="basic"&&t.hide()},e.show=function(t){e.settings.hideMode==="fadeToggle"?t.show():e.settings.hideMode==="basic"&&t.show()},e.checkKeepStateInCookiePreconditions=function(){if(e.settings.keepStateInCookie&&$.cookie===undefined)throw new Error("simple-expand: keepStateInCookie option requires $.cookie to be defined.")},e.readCookie=function(){var t=$.cookie(e.settings.cookieName);return t===null||t===""?{}:JSON.parse(t)},e.readState=function(t){if(!e.settings.keepStateInCookie)return!1;var n=t.attr("Id");if(n===undefined)return;var r=e.readCookie(),i=r[n]===!0||!1;return i},e.saveState=function(t,n){if(!e.settings.keepStateInCookie)return;var r=t.attr("Id");if(r===undefined)return;var i=e.readCookie();i[r]=n,$.cookie(e.settings.cookieName,JSON.stringify(i),{raw:!0,path:window.location.pathname})},e.toggle=function(t,n){var r=e.toggleCss(t);return e.settings.hideMode==="fadeToggle"?n.fadeToggle(150):e.settings.hideMode==="basic"?n.toggle():$.isFunction(e.settings.hideMode)&&e.settings.hideMode(t,n,r),e.saveState(t,r),!1},e.toggleCss=function(e){return e.hasClass("expanded")?(e.toggleClass("collapsed expanded"),!1):(e.toggleClass("expanded collapsed"),!0)},e.findTargets=function(t,n,r){var i=[];if(n==="absolute")i=$(r);else if(n==="relative")i=e.findLevelOneDeep(t,r,r);else if(n==="parent"){var s=t.parent();do i=e.findLevelOneDeep(s,r,r),i.length===0&&(s=s.parent());while(i.length===0&&s.length!==0)}return i},e.activate=function(t,n){$.extend(e.settings,n),e.checkKeepStateInCookiePreconditions(),t.each(function(){var t=$(this),n=t.attr("data-expander-target")||e.settings.defaultTarget,r=t.attr("data-expander-target-search")||e.settings.defaultSearchMode,i=e.findTargets(t,r,n);if(i.length===0){if(e.settings.throwOnMissingTarget)throw"simple-expand: Targets not found";return this}e.setInitialState(t,i),t.click(function(){return e.toggle(t,i)})})}}window.SimpleExpand=e,$.fn.simpleexpand=function(t){var n=new e;return n.activate(this,t),this}})(jQuery);

  $(function() {
    $('.expander').simpleexpand();
    $('.expander').click();
  });

<|endoftext|>


<commit_before>function coordsIntheCanvas(coordsMouse){
    // index of the little square that have the event
    var xi = Math.floor((coordsMouse.x)/littleSL);
    var yi = Math.floor((coordsMouse.y + 16 - 15)/littleSL); // plus the misplace of the the brush minus the canvas misplace

    // coord in pixel of the little square that have the event
    var x = xi * littleSL;
    var y = yi * littleSL;

    var squareIndexEvent = yi*nbSquaresOneEdge + xi;
    return {xi: xi, yi: yi, x: x, y: y, squareIndexEvent: squareIndexEvent}
};

function selectASquare(coords){
    // if the square can be selected
    if(jsColors[coords.squareIndexEvent][0] < 0){
        selectedSquare[coords.squareIndexEvent] = selectedColor.style.backgroundColor;
        drawSelectedSquare();
    }
};

function unselectASquare(coords){
    // if the square was selected
    if(selectedSquare[coords.squareIndexEvent]){
        selectedSquare[coords.squareIndexEvent] = false;
        drawSelectedSquare();
    }
};

// TODO: May be to slow
function drawSelectedSquare(){
    contextToDraw.clearRect(0, 0, canvasWidth, canvasWidth);
    for(var i=0; i<selectedSquare.length; ++i){
        // if the square was selected
        if(selectedSquare[i]){
            var x = i % nbSquaresOneEdge * littleSL;
            var y = Math.floor(i / nbSquaresOneEdge) * littleSL;

            contextToDraw.fillStyle = selectedSquare[i];
            contextToDraw.fillRect(x, y, littleSL, littleSL);

        }
    }
};

// littleSquareIncrease must be even
function selectSquares(canvasToDraw){
    var lastFlyOverSquareIndex = -1;

    // for select square when mouse down
    var mouseDown = false;

    // the selected color Element
    var selectedColor = document.getElementById('selectedColor');

    // selected tool
    var pipette = document.getElementById("pipetteIcon");
    var eraser = document.getElementById("eraserIcon");

    canvasToDraw.addEventListener('mousemove', function(e) {
        var coords = coordsIntheCanvas(this.relMouseCoords(e));

        // if not mode pipette
        if(pipette.className != "selected" && lastFlyOverSquareIndex != coords.squareIndexEvent){ // don't recompute if it is the same square than before
            if(mouseDown && eraser.className != "selected"){
                selectASquare(coords);
            }
            else if(mouseDown){ // eraser mode
                unselectASquare(coords);
            }
            else{
                biggerSquareMouseOver(coords, canvasToDraw, selectedColor);
            }
        }
        lastFlyOverSquareIndex = coords.squareIndexEvent;
    }, false);

    canvasToDraw.addEventListener('mousedown', function(e) {
        var coords = coordsIntheCanvas(this.relMouseCoords(e));
        eventMouseOnTheCanvas(coords);
        mouseDown = true;

    }, false);

    canvasToDraw.addEventListener('mouseup', function(e) {
        mouseDown = false;
    }, false);

    canvasToDraw.addEventListener('click', function(event){
        var coords = coordsIntheCanvas(this.relMouseCoords(event));
        eventMouseOnTheCanvas(coords);
    }, false);

    function eventMouseOnTheCanvas(coords) {

        // if the pipette tool was selected and select color
        if(pipette.className == "selected"){
            var context;

            // if the square can be selected
            if(jsColors[coords.squareIndexEvent][0] < 0) context = canvasToDraw.getContext('2d');
            else context = coloredSquare.getContext('2d');
            var data = context.getImageData(coords.x, coords.y, 1, 1).data; // minus the misplace of the the pipette
            //TODO: Comprendre pourquoi
            var rgba = 'rgba(' + data[4] + ',' + data[5] + ',' + data[6] + ',' + data[7] + ')';

            selectedColor.style.backgroundColor = rgba;

        }
        else if(eraser.className == "selected") unselectASquare(coords);
        else selectASquare(coords);
    }
};

function biggerSquareMouseOver(coords, canvasToDraw, selectedColor){

    var littleSquareIncrease = 4;

    drawSelectedSquare();

    // if the square can be selected
    if(jsColors[coords.squareIndexEvent][0] < 0){
        var contextToDraw = canvasToDraw.getContext('2d');

        // take the color selected on the palette
        contextToDraw.fillStyle = selectedColor.style.backgroundColor;
        contextToDraw.fillRect(coords.x - littleSquareIncrease/2, coords.y - littleSquareIncrease/2, littleSL + littleSquareIncrease, littleSL + littleSquareIncrease);
    }
};

<commit_msg>no message<commit_after>function coordsIntheCanvas(coordsMouse){
    // index of the little square that have the event
    var xi = Math.floor((coordsMouse.x)/littleSL);
    var yi = Math.floor((coordsMouse.y + 16 - 15)/littleSL); // plus the misplace of the the brush minus the canvas misplace

    // coord in pixel of the little square that have the event
    var x = xi * littleSL;
    var y = yi * littleSL;

    var squareIndexEvent = yi*nbSquaresOneEdge + xi;
    return {xi: xi, yi: yi, x: x, y: y, squareIndexEvent: squareIndexEvent}
};

function selectASquare(coords){
    // if the square can be selected
    if(jsColors[coords.squareIndexEvent][0] < 0){
        selectedSquare[coords.squareIndexEvent] = selectedColor.style.backgroundColor;
        drawSelectedSquare();
    }
};

function unselectASquare(coords){
    // if the square was selected
    if(selectedSquare[coords.squareIndexEvent]){
        selectedSquare[coords.squareIndexEvent] = false;
        drawSelectedSquare();
    }
};

// TODO: May be to slow
function drawSelectedSquare(){
    contextToDraw.clearRect(0, 0, canvasWidth, canvasWidth);
    for(var i=0; i<selectedSquare.length; ++i){
        // if the square was selected
        if(selectedSquare[i]){
            var x = i % nbSquaresOneEdge * littleSL;
            var y = Math.floor(i / nbSquaresOneEdge) * littleSL;

            contextToDraw.fillStyle = selectedSquare[i];
            contextToDraw.fillRect(x, y, littleSL, littleSL);

        }
    }
};

// littleSquareIncrease must be even
function selectSquares(canvasToDraw){
    var lastFlyOverSquareIndex = -1;

    // for select square when mouse down
    var mouseDown = false;

    // the selected color Element
    var selectedColor = document.getElementById('selectedColor');

    // selected tool
    var pipette = document.getElementById("pipetteIcon");
    var eraser = document.getElementById("eraserIcon");

     canvasToDraw.addEventListener('mouseout', function(e) {
        drawSelectedSquare();
        lastFlyOverSquareIndex = -1;
     }, false);

    canvasToDraw.addEventListener('mousemove', function(e) {
        var coords = coordsIntheCanvas(this.relMouseCoords(e));

        // if not mode pipette
        if(pipette.className != "selected" && lastFlyOverSquareIndex != coords.squareIndexEvent){ // don't recompute if it is the same square than before
            if(mouseDown && eraser.className != "selected"){
                selectASquare(coords);
            }
            else if(mouseDown){ // eraser mode
                unselectASquare(coords);
            }
            else{
                biggerSquareMouseOver(coords, canvasToDraw, selectedColor);
            }
        }
        lastFlyOverSquareIndex = coords.squareIndexEvent;
    }, false);

    canvasToDraw.addEventListener('mousedown', function(e) {
        var coords = coordsIntheCanvas(this.relMouseCoords(e));
        eventMouseOnTheCanvas(coords);
        mouseDown = true;

    }, false);

    canvasToDraw.addEventListener('mouseup', function(e) {
        mouseDown = false;
    }, false);

    canvasToDraw.addEventListener('click', function(event){
        var coords = coordsIntheCanvas(this.relMouseCoords(event));
        eventMouseOnTheCanvas(coords);
    }, false);

    function eventMouseOnTheCanvas(coords) {

        // if the pipette tool was selected and select color
        if(pipette.className == "selected"){
            var context;

            // if the square can be selected
            if(jsColors[coords.squareIndexEvent][0] < 0) context = canvasToDraw.getContext('2d');
            else context = coloredSquare.getContext('2d');
            var data = context.getImageData(coords.x, coords.y, 1, 1).data; // minus the misplace of the the pipette
            //TODO: Comprendre pourquoi
            var rgba = 'rgba(' + data[4] + ',' + data[5] + ',' + data[6] + ',' + data[7] + ')';

            selectedColor.style.backgroundColor = rgba;

        }
        else if(eraser.className == "selected") unselectASquare(coords);
        else selectASquare(coords);
    }
};

function biggerSquareMouseOver(coords, canvasToDraw, selectedColor){

    var littleSquareIncrease = 4;

    drawSelectedSquare();

    // if the square can be selected
    if(jsColors[coords.squareIndexEvent][0] < 0){
        var contextToDraw = canvasToDraw.getContext('2d');

        // take the color selected on the palette
        contextToDraw.fillStyle = selectedColor.style.backgroundColor;
        contextToDraw.fillRect(coords.x - littleSquareIncrease/2, coords.y - littleSquareIncrease/2, littleSL + littleSquareIncrease, littleSL + littleSquareIncrease);
    }
};

<|endoftext|>


<commit_before>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

// TODO:  Add ajax function to load pictures based on properties object.

$(window).scroll(function () {
    if ($(window).scrollTop() > $('body').height() / 2) {
        $("div#page-scrollback-image").fadeIn();
    }
    else
    {
        $("div#page-scrollback-image").fadeOut();

    }
});

$(document).load(function(){
     if ($("#slider-nav").text() == "false"){
         $("a.slidesjs-navigation").hide();
         console.log("slider nav hidden.");
        };

});

$(document).ready(function(){
 call_document_ready_on_show_page();
});

function call_document_ready_on_show_page() {
           setupPagePopup();

    // update left to correct height.
    $("#page-middle-left").height($("#page-body").height() + parseInt($("#page-body").css("margin-top")))

    // check for full screen and adjust layout
    if ($("#full-screen").html() == "true")
    {
        $("div#page-middle-left").hide();
        $("div#content").width("100%");
        $('#Content').css('background',"white")

    }

    activate_slides();
   start_flex_sliders();
}

function start_flex_sliders() {
        slideshow_nav_pagination = $("#slider-nav").text();
        slideshow_effect = $("#slider-effect").text();
        slideshow_auto = $("#slider-auto").text() || "true"
        slideshow_speed = $("#slider-speed").text() || "5000"

    if ($('.flexslider').length > 0) {
        require("jquery.flexslider.js");
        $('.flexslider').flexslider({start: function () {
                $('#page-slider-gallary-page').fadeIn();
            }, directionNav: slideshow_nav_pagination, animationSpeed: 2000, slideshowSpeed: slideshow_speed});

    }
}

function activate_slides() {

    if (($("div#slides3").length > 0))
    {
        $("#page-slider-gallary-page").show();
    }
    else
    {
        $("#page-slider-gallary-page").hide();

    }

    console.log($("div#slides3 > div").length);

    if ($("div#slides3 > div").length > 1)
    {
        slideshow_width = parseInt($("#slider-width").text());
        slideshow_height = parseInt($("#slider-height").text());
        slideshow_nav_pagination = $("#slider-nav").text();
        slideshow_effect = $("#slider-effect").text();
        slideshow_auto = $("#slider-auto").text() || "true"
        slideshow_speed = $("#slider-speed").text() || "5000"

        $('#slides3').slidesjs({
            width: slideshow_width,
            height: slideshow_height,
            pagination: {
                active: true,
                // [boolean] Create pagination items.
                // You cannot use your own pagination. Sorry.
                effect: slideshow_effect
                        // [string] Can be either "slide" or "fade".
            },
            play: {
                active: false,
                // [boolean] Generate the play and stop buttons.
                // You cannot use your own buttons. Sorry.
                effect: slideshow_effect,
                // [string] Can be either "slide" or "fade".
                interval: 5000,
                // [number] Time spent on each slide in milliseconds.
                auto: false,
                // [boolean] Start playing the slideshow on load.
                //swap: true,
                // [boolean] show/hide stop and play buttons
                pauseOnHover: true,
                // [boolean] pause a playing slideshow on hover
                //    restartDelay: 2500
                // [number] restart delay on inactive slideshow
            },
            navigation: {
                active: slideshow_nav_pagination,
                // [boolean] Generates next and previous buttons.
                // You can set to false and use your own buttons.
                // User defined buttons must have the following:
                // previous button: class="slidesjs-previous slidesjs-navigation"
                // next button: class="slidesjs-n           ext slidesjs-navigation"
                effect: slideshow_effect
                        // [string] Can be either "slide" or "fade".
            }

        });

        if (($("div#slides3 div.slidesjs-container").length > 0))
        {

            if ($("#slider-nav").text() == "false") {
                $("a.slidesjs-navigation").hide();
            }
            ;

            $("div#slides3 .slidesjs-container").width($("#slider-width").text());
            $("div#slides3 .slidesjs-container").height($("#slider-height").text());
            $("div#slides3 .slidesjs-container div.slides_control").width($("#slider-width").text());
            $("div#slides3 .slidesjs-container div.slides_control").height($("#slider-height").text());
            $("div#slides3 .slidesjs-container div.slider-content").width($("#slider-width").text());
            $("div#slides3 .slidesjs-container div.slider-content").height($("#slider-height").text());

            //  slideshow_width = $("#slides").width();
            //  slideshow_height =$("#slides").height();

            slideshow_width = parseInt($("#slider-width").text());
            slideshow_height = parseInt($("#slider-height").text());

            slideshow_offset = $("#slides3").offset();
            slideshow_middle = (slideshow_height / 2) - ($("#slides3 .next-slide").height() / 2);

            $("#slides3 a.slidesjs-next").offset({
                top: slideshow_middle + slideshow_offset.top,
                left: slideshow_width + slideshow_offset.left + 17
            });

            $("#slides3 a.slidesjs-previous").offset({
                top: slideshow_middle + slideshow_offset.top,
                left: slideshow_offset.left - $("#slides3 .prev-slide").width() - 30
            });

            $("#slides3").css("overflow", "visible");

        }
    $("#page-slider-gallary-page").css("position", "absolute");

    }
    else
    {
        $("#page-slider-gallary-page").css("top", "0px");
        $("#page-slider-gallary-page").css("overflow", "hidden");

    }

}

function setupPagePopup() {
    $.each($('.page-popup-link'),function(){
        var  page_to_open = $(this).attr('href');
        $(this).attr('href','#');
        $(this).attr('onClick','return(0);');
        $(this).attr("page-to-open",page_to_open);
    // console.log(this);
    });

    $('.page-popup-link').click( function(){
        var  page_to_open = $(this).attr('page-to-open');
        var  page_name = $(this).attr('title') || "popup-page";

        $.ajax({
            url: page_to_open,
            success: function(data)
            {
                pageViewDialog = createAppDialog(page_name,data);
                $("div.ui-dialog-titlebar").hide();
                $("div.ui-dialog .ui-dialog-buttonpane").css("border-width","0px");
                $(".ui-dialog .ui-dialog-buttonpane button span").html("X");

                dialogHeight = $(".ui-dialog").height();
                dialogWidth = $(".ui-dialog").width();
                $(".ui-dialog").css("background", "none");
                 $(".ui-dialog").css("border", "none");

                $(".ui-dialog .ui-dialog-buttonpane").css("background", "none");

                $(".ui-dialog .ui-dialog-buttonpane button").css("position", "absolute");
                $(".ui-dialog .ui-dialog-buttonpane button").css("top", "40px");
                $(".ui-dialog .ui-dialog-buttonpane button").css("right", "40px");
                $(".ui-dialog .ui-resizable-se").css("display", "none");

                pageViewDialog.dialog('open');
                pageViewDialog.dialog({
                    close: function( event, ui ) {
                        $('#app-dialog').html("");
                        $('#app-dialog').dialog( "destroy" );
                    }
                });
            // require("roles/update_rights.js");
            // update_rights_callDocumentReady();

            // setupRolesSelection();
            }
        });
    });
}

<commit_msg>added settings capabilities to flex slider javascript config.<commit_after>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

// TODO:  Add ajax function to load pictures based on properties object.

$(window).scroll(function () {
    if ($(window).scrollTop() > $('body').height() / 2) {
        $("div#page-scrollback-image").fadeIn();
    }
    else
    {
        $("div#page-scrollback-image").fadeOut();

    }
});

$(document).load(function(){
     if ($("#slider-nav").text() == "false"){
         $("a.slidesjs-navigation").hide();
         console.log("slider nav hidden.");
        };

});

$(document).ready(function(){
 call_document_ready_on_show_page();
});

function call_document_ready_on_show_page() {
           setupPagePopup();

    // update left to correct height.
    $("#page-middle-left").height($("#page-body").height() + parseInt($("#page-body").css("margin-top")))

    // check for full screen and adjust layout
    if ($("#full-screen").html() == "true")
    {
        $("div#page-middle-left").hide();
        $("div#content").width("100%");
        $('#Content').css('background',"white")

    }

    activate_slides();
   start_flex_sliders();
}

function start_flex_sliders() {
        slideshow_nav_pagination = $("#slider-nav").text() === "true";
        slideshow_effect = $("#slider-effect").text();
        slideshow_auto = $("#slider-auto").text() || "true"
        slideshow_speed = $("#slider-speed").text() || "5000"

    if ($('.flexslider').length > 0) {
        require("jquery.flexslider.js");
        $('.flexslider').flexslider({start: function () {
                $('#page-slider-gallary-page').fadeIn();
            }, directionNav: slideshow_nav_pagination, animationSpeed: 2000, slideshowSpeed: slideshow_speed});

    }
}

function activate_slides() {

    if (($("div#slides3").length > 0))
    {
        $("#page-slider-gallary-page").show();
    }
    else
    {
        $("#page-slider-gallary-page").hide();

    }

    console.log($("div#slides3 > div").length);

    if ($("div#slides3 > div").length > 1)
    {
        slideshow_width = parseInt($("#slider-width").text());
        slideshow_height = parseInt($("#slider-height").text());
        slideshow_nav_pagination = $("#slider-nav").text();
        slideshow_effect = $("#slider-effect").text();
        slideshow_auto = $("#slider-auto").text() || "true"
        slideshow_speed = $("#slider-speed").text() || "5000"

        $('#slides3').slidesjs({
            width: slideshow_width,
            height: slideshow_height,
            pagination: {
                active: true,
                // [boolean] Create pagination items.
                // You cannot use your own pagination. Sorry.
                effect: slideshow_effect
                        // [string] Can be either "slide" or "fade".
            },
            play: {
                active: false,
                // [boolean] Generate the play and stop buttons.
                // You cannot use your own buttons. Sorry.
                effect: slideshow_effect,
                // [string] Can be either "slide" or "fade".
                interval: 5000,
                // [number] Time spent on each slide in milliseconds.
                auto: false,
                // [boolean] Start playing the slideshow on load.
                //swap: true,
                // [boolean] show/hide stop and play buttons
                pauseOnHover: true,
                // [boolean] pause a playing slideshow on hover
                //    restartDelay: 2500
                // [number] restart delay on inactive slideshow
            },
            navigation: {
                active: slideshow_nav_pagination,
                // [boolean] Generates next and previous buttons.
                // You can set to false and use your own buttons.
                // User defined buttons must have the following:
                // previous button: class="slidesjs-previous slidesjs-navigation"
                // next button: class="slidesjs-n           ext slidesjs-navigation"
                effect: slideshow_effect
                        // [string] Can be either "slide" or "fade".
            }

        });

        if (($("div#slides3 div.slidesjs-container").length > 0))
        {

            if ($("#slider-nav").text() == "false") {
                $("a.slidesjs-navigation").hide();
            }
            ;

            $("div#slides3 .slidesjs-container").width($("#slider-width").text());
            $("div#slides3 .slidesjs-container").height($("#slider-height").text());
            $("div#slides3 .slidesjs-container div.slides_control").width($("#slider-width").text());
            $("div#slides3 .slidesjs-container div.slides_control").height($("#slider-height").text());
            $("div#slides3 .slidesjs-container div.slider-content").width($("#slider-width").text());
            $("div#slides3 .slidesjs-container div.slider-content").height($("#slider-height").text());

            //  slideshow_width = $("#slides").width();
            //  slideshow_height =$("#slides").height();

            slideshow_width = parseInt($("#slider-width").text());
            slideshow_height = parseInt($("#slider-height").text());

            slideshow_offset = $("#slides3").offset();
            slideshow_middle = (slideshow_height / 2) - ($("#slides3 .next-slide").height() / 2);

            $("#slides3 a.slidesjs-next").offset({
                top: slideshow_middle + slideshow_offset.top,
                left: slideshow_width + slideshow_offset.left + 17
            });

            $("#slides3 a.slidesjs-previous").offset({
                top: slideshow_middle + slideshow_offset.top,
                left: slideshow_offset.left - $("#slides3 .prev-slide").width() - 30
            });

            $("#slides3").css("overflow", "visible");

        }
    $("#page-slider-gallary-page").css("position", "absolute");

    }
    else
    {
        $("#page-slider-gallary-page").css("top", "0px");
        $("#page-slider-gallary-page").css("overflow", "hidden");

    }

}

function setupPagePopup() {
    $.each($('.page-popup-link'),function(){
        var  page_to_open = $(this).attr('href');
        $(this).attr('href','#');
        $(this).attr('onClick','return(0);');
        $(this).attr("page-to-open",page_to_open);
    // console.log(this);
    });

    $('.page-popup-link').click( function(){
        var  page_to_open = $(this).attr('page-to-open');
        var  page_name = $(this).attr('title') || "popup-page";

        $.ajax({
            url: page_to_open,
            success: function(data)
            {
                pageViewDialog = createAppDialog(page_name,data);
                $("div.ui-dialog-titlebar").hide();
                $("div.ui-dialog .ui-dialog-buttonpane").css("border-width","0px");
                $(".ui-dialog .ui-dialog-buttonpane button span").html("X");

                dialogHeight = $(".ui-dialog").height();
                dialogWidth = $(".ui-dialog").width();
                $(".ui-dialog").css("background", "none");
                 $(".ui-dialog").css("border", "none");

                $(".ui-dialog .ui-dialog-buttonpane").css("background", "none");

                $(".ui-dialog .ui-dialog-buttonpane button").css("position", "absolute");
                $(".ui-dialog .ui-dialog-buttonpane button").css("top", "40px");
                $(".ui-dialog .ui-dialog-buttonpane button").css("right", "40px");
                $(".ui-dialog .ui-resizable-se").css("display", "none");

                pageViewDialog.dialog('open');
                pageViewDialog.dialog({
                    close: function( event, ui ) {
                        $('#app-dialog').html("");
                        $('#app-dialog').dialog( "destroy" );
                    }
                });
            // require("roles/update_rights.js");
            // update_rights_callDocumentReady();

            // setupRolesSelection();
            }
        });
    });
}

<|endoftext|>


<commit_before>import angular from 'angular';
import gmfRasterRasterService from 'gmf/raster/RasterService.js';

import ngeoMiscDebounce from 'ngeo/misc/debounce.js';

import * as olEvents from 'ol/events.js';

import 'bootstrap/js/src/dropdown.js';

/**
 * @type {!angular.IModule}
 * @hidden
*/
const module = angular.module('gmfRasterComponent', [
  gmfRasterRasterService.name,
  ngeoMiscDebounce.name,
]);

module.run(/* @ngInject */ ($templateCache) => {
  // @ts-ignore: webpack
  $templateCache.put('gmf/raster/widgetComponent', require('./widgetComponent.html'));
});

module.value('gmfElevationwidgetTemplateUrl',
  /**
   * @param {!angular.IAttributes} $attrs Attributes.
   * @return {string} The template url.
   */
  ($attrs) => {
    const templateUrl = $attrs['gmfElevationwidgetTemplateUrl'];
    return templateUrl !== undefined ? templateUrl :
      'gmf/raster/widgetComponent';
  });

/**
 * @hidden
 * @param {!angular.IAttributes} $attrs Attributes.
 * @param {!function(!angular.IAttributes): string} gmfElevationwidgetTemplateUrl Template function.
 * @return {string} Template URL.
 * @ngInject
 * @private
 * @hidden
 */
function gmfElevationwidgetTemplateUrl($attrs, gmfElevationwidgetTemplateUrl) {
  return gmfElevationwidgetTemplateUrl($attrs);
}

/**
 * Provide a directive that set a value each 500ms with the elevation under the
 * mouse cursor position on the map. The value must come from the elevation
 * service of a c2cgeoportal server. The server's URL must be defined as
 * config value of the application.
 *
 * Example:
 *
 *      <span gmf-elevation
 *            gmf-elevation-active="elevationActive"
 *            gmf-elevation-elevation="elevationValue"
 *            gmf-elevation-layer="mainCtrl.elevationLayer"
 *            gmf-elevation-layersconfig="::mainCtrl.elevationLayersConfig"
 *            gmf-elevation-map="::mainCtrl.map">
 *            {{elevationValue}}
 *      </span>
 *
 *  For value in meter `elevationLayersConfig` can be an empty object, complex example:
 *
 *      elevationLayersConfig = {
 *          '<layer>': {
 *              'filter': 'ngeoUnitPrefix',
 *              'args': ['m²', 'square'],
 *              'postfix': '<notice>',
 *              'separator': ''
 *          }
 *      };
 *
 *
 * @htmlAttribute {boolean} gmf-elevation-active A boolean to set active or
 *     deactivate the component.
 * @htmlAttribute {number} gmf-elevation-elevation The value to set with the
 *     elevation value.
 * @htmlAttribute {string} gmf-elevation-layer Elevation layer to use.
 * @htmlAttribute {Object.<string, LayerConfig>} gmf-elevation-layersconfig Elevation layer configurations.
 * @htmlAttribute {import("ol/Map.js").default} gmf-elevation-map The map.
 * @return {angular.IDirective} Directive Definition Object.
 * @ngdoc directive
 * @ngname gmfElevation
 */
function rasterComponent() {
  return {
    restrict: 'A',
    controller: 'GmfElevationController as ctrl',
    bindToController: true,
    scope: {
      'active': '<gmfElevationActive',
      'elevation': '=gmfElevationElevation',
      'layersconfig': '=gmfElevationLayersconfig',
      'loading': '=?gmfElevationLoading',
      'layer': '<gmfElevationLayer',
      'map': '=gmfElevationMap'
    },
    link: (scope, element, attr) => {
      const ctrl = scope['ctrl'];

      // Watch active or not.
      scope.$watch(() => ctrl.active, function(active) {
        this.toggleActive_(active);
      }.bind(ctrl));

      // Watch current layer.
      scope.$watch(() => ctrl.layer, function(layer) {
        this.layer = layer;
        this.elevation = null;
      }.bind(ctrl));
    }
  };
}

module.directive('gmfElevation', rasterComponent);

/**
 * @hidden
 * @param {!angular.IScope} $scope Scope.
 * @param {!angular.IFilterService} $filter Angular filter.
 * @param {!import("ngeo/misc/debounce.js").miscDebounce
 * <function(import("ol/MapBrowserPointerEvent.js").default): void>} ngeoDebounce Ngeo debounce factory
 * @param {!import("gmf/raster/RasterService.js").RasterService} gmfRaster Gmf Raster service
 * @param {!angular.gettext.gettextCatalog} gettextCatalog Gettext catalog.
 * @constructor
 * @private
 * @hidden
 * @ngInject
 * @ngdoc controller
 * @ngname gmfElevationController
 */
function Controller($scope, $filter, ngeoDebounce, gmfRaster, gettextCatalog) {

  /**
   * @type {!angular.IFilterService}
   * @private
   */
  this.filter_ = $filter;

  /**
   * @type {import("ngeo/misc/debounce.js").miscDebounce
   * <function(import("ol/MapBrowserPointerEvent.js").default): void>}
   * @private
   */
  this.ngeoDebounce_ = ngeoDebounce;

  /**
   * @type {import("gmf/raster/RasterService.js").RasterService}
   * @private
   */
  this.gmfRaster_ = gmfRaster;

  /**
   * @type {angular.gettext.gettextCatalog}
   * @private
   */
  this.gettextCatalog = gettextCatalog;

  /**
   * @type {!Object.<string, LayerConfig>}
   * @private
   */
  this.layersconfig;

  /**
   * @type {boolean}
   */
  this.active;

  /**
   * @type {!string|undefined}
   */
  this.elevation;

  /**
   * @type {string}
   */
  this.layer;

  /**
   * @type {import("ol/Map.js").default}
   */
  this.map;

  /**
   * @type {Array.<import("ol/events.js").EventsKey>}
   * @private
   */
  this.listenerKeys_ = [];

  /**
   * @type {angular.IScope}
   * @private
   */
  this.scope_ = $scope;

  /**
   * @type {boolean}
   * @private
   */
  this.inViewport_ = false;

  /**
   * @type {boolean}
   */
  this.loading = false;
}

/**
 * Activate or deactivate the request of the raster each 500 ms on pointermove.
 * @param {boolean} active true to make requests.
 * @private
 */
Controller.prototype.toggleActive_ = function(active) {
  this.elevation = undefined;
  if (active) {
    console.assert(this.listenerKeys_.length === 0);

    // Moving the mouse clears previously displayed elevation
    /**
     * @param {Event|import("ol/events/Event.js").default} event The event
     * @return {void}
     */
    const listen = (event) => {
      this.scope_.$apply(() => {
        this.inViewport_ = true;
        this.elevation = undefined;
        this.loading = false;
      });
    };
    this.listenerKeys_.push(olEvents.listen(this.map, 'pointermove', listen));

    // Launch the elevation service request when the user stops moving the
    // mouse for less short delay
    this.listenerKeys_.push(olEvents.listen(this.map, 'pointermove',
      this.ngeoDebounce_(this.pointerStop_.bind(this), 500, true)
    ));

    this.listenerKeys_.push(olEvents.listen(this.map.getViewport(), 'mouseout', () => {
      this.scope_.$apply(() => {
        this.elevation = undefined;
        this.inViewport_ = false;
        this.loading = false;
      });
    }));
  } else {
    this.elevation = undefined;
    this.listenerKeys_.forEach(olEvents.unlistenByKey);
    this.listenerKeys_.length = 0;
  }
};

/**
 * Request data from a raster from a MapBrowserPointerEvent's coordinates.
 * Called when the user stopped moving the mouse for 500ms.
 * @param {import("ol/MapBrowserPointerEvent.js").default} e An ol map browser pointer event.
 * @private
 */
Controller.prototype.pointerStop_ = function(e) {
  if (this.inViewport_) {
    this.loading = true;
    const params = {
      'layers': this.layer
    };
    this.gmfRaster_.getRaster(e.coordinate, params).then(
      this.getRasterSuccess_.bind(this),
      this.getRasterError_.bind(this)
    );
  }
};

/**
 * @param {Object.<string, number>} resp Response of the get Raster service.
 * @private
 */
Controller.prototype.getRasterSuccess_ = function(resp) {
  console.assert(this.layer, 'A layer should be selected');
  const value = resp[this.layer];
  if (value !== undefined && value !== null) {
    const options = this.layersconfig[this.layer] || {};
    const filter = options.filter || 'number';
    const custom_args = options.args || [];
    const postfix = options.hasOwnProperty('postfix') ? options.postfix : 'm';
    const separator = postfix.length > 0 ?
      (options.hasOwnProperty('separator') ? options.separator : '\u00a0') : '';
    const args = Array.prototype.concat([value], custom_args);
    this.elevation = this.filter_(filter)(...args) + separator + postfix;
  } else {
    const gettextCatalog = this.gettextCatalog;
    this.elevation = gettextCatalog.getString('No value');
  }
  this.loading = false;
};

/**
 * @private
 */
Controller.prototype.getRasterError_ = function() {
  console.error('Error on getting the raster.');
  this.elevation = undefined;
  this.loading = false;
};

module.controller('GmfElevationController', Controller);

/**
 * Provides a component which encapsulates the elevation component (see above)
 * in a button with dropdown menu to be included in a application directly.
 *
 * Example:
 *  <gmf-elevationwidget
 *      gmf-elevationwidget-map="::mainCtrl.map"
 *      gmf-elevationwidget-layers="::mainCtrl.elevationLayers"
 *      gmf-elevationwidget-layersconfig="::mainCtrl.elevationLayersConfig"
 *      gmf-elevationwidget-active="mainCtrl.showInfobar">
 *  </gmf-elevationwidget>
 *
 * @htmlAttribute {import("ol/Map.js").default} gmf-elevationwidget-map The map.
 * @htmlAttribute {Array.<string>} gmf-elevationwidget-layers The list of
 *     layers.
 * @htmlAttribute {boolean} gmf-elevationwidget-active Whether to activate the
 *     elevation component.
 *
 * @ngdoc component
 * @ngname gmfElevationwidget
 */
const rasterWidgetComponent = {
  controller: 'gmfElevationwidgetController as ctrl',
  bindings: {
    'map': '<gmfElevationwidgetMap',
    'layers': '<gmfElevationwidgetLayers',
    'layersconfig': '=gmfElevationwidgetLayersconfig',
    'active': '<gmfElevationwidgetActive'
  },
  templateUrl: gmfElevationwidgetTemplateUrl
};
module.component('gmfElevationwidget', rasterWidgetComponent);

/**
 * @constructor
 * @private
 * @hidden
 * @ngdoc controller
 */
function WidgetController() {
  /**
   * @type {!import("ol/Map.js").default}
   */
  this.map;

  /**
   * @type {!Array.<string>}
   */
  this.layers;

  /**
   * @type {!Object.<string, LayerConfig>}
   * @private
   */
  this.layersconfig;

  /**
   * @type {boolean}
   */
  this.active;

  /**
   * @type {string}
   */
  this.selectedElevationLayer;
}

WidgetController.prototype.$onInit = function() {
  this.selectedElevationLayer = this.layers[0];
};

module.controller('gmfElevationwidgetController', WidgetController);

/**
 * @typedef {Object} LayerConfig
 * @property {string} [filter]
 * @property {Array.<string>} [args]
 * @property {string} [postfix]
 * @property {string} [separator]
 */

export default module;
<commit_msg>Remove line break in param definition<commit_after>import angular from 'angular';
import gmfRasterRasterService from 'gmf/raster/RasterService.js';

import ngeoMiscDebounce from 'ngeo/misc/debounce.js';

import * as olEvents from 'ol/events.js';

import 'bootstrap/js/src/dropdown.js';

/**
 * @type {!angular.IModule}
 * @hidden
*/
const module = angular.module('gmfRasterComponent', [
  gmfRasterRasterService.name,
  ngeoMiscDebounce.name,
]);

module.run(/* @ngInject */ ($templateCache) => {
  // @ts-ignore: webpack
  $templateCache.put('gmf/raster/widgetComponent', require('./widgetComponent.html'));
});

module.value('gmfElevationwidgetTemplateUrl',
  /**
   * @param {!angular.IAttributes} $attrs Attributes.
   * @return {string} The template url.
   */
  ($attrs) => {
    const templateUrl = $attrs['gmfElevationwidgetTemplateUrl'];
    return templateUrl !== undefined ? templateUrl :
      'gmf/raster/widgetComponent';
  });

/**
 * @hidden
 * @param {!angular.IAttributes} $attrs Attributes.
 * @param {!function(!angular.IAttributes): string} gmfElevationwidgetTemplateUrl Template function.
 * @return {string} Template URL.
 * @ngInject
 * @private
 * @hidden
 */
function gmfElevationwidgetTemplateUrl($attrs, gmfElevationwidgetTemplateUrl) {
  return gmfElevationwidgetTemplateUrl($attrs);
}

/**
 * Provide a directive that set a value each 500ms with the elevation under the
 * mouse cursor position on the map. The value must come from the elevation
 * service of a c2cgeoportal server. The server's URL must be defined as
 * config value of the application.
 *
 * Example:
 *
 *      <span gmf-elevation
 *            gmf-elevation-active="elevationActive"
 *            gmf-elevation-elevation="elevationValue"
 *            gmf-elevation-layer="mainCtrl.elevationLayer"
 *            gmf-elevation-layersconfig="::mainCtrl.elevationLayersConfig"
 *            gmf-elevation-map="::mainCtrl.map">
 *            {{elevationValue}}
 *      </span>
 *
 *  For value in meter `elevationLayersConfig` can be an empty object, complex example:
 *
 *      elevationLayersConfig = {
 *          '<layer>': {
 *              'filter': 'ngeoUnitPrefix',
 *              'args': ['m²', 'square'],
 *              'postfix': '<notice>',
 *              'separator': ''
 *          }
 *      };
 *
 *
 * @htmlAttribute {boolean} gmf-elevation-active A boolean to set active or
 *     deactivate the component.
 * @htmlAttribute {number} gmf-elevation-elevation The value to set with the
 *     elevation value.
 * @htmlAttribute {string} gmf-elevation-layer Elevation layer to use.
 * @htmlAttribute {Object.<string, LayerConfig>} gmf-elevation-layersconfig Elevation layer configurations.
 * @htmlAttribute {import("ol/Map.js").default} gmf-elevation-map The map.
 * @return {angular.IDirective} Directive Definition Object.
 * @ngdoc directive
 * @ngname gmfElevation
 */
function rasterComponent() {
  return {
    restrict: 'A',
    controller: 'GmfElevationController as ctrl',
    bindToController: true,
    scope: {
      'active': '<gmfElevationActive',
      'elevation': '=gmfElevationElevation',
      'layersconfig': '=gmfElevationLayersconfig',
      'loading': '=?gmfElevationLoading',
      'layer': '<gmfElevationLayer',
      'map': '=gmfElevationMap'
    },
    link: (scope, element, attr) => {
      const ctrl = scope['ctrl'];

      // Watch active or not.
      scope.$watch(() => ctrl.active, function(active) {
        this.toggleActive_(active);
      }.bind(ctrl));

      // Watch current layer.
      scope.$watch(() => ctrl.layer, function(layer) {
        this.layer = layer;
        this.elevation = null;
      }.bind(ctrl));
    }
  };
}

module.directive('gmfElevation', rasterComponent);

/**
 * @hidden
 * @param {!angular.IScope} $scope Scope.
 * @param {!angular.IFilterService} $filter Angular filter.
 * @param {!import("ngeo/misc/debounce.js").miscDebounce<function(import("ol/MapBrowserPointerEvent.js").default): void>} ngeoDebounce Ngeo debounce factory
 * @param {!import("gmf/raster/RasterService.js").RasterService} gmfRaster Gmf Raster service
 * @param {!angular.gettext.gettextCatalog} gettextCatalog Gettext catalog.
 * @constructor
 * @private
 * @hidden
 * @ngInject
 * @ngdoc controller
 * @ngname gmfElevationController
 */
function Controller($scope, $filter, ngeoDebounce, gmfRaster, gettextCatalog) {

  /**
   * @private
   */
  this.filter_ = $filter;

  /**
   * @private
   */
  this.ngeoDebounce_ = ngeoDebounce;

  /**
   * @private
   */
  this.gmfRaster_ = gmfRaster;

  /**
   * @private
   */
  this.gettextCatalog = gettextCatalog;

  /**
   * @type {!Object.<string, LayerConfig>}
   * @private
   */
  this.layersconfig;

  /**
   * @type {boolean}
   */
  this.active;

  /**
   * @type {!string|undefined}
   */
  this.elevation;

  /**
   * @type {string}
   */
  this.layer;

  /**
   * @type {import("ol/Map.js").default}
   */
  this.map;

  /**
   * @type {Array.<import("ol/events.js").EventsKey>}
   * @private
   */
  this.listenerKeys_ = [];

  /**
   * @type {angular.IScope}
   * @private
   */
  this.scope_ = $scope;

  /**
   * @type {boolean}
   * @private
   */
  this.inViewport_ = false;

  /**
   * @type {boolean}
   */
  this.loading = false;
}

/**
 * Activate or deactivate the request of the raster each 500 ms on pointermove.
 * @param {boolean} active true to make requests.
 * @private
 */
Controller.prototype.toggleActive_ = function(active) {
  this.elevation = undefined;
  if (active) {
    console.assert(this.listenerKeys_.length === 0);

    // Moving the mouse clears previously displayed elevation
    /**
     * @param {Event|import("ol/events/Event.js").default} event The event
     * @return {void}
     */
    const listen = (event) => {
      this.scope_.$apply(() => {
        this.inViewport_ = true;
        this.elevation = undefined;
        this.loading = false;
      });
    };
    this.listenerKeys_.push(olEvents.listen(this.map, 'pointermove', listen));

    // Launch the elevation service request when the user stops moving the
    // mouse for less short delay
    this.listenerKeys_.push(olEvents.listen(this.map, 'pointermove',
      this.ngeoDebounce_(this.pointerStop_.bind(this), 500, true)
    ));

    this.listenerKeys_.push(olEvents.listen(this.map.getViewport(), 'mouseout', () => {
      this.scope_.$apply(() => {
        this.elevation = undefined;
        this.inViewport_ = false;
        this.loading = false;
      });
    }));
  } else {
    this.elevation = undefined;
    this.listenerKeys_.forEach(olEvents.unlistenByKey);
    this.listenerKeys_.length = 0;
  }
};

/**
 * Request data from a raster from a MapBrowserPointerEvent's coordinates.
 * Called when the user stopped moving the mouse for 500ms.
 * @param {import("ol/MapBrowserPointerEvent.js").default} e An ol map browser pointer event.
 * @private
 */
Controller.prototype.pointerStop_ = function(e) {
  if (this.inViewport_) {
    this.loading = true;
    const params = {
      'layers': this.layer
    };
    this.gmfRaster_.getRaster(e.coordinate, params).then(
      this.getRasterSuccess_.bind(this),
      this.getRasterError_.bind(this)
    );
  }
};

/**
 * @param {Object.<string, number>} resp Response of the get Raster service.
 * @private
 */
Controller.prototype.getRasterSuccess_ = function(resp) {
  console.assert(this.layer, 'A layer should be selected');
  const value = resp[this.layer];
  if (value !== undefined && value !== null) {
    const options = this.layersconfig[this.layer] || {};
    const filter = options.filter || 'number';
    const custom_args = options.args || [];
    const postfix = options.hasOwnProperty('postfix') ? options.postfix : 'm';
    const separator = postfix.length > 0 ?
      (options.hasOwnProperty('separator') ? options.separator : '\u00a0') : '';
    const args = Array.prototype.concat([value], custom_args);
    this.elevation = this.filter_(filter)(...args) + separator + postfix;
  } else {
    const gettextCatalog = this.gettextCatalog;
    this.elevation = gettextCatalog.getString('No value');
  }
  this.loading = false;
};

/**
 * @private
 */
Controller.prototype.getRasterError_ = function() {
  console.error('Error on getting the raster.');
  this.elevation = undefined;
  this.loading = false;
};

module.controller('GmfElevationController', Controller);

/**
 * Provides a component which encapsulates the elevation component (see above)
 * in a button with dropdown menu to be included in a application directly.
 *
 * Example:
 *  <gmf-elevationwidget
 *      gmf-elevationwidget-map="::mainCtrl.map"
 *      gmf-elevationwidget-layers="::mainCtrl.elevationLayers"
 *      gmf-elevationwidget-layersconfig="::mainCtrl.elevationLayersConfig"
 *      gmf-elevationwidget-active="mainCtrl.showInfobar">
 *  </gmf-elevationwidget>
 *
 * @htmlAttribute {import("ol/Map.js").default} gmf-elevationwidget-map The map.
 * @htmlAttribute {Array.<string>} gmf-elevationwidget-layers The list of
 *     layers.
 * @htmlAttribute {boolean} gmf-elevationwidget-active Whether to activate the
 *     elevation component.
 *
 * @ngdoc component
 * @ngname gmfElevationwidget
 */
const rasterWidgetComponent = {
  controller: 'gmfElevationwidgetController as ctrl',
  bindings: {
    'map': '<gmfElevationwidgetMap',
    'layers': '<gmfElevationwidgetLayers',
    'layersconfig': '=gmfElevationwidgetLayersconfig',
    'active': '<gmfElevationwidgetActive'
  },
  templateUrl: gmfElevationwidgetTemplateUrl
};
module.component('gmfElevationwidget', rasterWidgetComponent);

/**
 * @constructor
 * @private
 * @hidden
 * @ngdoc controller
 */
function WidgetController() {
  /**
   * @type {!import("ol/Map.js").default}
   */
  this.map;

  /**
   * @type {!Array.<string>}
   */
  this.layers;

  /**
   * @type {!Object.<string, LayerConfig>}
   * @private
   */
  this.layersconfig;

  /**
   * @type {boolean}
   */
  this.active;

  /**
   * @type {string}
   */
  this.selectedElevationLayer;
}

WidgetController.prototype.$onInit = function() {
  this.selectedElevationLayer = this.layers[0];
};

module.controller('gmfElevationwidgetController', WidgetController);

/**
 * @typedef {Object} LayerConfig
 * @property {string} [filter]
 * @property {Array.<string>} [args]
 * @property {string} [postfix]
 * @property {string} [separator]
 */

export default module;
<|endoftext|>


<commit_before>(function () {
	'use strict';
	var gulp = require('gulp'),
			  concat = require('gulp-concat'),
			  size = require('gulp-filesize'),
			  jshint = require('gulp-jshint'),
			  uglify = require('gulp-uglify');
	gulp.task('default', ['minify']);
	gulp.task('minify', function () {
		gulp.src('target/classes/ocelot-core.js')
				  .pipe(jshint())
				  .pipe(uglify())
				  .pipe(concat("ocelot-core-min.js"))
				  .pipe(size())
				  .pipe(gulp.dest('target/classes/'));
	});
})();
<commit_msg>gulp add show size file before and after add jshint reporter<commit_after>(function () {
	'use strict';
	var gulp = require('gulp'),
			  concat = require('gulp-concat'),
			  size = require('gulp-filesize'),
			  jshint = require('gulp-jshint'),
			  uglify = require('gulp-uglify');
	gulp.task('default', ['minify']);
	gulp.task('minify', function () {
		gulp.src('target/classes/ocelot-core.js')
				  .pipe(size())
				  .pipe(jshint())
				  .pipe(jshint.reporter('jshint-stylish'))
				  .pipe(uglify())
				  .pipe(concat("ocelot-core-min.js"))
				  .pipe(gulp.dest('target/classes/'));
		gulp.src('target/classes/ocelot-core-min.js')
				  .pipe(size());
	});
})();
<|endoftext|>


<commit_before>$(function () {

  var home_dirs = ["agenda", "projects"];
  var home_files = ["what", "where"];

  var set_directory_prompt = function(dirs) {
    if(dirs.length === 0) {
      $.set_prompt("geeko@hackweek:~ >");
    } else {
      $.set_prompt("geeko@hackweek:~/" + dirs.join("/") + " >");
    }
  };

  var projects = [
    {
      title: "Make a nifty hackweek website"
    },
    {
      title: "Do something great"
    }
  ];

  var directory_stack = [];

  var to_directories = function(dirs) {
    return $.map(dirs, function(e){
      return "" + e + "";
    }).join("
");
  };

  var to_files = function(files) {
    return $.map(files, function(e){
      return "" + e + "";
    }).join("
");
  };

  $.register_command('ls', function(){
    if(directory_stack.length == 0) {
      return [to_directories(home_dirs), to_files(home_files)].join("
");
    } else if(directory_stack[0] == "agenda") {
      if(directory_stack.length == 1) {
        return to_directories(Object.keys(agenda_content));
      } else {
        return to_files(Object.keys(agenda_content[directory_stack[1]]));
      }
    } else if(directory_stack[0] == "projects") {
      return to_files(Object.keys(projects_content));
    }
  });

  $.register_command('cd', function(args){
    if(directory_stack.length === 0 && $.inArray(args[1], home_dirs) >= 0) {
      directory_stack.push(args[1]);
    } else if(directory_stack.length === 1 &&
        directory_stack[0] === "agenda" &&
        $.inArray(args[1], Object.keys(agenda_content)) >= 0) {
      directory_stack.push(args[1]);
    } else if(args[1] === "..") {
      directory_stack.pop();
    } else {
      return "No such file or directory."
    }
    set_directory_prompt(directory_stack);
    return " ";
  });

  $.register_command('..', function(){
    directory_stack.pop();
    set_directory_prompt(directory_stack);
    return " ";
  });

  $.register_command('cat', function(args){
    if(directory_stack.length == 0 &&
        $.inArray(args[1], home_files) >= 0) {
      return other_content[args[1]].replace(/\n/g, "
");
    } else if(directory_stack.length == 2 &&
        directory_stack[0] == "agenda" &&
        $.inArray(args[1], Object.keys(agenda_content[directory_stack[1]])) >= 0) {
      return agenda_content[directory_stack[1]][args[1]].replace(/\n/g, "
");
    } else if(directory_stack.length == 1 &&
        directory_stack[0] == "projects" &&
        $.inArray(args[1], Object.keys(projects_content)) >= 0) {
      return projects_content[args[1]]
    } else {
      return "No such file or directory."
    }
  });

  $.register_command('open', function(args){
    if(directory_stack.length == 1 &&
        directory_stack[0] == "projects" &&
        $.inArray(args[1], Object.keys(projects_content)) >= 0) {
      var win = window.open(projects_content[args[1]], '_blank');
      win.focus();
      return "done";
    } else {
      return "No such file or directory."
    }
  });

  $.register_command('exit', function(){
    toggle_terminal();
  });

  $.register_command( 'help', function() {
    return "The most commonly used commands are:
" +
      "ls - List all content.
" +
      "cd - Change working directory
" +
      "cat <FILE> - Concatenate FILE, or standard input, to standard output.
" +
      "date - Returns Current Date
" +
      "open <filename> - Open the target in a new tab
" +
      "exit - Close terminal shell.
"
  });

// COPY AND PASTED FUNCTIONS, REMOVE ON PRODUCTION
  var command_directory = {
    'eval': function( tokens ) {
      tokens.shift();
      var expression = tokens.join( ' ' );
      var result = '';
      try {
        result = eval( expression );
      } catch( e ) {
        result = 'Error: ' + e.message;
    }
    return "" + result + "";
  },
    'date': function( tokens ) {
      var now = new Date();
      return "" + now.getDate() + '-' +
      now.getMonth() + '-' +
      ( 1900 + now.getYear() ) + ""
    },
    'cap': function( tokens ) {
      tokens.shift();
      return "" + tokens.join( ' ' ).toUpperCase() + "";
    },
    'go': function( tokens ) {
      var url = tokens[1];
      document.location.href = url;
    }
  };

  for( var j in command_directory ) {
    $.register_command( j, command_directory[j] );
  }

});<commit_msg>fix issue#25: termninal mode: > date is off by one month<commit_after>$(function () {

  var home_dirs = ["agenda", "projects"];
  var home_files = ["what", "where"];

  var set_directory_prompt = function(dirs) {
    if(dirs.length === 0) {
      $.set_prompt("geeko@hackweek:~ >");
    } else {
      $.set_prompt("geeko@hackweek:~/" + dirs.join("/") + " >");
    }
  };

  var projects = [
    {
      title: "Make a nifty hackweek website"
    },
    {
      title: "Do something great"
    }
  ];

  var directory_stack = [];

  var to_directories = function(dirs) {
    return $.map(dirs, function(e){
      return "" + e + "";
    }).join("
");
  };

  var to_files = function(files) {
    return $.map(files, function(e){
      return "" + e + "";
    }).join("
");
  };

  $.register_command('ls', function(){
    if(directory_stack.length == 0) {
      return [to_directories(home_dirs), to_files(home_files)].join("
");
    } else if(directory_stack[0] == "agenda") {
      if(directory_stack.length == 1) {
        return to_directories(Object.keys(agenda_content));
      } else {
        return to_files(Object.keys(agenda_content[directory_stack[1]]));
      }
    } else if(directory_stack[0] == "projects") {
      return to_files(Object.keys(projects_content));
    }
  });

  $.register_command('cd', function(args){
    if(directory_stack.length === 0 && $.inArray(args[1], home_dirs) >= 0) {
      directory_stack.push(args[1]);
    } else if(directory_stack.length === 1 &&
        directory_stack[0] === "agenda" &&
        $.inArray(args[1], Object.keys(agenda_content)) >= 0) {
      directory_stack.push(args[1]);
    } else if(args[1] === "..") {
      directory_stack.pop();
    } else {
      return "No such file or directory."
    }
    set_directory_prompt(directory_stack);
    return " ";
  });

  $.register_command('..', function(){
    directory_stack.pop();
    set_directory_prompt(directory_stack);
    return " ";
  });

  $.register_command('cat', function(args){
    if(directory_stack.length == 0 &&
        $.inArray(args[1], home_files) >= 0) {
      return other_content[args[1]].replace(/\n/g, "
");
    } else if(directory_stack.length == 2 &&
        directory_stack[0] == "agenda" &&
        $.inArray(args[1], Object.keys(agenda_content[directory_stack[1]])) >= 0) {
      return agenda_content[directory_stack[1]][args[1]].replace(/\n/g, "
");
    } else if(directory_stack.length == 1 &&
        directory_stack[0] == "projects" &&
        $.inArray(args[1], Object.keys(projects_content)) >= 0) {
      return projects_content[args[1]]
    } else {
      return "No such file or directory."
    }
  });

  $.register_command('open', function(args){
    if(directory_stack.length == 1 &&
        directory_stack[0] == "projects" &&
        $.inArray(args[1], Object.keys(projects_content)) >= 0) {
      var win = window.open(projects_content[args[1]], '_blank');
      win.focus();
      return "done";
    } else {
      return "No such file or directory."
    }
  });

  $.register_command('exit', function(){
    toggle_terminal();
  });

  $.register_command( 'help', function() {
    return "The most commonly used commands are:
" +
      "ls - List all content.
" +
      "cd - Change working directory
" +
      "cat <FILE> - Concatenate FILE, or standard input, to standard output.
" +
      "date - Returns Current Date
" +
      "open <filename> - Open the target in a new tab
" +
      "exit - Close terminal shell.
"
  });

// COPY AND PASTED FUNCTIONS, REMOVE ON PRODUCTION
  var command_directory = {
    'eval': function( tokens ) {
      tokens.shift();
      var expression = tokens.join( ' ' );
      var result = '';
      try {
        result = eval( expression );
      } catch( e ) {
        result = 'Error: ' + e.message;
    }
    return "" + result + "";
  },
    'date': function( tokens ) {
      var now = new Date();
      return "" + now.toDateString() + ""
    },
    'cap': function( tokens ) {
      tokens.shift();
      return "" + tokens.join( ' ' ).toUpperCase() + "";
    },
    'go': function( tokens ) {
      var url = tokens[1];
      document.location.href = url;
    }
  };

  for( var j in command_directory ) {
    $.register_command( j, command_directory[j] );
  }

});
<|endoftext|>