<commit_before>describe('OIDE Filetree', function(){

  //Helper function which returns true if the specified element has the specified class
  var classMatcherHelper = function(element, cls) {
    return element.getAttribute('class').then(function(classes){
      return classes.split(' ').indexOf(cls) !== -1;
    });
  };

  // Run tests for filetree

  it('should open the filetree when a node is clicked', function(){
    // Get the first filetree node
    var fileNode = $$('.tree-branch-head').first();
    // The element should have class fa-folder
    expect(classMatcherHelper(fileNode, 'fa-folder')).toBeTruthy();
    // Simulate click for the element
    fileNode.click();
    // The element should now have class fa-folder-open
    expect(classMatcherHelper(fileNode, 'fa-folder-open')).toBeTruthy();
    // On clicking again, the class should not be set to fa-folder-open
    fileNode.click();
    expect(classMatcherHelper(fileNode, 'fa-folder-open')).toBeFalsy();
  });

  it('should open the delete modal when delete is clicked', function(){
    $$('.tree-label').first().click().then(function(){
      $$('.filetree-btn').get(2).click(function() {
        var modalTitle = $('h3.modal-title');
        browser.wait(function() {
          return modalTitle.isDisplayed();
        }, 500);
        expect(modalTitle.getText()).toBe('Confirm Remove');
        $('.btn-danger').click();
      });
    });
  });

  it('should open the rename modal when rename is clicked', function(){
      $$('.tree-label').first().click().then(function(){
        $$('.tree-label').first().click();
        //click on rename
        var driver = browser.driver;
        driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
          driver.executeScript("arguments[0].click()", elements[4]).then(function() {
            //Expect modal to be displayed
            expect($('.modal').isDisplayed()).toBeTruthy();
            // Modal title should be Rename File
            expect($('.modal-title').getInnerHtml()).toBe('Rename File');
            $('.btn-danger').click();
          });
        });
      });
  });

  it('should open a file for editing', function(){
    var driver = browser.driver;
    var initialNumberOfFiles = 0;
    var newNumberOfFiles = 0;
    var fileNode = $$('.tree-branch-head').first().click(function() {
      // Make sure a file exists in the selected directory
      $$('.tree-label').first().click().then(function(){
        driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
          driver.executeScript("arguments[0].click()", elements[0]).then(function() {
            //Save the initial number of open files
            $$('tab-heading > span.ng-binding').then(function(elements){
              initialNumberOfFiles = elements.length;
              //Open a file
              $('li.tree-leaf > div').click(function(){
                //Click on edit file
                $$('.filetree-btn').get(0).click(function() {
                  $('.filetree-btn').click(function() {
                    expect($$('tab-heading > span.ng-binding').count()).toBe(initialNumberOfFiles+1);
                  });
                });
              });
            });
          });
        });
      });
    });
  });

  it('should create new file when new file is clicked', function(){
    var driver = browser.driver;
    var initialNumberOfFiles = 0;
    var finalNumberOfFiles = 0;
    $$('.tree-branch-head').first().click(function() {
      $$('.tree-label').first().click().then(function(){
        //Get initial number of files
        $$('.fa-file').then(function(files){
          initialNumberOfFiles = files.length;
          //click on new file
          driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
            driver.executeScript("arguments[0].click()", elements[0]).then(function() {
              expect($$('.fa-file').count()).toBe(initialNumberOfFiles + 1);
            });
          });
        });
      });
    });
  });

  it('should be able to duplicate a file', function(){
    // var fileNode = element.all(by.css('.tree-branch-head')).first();
    // fileNode.click();
    var driver = browser.driver;
    var initialNumberOfFiles = 0;
    var newNumberOfFiles = 0;
    //Save the initial number of open files

    var fileNode = $$('.tree-branch-head').first().click(function() {
      // Make sure a file exists in the selected directory
      $$('.tree-label').first().click().then(function(){
        driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
          driver.executeScript("arguments[0].click()", elements[0]).then(function() {
            $$('li.tree-leaf > div').then(function(elements){
              initialNumberOfFiles = elements.length;
              $('li.tree-leaf > div').click().then(function(){
                //Click on duplicate file
                $$('.filetree-btn').get(1).click(function() {
                  expect($$('li.tree-leaf > div').count()).toBe(initialNumberOfFiles + 1);
                });
              });
            });
          });
        });
      });
    });
  });

  it('should create a new folder', function(){
    var driver = browser.driver;
    var initialNumberOfFolders = 0;
    var finalNumberOfFolders = 0;
    $$('.tree-branch-head').first().click(function() {
      $$('.tree-label').first().click().then(function(){
        //Get initial number of folders
        $$('.fa-file').then(function(folders){
          initialNumberOfFolders = files.length;
          //click on new folder
          driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
            driver.executeScript("arguments[0].click()", elements[1]).then(function() {
              expect($$('.fa-folder').count()).toBe(initialNumberOfFolders + 1);
            });
          });
        });
      });
    });
  });

  it('should copy a file to clipboard and paste in a folder', function(){
    // var fileNode = element.all(by.css('.tree-branch-head')).first();
    // fileNode.click();
    var initialNumberOfFiles = 0;
    var newNumberOfFiles = 0;
    var driver = browser.driver;
    // Count the number of files
    $$('.tree-label').then(function(elements){
      initialNumberOfFiles = elements.length;
      //Click on first element
      elements[1].click().then(function(){
        // click on copy
        driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
          driver.executeScript("arguments[0].click()", elements[2]).then(function(){
            // Click paste
            driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
              driver.executeScript("arguments[0].click()", elements[3]).then(function(){
                // count elements
                $$('.tree-label').then(function(elements){
                  newNumberOfFiles = elements.length;
                  // Expect new number of files to be one more than initial number of files
                  expect(newNumberOfFiles).toBe(initialNumberOfFiles + 1);
                });
              });
            });
          });
        });
      });
    });
  });
});
<commit_msg>Finished rewriting existing E2E tests.<commit_after>describe('OIDE Filetree', function(){

  //Helper function which returns true if the specified element has the specified class
  var classMatcherHelper = function(element, cls) {
    return element.getAttribute('class').then(function(classes){
      return classes.split(' ').indexOf(cls) !== -1;
    });
  };

  // Run tests for filetree

  it('should open the filetree when a node is clicked', function(){
    // Get the first filetree node
    var fileNode = $$('.tree-branch-head').first();
    // The element should have class fa-folder
    expect(classMatcherHelper(fileNode, 'fa-folder')).toBeTruthy();
    // Simulate click for the element
    fileNode.click();
    // The element should now have class fa-folder-open
    expect(classMatcherHelper(fileNode, 'fa-folder-open')).toBeTruthy();
    // On clicking again, the class should not be set to fa-folder-open
    fileNode.click();
    expect(classMatcherHelper(fileNode, 'fa-folder-open')).toBeFalsy();
  });

  it('should open the delete modal when delete is clicked', function(){
    $$('.tree-label').first().click().then(function(){
      $$('.filetree-btn').get(2).click(function() {
        var modalTitle = $('h3.modal-title');
        browser.wait(function() {
          return modalTitle.isDisplayed();
        }, 500);
        expect(modalTitle.getText()).toBe('Confirm Remove');
        $('.btn-danger').click();
      });
    });
  });

  it('should open the rename modal when rename is clicked', function(){
      $$('.tree-label').first().click().then(function(){
        $$('.tree-label').first().click();
        //click on rename
        var driver = browser.driver;
        driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
          driver.executeScript("arguments[0].click()", elements[4]).then(function() {
            //Expect modal to be displayed
            expect($('.modal').isDisplayed()).toBeTruthy();
            // Modal title should be Rename File
            expect($('.modal-title').getInnerHtml()).toBe('Rename File');
            $('.btn-danger').click();
          });
        });
      });
  });

  it('should open a file for editing', function(){
    var driver = browser.driver;
    var initialNumberOfFiles = 0;
    var newNumberOfFiles = 0;
    var fileNode = $$('.tree-branch-head').first().click(function() {
      // Make sure a file exists in the selected directory
      $$('.tree-label').first().click().then(function(){
        driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
          driver.executeScript("arguments[0].click()", elements[0]).then(function() {
            //Save the initial number of open files
            $$('tab-heading > span.ng-binding').then(function(elements){
              initialNumberOfFiles = elements.length;
              //Open a file
              $('li.tree-leaf > div').click(function(){
                //Click on edit file
                $$('.filetree-btn').get(0).click(function() {
                  $('.filetree-btn').click(function() {
                    expect($$('tab-heading > span.ng-binding').count()).toBe(initialNumberOfFiles+1);
                  });
                });
              });
            });
          });
        });
      });
    });
  });

  it('should create new file when new file is clicked', function(){
    var driver = browser.driver;
    var initialNumberOfFiles = 0;
    var finalNumberOfFiles = 0;
    $$('.tree-branch-head').first().click(function() {
      $$('.tree-label').first().click().then(function(){
        //Get initial number of files
        $$('.fa-file').then(function(files){
          initialNumberOfFiles = files.length;
          //click on new file
          driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
            driver.executeScript("arguments[0].click()", elements[0]).then(function() {
              expect($$('.fa-file').count()).toBe(initialNumberOfFiles + 1);
            });
          });
        });
      });
    });
  });

  it('should be able to duplicate a file', function(){
    // var fileNode = element.all(by.css('.tree-branch-head')).first();
    // fileNode.click();
    var driver = browser.driver;
    var initialNumberOfFiles = 0;
    var newNumberOfFiles = 0;
    //Save the initial number of open files

    var fileNode = $$('.tree-branch-head').first().click(function() {
      // Make sure a file exists in the selected directory
      $$('.tree-label').first().click().then(function(){
        driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
          driver.executeScript("arguments[0].click()", elements[0]).then(function() {
            $$('li.tree-leaf > div').then(function(elements){
              initialNumberOfFiles = elements.length;
              $('li.tree-leaf > div').click().then(function(){
                //Click on duplicate file
                $$('.filetree-btn').get(1).click(function() {
                  expect($$('li.tree-leaf > div').count()).toBe(initialNumberOfFiles + 1);
                });
              });
            });
          });
        });
      });
    });
  });

  it('should create a new folder', function(){
    var driver = browser.driver;
    var initialNumberOfFolders = 0;
    var finalNumberOfFolders = 0;
    $$('.tree-branch-head').first().click(function() {
      $$('.tree-label').first().click().then(function(){
        //Get initial number of folders
        $$('.fa-file').then(function(folders){
          initialNumberOfFolders = files.length;
          //click on new folder
          driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
            driver.executeScript("arguments[0].click()", elements[1]).then(function() {
              expect($$('.fa-folder').count()).toBe(initialNumberOfFolders + 1);
            });
          });
        });
      });
    });
  });

  it('should copy a file to clipboard and paste in a folder', function(){
    // var fileNode = element.all(by.css('.tree-branch-head')).first();
    // fileNode.click();
    var initialNumberOfFiles = 0;
    var newNumberOfFiles = 0;
    var driver = browser.driver;
    // Make sure a file exists in the selected directory
    $$('.tree-branch-head').first().click(function() {
      $$('.tree-label').first().click().then(function(){
        driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
          driver.executeScript("arguments[0].click()", elements[0]).then(function() {
            $$('.tree-label').then(function(elements){
              // Count the number of files
              initialNumberOfFiles = elements.length;
              //Click on first element
              elements[1].click().then(function(){
                // click on copy
                driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
                  driver.executeScript("arguments[0].click()", elements[2]).then(function(){
                    // Click paste
                    driver.findElements(by.css('.fc-dropdown-link')).then(function(elements){
                      driver.executeScript("arguments[0].click()", elements[3]).then(function(){
                        // count elements
                        // Expect new number of files to be one more than initial number of files
                        expect($$('.tree-label').count()).toBe(initialNumberOfFiles+1);
                      });
                    });
                  });
                });
              });
            });
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
* Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/

var http = require("http");
var log4js = require("log4js");
var Arrow = require("../interface/arrow");
var fs = require('fs');

function TestSession(config, args, sessionId) {
    this.logger = log4js.getLogger("TestSession");
    this.args = args;
    this.config = config;
    this.sessionId = sessionId;
    this.driverName = args.driver;
    this.controller = args.controller;
    this.testConfig = args.config;
    this.retryCount = 0;
    if (args.params) {
        this.testParams = args.params;
    } else {
        this.testParams = {};
    }
}

TestSession.prototype.setup = function (callback) {
    var DriverClass = null;

    if (!this.driverName) {
        if (this.controller || this.testParams.page || this.args.browser || this.sessionId) {
            this.driverName = "selenium";
        } else {
            this.driverName = "nodejs";
        }
    }

    // if descriptor has defined driver, that overrides everything else.
    if (this.testParams.driver) {
        this.driverName = this.testParams.driver;
    }

    this.logger.debug("driver: " + this.driver + ", browser: " + this.args.browser);

    if ("selenium" === this.driverName) {
        this.logger.info("Using selenium driver");
        DriverClass = require("../driver/selenium");
    } else if ("nodejs" === this.driverName) {
        this.logger.info("Using node driver");
        DriverClass = require("../driver/node");
    } else {
        this.logger.fatal("ERROR :" + this.driverName + " is not a supported test driver, Please provide \"selenium\" or \"nodejs\" as driver.");
        callback("ERROR :" + this.driverName + " is not a supported test driver, Please provide \"selenium\" or \"nodejs\" as driver.");
        return;
    }

    this.driver = new DriverClass(this.config, this.args);
    this.driver.setSessionId(this.sessionId);

    //setting default page
    if (!this.testParams.page) {
        this.testParams.page = this.config["defaultTestHost"];
    }
    callback(null);
};

TestSession.prototype.runTest = function (callback) {
    var self = this,
        arrow = Arrow.getInstance(),
        rep,
        arrReport;

    if (this.args.testName) {
        self.logger.info("Running test: " + this.args.testName);
    }

    self.setup(function (error) {
        if (error) {
            //callback(error);
            self.retryTest(callback, error);
            //return;
        } else {
            self.driver.start(function (error) {
                if (error) {
                    //callback(error);
                    self.retryTest(callback, error);
                    //return;
                } else {
                    arrow.runController(self.controller, self.testConfig, self.testParams, self.driver, function (error, data, controller) {
                        self.retryTest(callback, error);
                    });
                }
            });
        }
        return;
    });

};

TestSession.prototype.retryTest = function (callback, error) {

    var self = this;
    self.retryCount += 1;

    // checking if there is a yui test failues : self.isFail()
    // or if there is a failure at controller level : error
    if (self.isFail() || error) {
        // if retryCount is provided, and retries are left for this test, lets record the failure and retry the test
        if (global.retryCount - self.retryCount >= 0) {
            self.logger.info("Retrying Test, Attempt #" + self.retryCount);
            self.recordFailure(self.retryCount, function() {
                self.driver.stop(function() {
                    self.runTest(callback);
                });
            });
        } else {
            // no more retries, failing the test.
            // HACK : To take care of endless loop created by uncaught-exception handler at Arrow.runController method.
            if (global.retryCount - self.retryCount >= -1) {
                self.recordFailure(self.retryCount, function() {
                    self.driver.stop(callback);
                });
            } else {
                callback(error);
            }
        }
    } else {
        self.driver.stop(callback);
    }

}
TestSession.prototype.isFail = function () {
    var arrReport,
        rep,
        j,
        k,
        isFail = false,
        self = this,
        results,
        testJson;

    //checking if there was any failure
    rep = self.driver.getReports();
    if (rep.scenario) {
        arrReport = rep.scenario;
    } else {
        arrReport = rep.results;
    }

    if (arrReport) {
        if (arrReport.length === 0) {
            isFail = true;
        } else {
            for (j = 0; j < arrReport.length; j = j + 1) {
                if (rep.scenario) {
                    results = arrReport[j].results;
                    for (k = 0; k < results.length; k = k + 1) {
                        testJson =  results[k];
                        if (testJson.type === "report" && testJson.failed > 0) {
                            isFail = true;
                        }
                    }
                } else {
                    testJson = arrReport[j];
                    if (testJson.type === "report" && testJson.failed > 0) {
                        isFail = true;
                    }
                }
            }
        }
    }
    return isFail;
};

TestSession.prototype.recordFailure = function (count, callback) {

    var webdriver = this.driver.webdriver,
        testName,
        self = this;
    try {
        if (this.args.testName) {
            testName = "arrow-" + this.args.testName;
        } else {
            testName = "arrow";
        }

        if (webdriver) {
            //recording screenshot
            webdriver.takeScreenshot().then(function(img) {
                fs.writeFileSync(testName + "-" + count + ".png", new Buffer(img, 'base64'));
                //recording html source
                webdriver.getPageSource().then(function(src) {
                    fs.writeFileSync(testName + "-" + count + ".html", src);
                    callback();
                });
            });
        } else {
            callback();
        }
    } catch (e) {
        self.logger.error(e.toString());
        callback();
    }
};

module.exports = TestSession;

<commit_msg>jslint fix<commit_after>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
* Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/

var http = require("http");
var log4js = require("log4js");
var Arrow = require("../interface/arrow");
var fs = require('fs');

function TestSession(config, args, sessionId) {
    this.logger = log4js.getLogger("TestSession");
    this.args = args;
    this.config = config;
    this.sessionId = sessionId;
    this.driverName = args.driver;
    this.controller = args.controller;
    this.testConfig = args.config;
    this.retryCount = 0;
    if (args.params) {
        this.testParams = args.params;
    } else {
        this.testParams = {};
    }
}

TestSession.prototype.setup = function (callback) {
    var DriverClass = null;

    if (!this.driverName) {
        if (this.controller || this.testParams.page || this.args.browser || this.sessionId) {
            this.driverName = "selenium";
        } else {
            this.driverName = "nodejs";
        }
    }

    // if descriptor has defined driver, that overrides everything else.
    if (this.testParams.driver) {
        this.driverName = this.testParams.driver;
    }

    this.logger.debug("driver: " + this.driver + ", browser: " + this.args.browser);

    if ("selenium" === this.driverName) {
        this.logger.info("Using selenium driver");
        DriverClass = require("../driver/selenium");
    } else if ("nodejs" === this.driverName) {
        this.logger.info("Using node driver");
        DriverClass = require("../driver/node");
    } else {
        this.logger.fatal("ERROR :" + this.driverName + " is not a supported test driver, Please provide \"selenium\" or \"nodejs\" as driver.");
        callback("ERROR :" + this.driverName + " is not a supported test driver, Please provide \"selenium\" or \"nodejs\" as driver.");
        return;
    }

    this.driver = new DriverClass(this.config, this.args);
    this.driver.setSessionId(this.sessionId);

    //setting default page
    if (!this.testParams.page) {
        this.testParams.page = this.config["defaultTestHost"];
    }
    callback(null);
};

TestSession.prototype.runTest = function (callback) {
    var self = this,
        arrow = Arrow.getInstance(),
        rep,
        arrReport;

    if (this.args.testName) {
        self.logger.info("Running test: " + this.args.testName);
    }

    self.setup(function (error) {
        if (error) {
            //callback(error);
            self.retryTest(callback, error);
            //return;
        } else {
            self.driver.start(function (error) {
                if (error) {
                    //callback(error);
                    self.retryTest(callback, error);
                    //return;
                } else {
                    arrow.runController(self.controller, self.testConfig, self.testParams, self.driver, function (error, data, controller) {
                        self.retryTest(callback, error);
                    });
                }
            });
        }
        return;
    });

};

TestSession.prototype.retryTest = function (callback, error) {

    var self = this;
    self.retryCount += 1;

    // checking if there is a yui test failues : self.isFail()
    // or if there is a failure at controller level : error
    if (self.isFail() || error) {
        // if retryCount is provided, and retries are left for this test, lets record the failure and retry the test
        if (global.retryCount - self.retryCount >= 0) {
            self.logger.info("Retrying Test, Attempt #" + self.retryCount);
            self.recordFailure(self.retryCount, function() {
                self.driver.stop(function() {
                    self.runTest(callback);
                });
            });
        } else {
            // no more retries, failing the test.
            // HACK : To take care of endless loop created by uncaught-exception handler at Arrow.runController method.
            if (global.retryCount - self.retryCount >= -1) {
                self.recordFailure(self.retryCount, function() {
                    self.driver.stop(callback);
                });
            } else {
                callback(error);
            }
        }
    } else {
        self.driver.stop(callback);
    }
};

TestSession.prototype.isFail = function () {
    var arrReport,
        rep,
        j,
        k,
        isFail = false,
        self = this,
        results,
        testJson;

    //checking if there was any failure
    rep = self.driver.getReports();
    if (rep.scenario) {
        arrReport = rep.scenario;
    } else {
        arrReport = rep.results;
    }

    if (arrReport) {
        if (arrReport.length === 0) {
            isFail = true;
        } else {
            for (j = 0; j < arrReport.length; j = j + 1) {
                if (rep.scenario) {
                    results = arrReport[j].results;
                    for (k = 0; k < results.length; k = k + 1) {
                        testJson =  results[k];
                        if (testJson.type === "report" && testJson.failed > 0) {
                            isFail = true;
                        }
                    }
                } else {
                    testJson = arrReport[j];
                    if (testJson.type === "report" && testJson.failed > 0) {
                        isFail = true;
                    }
                }
            }
        }
    }
    return isFail;
};

TestSession.prototype.recordFailure = function (count, callback) {

    var webdriver = this.driver.webdriver,
        testName,
        self = this;
    try {
        if (this.args.testName) {
            testName = "arrow-" + this.args.testName;
        } else {
            testName = "arrow";
        }

        if (webdriver) {
            //recording screenshot
            webdriver.takeScreenshot().then(function(img) {
                fs.writeFileSync(testName + "-" + count + ".png", new Buffer(img, 'base64'));
                //recording html source
                webdriver.getPageSource().then(function(src) {
                    fs.writeFileSync(testName + "-" + count + ".html", src);
                    callback();
                });
            });
        } else {
            callback();
        }
    } catch (e) {
        self.logger.error(e.toString());
        callback();
    }
};

module.exports = TestSession;

<|endoftext|>


<commit_before>/**
 * @class WebRtcContent
 *
 * @param {String} ws_uri: URI of the server WebSocket endpoint. Alternatively,
 *   it can be used a WebSocket or DataChannel object.
 */
function WebRtcContent(url)
{
  var self = this;

  $.jsonRPC.setup({endPoint: url});

  var sessionId = null;
  var pollingTimeout = null;

  var pc = new RTCPeerConnection(
  {
    iceServers: [{url: 'stun:'+'stun.l.google.com:19302'}]
  });

  pc.addEventListener('signalingState', function(event)
  {
    if(pc.signalingState == "close"
    && self.onclose)
       self.onclose(new Event('close'));
  });

  function onerror(error)
  {
    if(self.onerror)
       self.onerror(error);
  }

  function onerror_jsonrpc(event)
  {
    onerror(new Error(event.error));
  }

  // Start
  var mediaConstraints =
  {
    'mandatory':
    {
      'OfferToReceiveAudio': true,
      'OfferToReceiveVideo': true
    }
  };

  pc.createOffer(function(offer)
  {
    // Set the peer local description
    pc.setLocalDescription(offer,
    function()
    {
      console.info("LocalDescription correctly set");
    },
    onerror);
  },
  onerror,
  mediaConstraints);

  pc.onicecandidate = function(event)
  {
    if(event.candidate)
      return;

    var params =
    {
      sdp: pc.localDescription.sdp
    };

    function success(response)
    {
      var result = response.result;

      sessionId = result.sessionId;

      pc.setRemoteDescription(new RTCSessionDescription(
      {
        type: 'answer',
        sdp: result.sdp
      }),
      function()
      {
        // Init MediaEvents polling
        pollMediaEvents();

        // Notify to the user about the new stream
        if(self.onsuccess)
        {
          var streams = pc.getRemoteStreams();

          if(streams)
          {
            var event = new Event('open');
                event.stream = stream[0];

            self.onsuccess(event);
          }
          else
            onerror(new Error("No streams are available"));
        }
      },
      onerror);
    }

    $.jsonRPC.request('start',
    {
      params:  params,
      success: success,
      error:   onerror_jsonrpc
    });
  };

  // Terminate
  this.terminate = function()
  {
    var params =
    {
      sessionId: sessionId
    };

    $.jsonRPC.request('terminate',
    {
      params: params,
      success: function(result)
      {
        // Stop polling
        clearTimeout(pollingTimeout);

        console.info("Connection terminated");
      },
      error: onerror_jsonrpc
    });
  };

  // Pool

  /**
   * Pool for events dispatched on the server pipeline
   */
  function pollMediaEvents()
  {
    var timeout = 5*1000;  // Request events each 5 seconds

    var params =
    {
      sessionId: sessionId
    };

    $.jsonRPC.request('poll',
    {
      params: params,
      success: function(response)
      {
        var result = response.result;

        if(result.events)
          for(var i=0, data; data=result.events[i]; i++)
            if(self.onMediaEvent)
            {
              var event = new Event('MediaEvent');
                  event.data = data;

              self.onMediaEvent(event);
            }

        pollingTimeout = setTimeout(pollMediaEvents, timeout);
      },
      error: function(event)
      {
        onerror_jsonrpc(event);

        pollingTimeout = setTimeout(pollMediaEvents, timeout);
      }
    });
  }

  // Mediacontrol

  /**
   * Start a new media communication
   *
   * @param {String} mediaId: identifier of the media communication
   * @param {Object} options: configuration options
   *   {Enum(null, 'send', 'recv', 'sendrecv')} audio: audio stream mode
   *   {Enum(null, 'send', 'recv', 'sendrecv')} video: video stream mode
   * @param {Function(Error, Media)} callback: continuation function
   */
/*  this.startMedia = function(mediaId, options, callback)
  {
    // Adjust arguments if options is not defined
    if(typeof options == 'function')
    {
      callback = options;
      options = undefined;
    }

    options = options || {};

    // We can't disable both audio and video on a stream, raise error
    if(options.audio == null
    && options.video == null)
    {
      callback(new Error("No audio or video medias are defined"));
      return
    }
*/
    /**
     * Decode the mode of the streams
     */
/*    function decodeMode(type, mode)
    {
      var result = {};

      switch(mode)
      {
        case undefined:  // If not defined, set send & receive by default
        case 'sendrecv':
          result.local = true;
          result.remote = true;
        break;

        case 'send':
          result.local = true;
          result.remote = false;
        break;

        case 'recv':
          result.local = false;
          result.remote = true;
        break;

        default:
          callback(new Error("Invalid "+type+" media mode"));
          return
      }

      return result;
    }

    // Audio media
    var audio = decodeMode("audio", options.audio);
    if(!audio) return;

    // Video media
    var video = decodeMode("video", options.video);
    if(!video) return;
*/
    /**
     * Send an offer with the current and new streams and constraints
     */
/*
    // Mode set to send local audio and/or video stream
    if(audio.local || video.local)
      navigator.getUserMedia({'audio': audio.local, 'video': video.local},
      function(stream)
      {
        pc.addStream(stream);
        sendOffer();
      },
      onerror)

    // Mode set to only receive a stream, not send it
    else
      sendOffer();
  }*/
}
<commit_msg>Using onopen event instead of onsuccess as defined previously<commit_after>/**
 * @class WebRtcContent
 *
 * @param {String} ws_uri: URI of the server WebSocket endpoint. Alternatively,
 *   it can be used a WebSocket or DataChannel object.
 */
function WebRtcContent(url)
{
  var self = this;

  $.jsonRPC.setup({endPoint: url});

  var sessionId = null;
  var pollingTimeout = null;

  var pc = new RTCPeerConnection(
  {
    iceServers: [{url: 'stun:'+'stun.l.google.com:19302'}]
  });

  pc.addEventListener('signalingState', function(event)
  {
    if(pc.signalingState == "close"
    && self.onclose)
       self.onclose(new Event('close'));
  });

  function onerror(error)
  {
    if(self.onerror)
       self.onerror(error);
  }

  function onerror_jsonrpc(event)
  {
    onerror(new Error(event.error));
  }

  // Start
  var mediaConstraints =
  {
    'mandatory':
    {
      'OfferToReceiveAudio': true,
      'OfferToReceiveVideo': true
    }
  };

  pc.createOffer(function(offer)
  {
    // Set the peer local description
    pc.setLocalDescription(offer,
    function()
    {
      console.info("LocalDescription correctly set");
    },
    onerror);
  },
  onerror,
  mediaConstraints);

  pc.onicecandidate = function(event)
  {
    if(event.candidate)
      return;

    var params =
    {
      sdp: pc.localDescription.sdp
    };

    function success(response)
    {
      var result = response.result;

      sessionId = result.sessionId;

      pc.setRemoteDescription(new RTCSessionDescription(
      {
        type: 'answer',
        sdp: result.sdp
      }),
      function()
      {
        // Init MediaEvents polling
        pollMediaEvents();

        // Notify to the user about the new stream
        if(self.onopen)
        {
          var streams = pc.getRemoteStreams();

          if(streams)
          {
            var event = new Event('open');
                event.stream = streams[0];

            self.onopen(event);
          }
          else
            onerror(new Error("No streams are available"));
        }
      },
      onerror);
    }

    $.jsonRPC.request('start',
    {
      params:  params,
      success: success,
      error:   onerror_jsonrpc
    });
  };

  // Terminate
  this.terminate = function()
  {
    var params =
    {
      sessionId: sessionId
    };

    $.jsonRPC.request('terminate',
    {
      params: params,
      success: function(result)
      {
        // Stop polling
        clearTimeout(pollingTimeout);

        console.info("Connection terminated");
      },
      error: onerror_jsonrpc
    });
  };

  // Pool

  /**
   * Pool for events dispatched on the server pipeline
   */
  function pollMediaEvents()
  {
    var timeout = 5*1000;  // Request events each 5 seconds

    var params =
    {
      sessionId: sessionId
    };

    $.jsonRPC.request('poll',
    {
      params: params,
      success: function(response)
      {
        var result = response.result;

        if(result.events)
          for(var i=0, data; data=result.events[i]; i++)
            if(self.onMediaEvent)
            {
              var event = new Event('MediaEvent');
                  event.data = data;

              self.onMediaEvent(event);
            }

        pollingTimeout = setTimeout(pollMediaEvents, timeout);
      },
      error: function(event)
      {
        onerror_jsonrpc(event);

        pollingTimeout = setTimeout(pollMediaEvents, timeout);
      }
    });
  }

  // Mediacontrol

  /**
   * Start a new media communication
   *
   * @param {String} mediaId: identifier of the media communication
   * @param {Object} options: configuration options
   *   {Enum(null, 'send', 'recv', 'sendrecv')} audio: audio stream mode
   *   {Enum(null, 'send', 'recv', 'sendrecv')} video: video stream mode
   * @param {Function(Error, Media)} callback: continuation function
   */
/*  this.startMedia = function(mediaId, options, callback)
  {
    // Adjust arguments if options is not defined
    if(typeof options == 'function')
    {
      callback = options;
      options = undefined;
    }

    options = options || {};

    // We can't disable both audio and video on a stream, raise error
    if(options.audio == null
    && options.video == null)
    {
      callback(new Error("No audio or video medias are defined"));
      return
    }
*/
    /**
     * Decode the mode of the streams
     */
/*    function decodeMode(type, mode)
    {
      var result = {};

      switch(mode)
      {
        case undefined:  // If not defined, set send & receive by default
        case 'sendrecv':
          result.local = true;
          result.remote = true;
        break;

        case 'send':
          result.local = true;
          result.remote = false;
        break;

        case 'recv':
          result.local = false;
          result.remote = true;
        break;

        default:
          callback(new Error("Invalid "+type+" media mode"));
          return
      }

      return result;
    }

    // Audio media
    var audio = decodeMode("audio", options.audio);
    if(!audio) return;

    // Video media
    var video = decodeMode("video", options.video);
    if(!video) return;
*/
    /**
     * Send an offer with the current and new streams and constraints
     */
/*
    // Mode set to send local audio and/or video stream
    if(audio.local || video.local)
      navigator.getUserMedia({'audio': audio.local, 'video': video.local},
      function(stream)
      {
        pc.addStream(stream);
        sendOffer();
      },
      onerror)

    // Mode set to only receive a stream, not send it
    else
      sendOffer();
  }*/
}
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import { translate } from 'react-i18next'
import { Nav, NavItem } from 'react-bootstrap'
import Icon from 'components/Common/Icon'

class SearchToolbar extends React.Component {
  constructor() {
    super()

    this.searchTypes = ['', 'portal', 'public', 'user']

    this.getActiveType = this.getActiveType.bind(this)
  }

  getActiveType() {
    const defaultType = this.searchTypes[0]
    const { type } = this.props
    return this.searchTypes.includes(type) ? type : defaultType
  }

  render() {
    const { t } = this.props
    return (

{this.props.keyword}

          {this.props.searching && <Icon name="spinner" spin />  || t('search.toolbar.results', { value: this.props.total })}

            <NavItem eventKey={this.searchTypes[0]} href="#">
              <Icon name="th" />
              {t('page_types.all')}
            </NavItem>
            <NavItem eventKey={this.searchTypes[1]} href="#">
              <Icon name="circle" regular />
              {t('page_types.portal')}
            </NavItem>
            <NavItem eventKey={this.searchTypes[2]} href="#">
              <Icon name="file" regular />
              {t('page_types.public')}
            </NavItem>
            <NavItem eventKey={this.searchTypes[3]} href="#">
              <Icon name="user" regular />
              {t('page_types.user')}
            </NavItem>

    )
  }
}

SearchToolbar.propTypes = {
  keyword: PropTypes.string,
  type: PropTypes.string,
  total: PropTypes.number,
  changeType: PropTypes.func,
  searching: PropTypes.boolean,
  t: PropTypes.func.isRequired,
}
SearchToolbar.defaultProps = {
  keyword: '',
  type: '',
  searching: false,
  total: 0,
}

export default translate()(SearchToolbar)
<commit_msg>Show spinner<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import { translate } from 'react-i18next'
import { Nav, NavItem } from 'react-bootstrap'
import Icon from 'components/Common/Icon'

class SearchToolbar extends React.Component {
  constructor() {
    super()

    this.searchTypes = ['', 'portal', 'public', 'user']

    this.getActiveType = this.getActiveType.bind(this)
  }

  getActiveType() {
    const defaultType = this.searchTypes[0]
    const { type } = this.props
    return this.searchTypes.includes(type) ? type : defaultType
  }

  render() {
    const { t } = this.props
    return (

{this.props.keyword}

            {(this.props.searching && <Icon name="spinner" spin />) ||
              t('search.toolbar.results', { value: this.props.total })}

            <NavItem eventKey={this.searchTypes[0]} href="#">
              <Icon name="th" />
              {t('page_types.all')}
            </NavItem>
            <NavItem eventKey={this.searchTypes[1]} href="#">
              <Icon name="circle" regular />
              {t('page_types.portal')}
            </NavItem>
            <NavItem eventKey={this.searchTypes[2]} href="#">
              <Icon name="file" regular />
              {t('page_types.public')}
            </NavItem>
            <NavItem eventKey={this.searchTypes[3]} href="#">
              <Icon name="user" regular />
              {t('page_types.user')}
            </NavItem>

    )
  }
}

SearchToolbar.propTypes = {
  keyword: PropTypes.string,
  type: PropTypes.string,
  total: PropTypes.number,
  changeType: PropTypes.func,
  searching: PropTypes.boolean,
  t: PropTypes.func.isRequired,
}
SearchToolbar.defaultProps = {
  keyword: '',
  type: '',
  searching: false,
  total: 0,
}

export default translate()(SearchToolbar)
<|endoftext|>


<commit_before>/**
 * Debuggify Collector
 * @module debuggify/collector
 * @author Ankur Agarwal
 */

(function (debuggify, undefined) {

  var collector = debuggify.Collector = debuggify.Collector || (function (w, d, extend, globals, transports) {

    /**
     * Collection of commands which are available in collector
     * @type {Object}
     */
    var funcs = {

      /**
       * Add a transport to a logger object
       * @param {string} transportName Name of the transport
       * @param {Object} options       settinngs required for the transport
       */
      _addTransport: function (transportName, options) {

        if(globals.transports[transportName] && transports[transportName]) {

          this.transports.push(new transports[transportName](options));

        } else {
          throw 'transport ' + transportName + ' is not defined';
        }

      }
    };

    var toString = Object.prototype.toString;

    /**
     * Check whether its array or not
     * @param  {Object}  obj variable which need to be checked
     * @return {Boolean}     true if Array else false
     */
    function isArray (obj) {
        return toString.call(obj) === "[object Array]";
    }

    /**
     * Delete the array
     * @param  {Array} arr Array to be deleted
     * @return {undefined}
     */
    function deleteArray(arr) {
      arr.splice(0, arr.length);
    }

    /**
     * Initializing the collector
     * @return {undefined}
     */
    function init() {
      processProjects();
    }

    /**
     * process all the projects
     * @return {undefined}
     */
    function processProjects () {
      var project;
      var projectList = globals.projects;

      for (project in projectList) {
        if(projectList.hasOwnProperty(project)) {
          processQueue(projectList[project]);
        }
      }
    }

     /**
      * Process the queue for any project
      * @param  {Object} project project need to be processed
      * @return {undefined}
      */
    function processQueue (project) {

      // Initialize the queue if not already

      var queue = project.collectorQueue = project.collectorQueue || [];

      if(typeof queue.isCollector !== 'undefined') {
        return false;
      }

      if(!isArray(queue)) {
        throw 'Queue must be array';
      }

      var l = queue.length;

      // Process the data inside queue
      for (var i = 0; i < l; i++) {
        processCmd(queue[i], project);
      }

      // Delete elements inside array
      deleteArray(queue);

      // Overload the queue array to collector object
      project.collectorQueue = new Collector(project);
    }

    /**
     * Process cmd on any specific project environment
     * @param  {Array} cmd   Command with the arrguments
     * @param  {Object} self Project on which command is to executed
     * @return {undefined}
     */
    function processCmd(cmd, self) {

      // Checking for Array
      if (isArray(cmd)) {

        // Get the function name which is called
        var func = cmd[0];
        // Get the function argunments
        var args = Array.prototype.slice.call(cmd, 1);

        // if function start with _ then execute it else send to collector
        if(func[0] === '_' && typeof funcs[func] === "function") {

          // Execute the functions
          funcs[func].apply(self, args[0]);

          //sendDataToServer(args);
        } else {

          // Send to all the transports for project
          var l = self.transports.length;
          var transport;

          for(transport in self.transports){
            if(self.transports.hasOwnProperty(transport)) {

              try {
                self.transports[transport].send.apply(self.transports[transport], args);
              } catch (e){
                console.warn(self.transports[transport].name + ': Sending via transport failed: ' + e);
              }

            }
          }
        }

        // delete the array
       // deleteArray(cmd);

      } else {

        console.log(cmd);
        // Handle Invalid Data
        throw "Expecting array, got " + typeof cmd;

      }
    }

    /**
     * Collector Class
     * @constructor
     * @param {Object} project project which need to connected with collector
     */
    function Collector(project) {

      this.isCollector = true;
      this.project = project;

    }

    /**
     * Extending the prototypes of Collector Class
     * @type {Object}
     */
    Collector.prototype = {

      push: function (cmd) {
        return processCmd(cmd, this.project);
      }
    };

    return {
      init: init,
      process: processProjects
    };

  }(debuggify.win, debuggify.doc, debuggify.extend, debuggify.globals, debuggify.Transports));

}(debuggify));<commit_msg>Added level support for all transports<commit_after>/**
 * Debuggify Collector
 * @module debuggify/collector
 * @author Ankur Agarwal
 */

(function (debuggify, undefined) {

  var collector = debuggify.Collector = debuggify.Collector || (function (w, d, extend, globals, transports, envs) {

    /**
     * Collection of commands which are available in collector
     * @type {Object}
     */
    var funcs = {

      /**
       * Add a transport to a logger object
       * @param {string} transportName Name of the transport
       * @param {Object} options       settinngs required for the transport
       */
      _addTransport: function (transportName, options) {

        if(globals.transports[transportName] && transports[transportName]) {

          this.transports.push(new transports[transportName](options));

        } else {
          throw 'transport ' + transportName + ' is not defined';
        }

      }
    };

    var toString = Object.prototype.toString;

    /**
     * Check whether its array or not
     * @param  {Object}  obj variable which need to be checked
     * @return {Boolean}     true if Array else false
     */
    function isArray (obj) {
        return toString.call(obj) === "[object Array]";
    }

    /**
     * Delete the array
     * @param  {Array} arr Array to be deleted
     * @return {undefined}
     */
    function deleteArray(arr) {
      arr.splice(0, arr.length);
    }

    /**
     * Initializing the collector
     * @return {undefined}
     */
    function init() {
      processProjects();
    }

    /**
     * process all the projects
     * @return {undefined}
     */
    function processProjects () {
      var project;
      var projectList = globals.projects;

      for (project in projectList) {
        if(projectList.hasOwnProperty(project)) {
          processQueue(projectList[project]);
        }
      }
    }

     /**
      * Process the queue for any project
      * @param  {Object} project project need to be processed
      * @return {undefined}
      */
    function processQueue (project) {

      // Initialize the queue if not already

      var queue = project.collectorQueue = project.collectorQueue || [];

      if(typeof queue.isCollector !== 'undefined') {
        return false;
      }

      if(!isArray(queue)) {
        throw 'Queue must be array';
      }

      var l = queue.length;

      // Process the data inside queue
      for (var i = 0; i < l; i++) {
        processCmd(queue[i], project);
      }

      // Delete elements inside array
      deleteArray(queue);

      // Overload the queue array to collector object
      project.collectorQueue = new Collector(project);
    }

    /**
     * Process cmd on any specific project environment
     * @param  {Array} cmd   Command with the arrguments
     * @param  {Object} self Project on which command is to executed
     * @return {undefined}
     */
    function processCmd(cmd, self) {

      // Checking for Array
      if (isArray(cmd)) {

        // Get the function name which is called
        var func = cmd[0];
        // Get the function argunments
        var args = Array.prototype.slice.call(cmd, 1);

        // if function start with _ then execute it else send to collector
        if(func[0] === '_' && typeof funcs[func] === "function") {

          // Execute the functions
          funcs[func].apply(self, args[0]);

          //sendDataToServer(args);
        } else {

          // Send to all the transports for project
          var l = self.transports.length;
          var transport;

          for(transport in self.transports){
            if(self.transports.hasOwnProperty(transport)) {
                var t = self.transports[transport];
                try {
                  var level = self.options.messagesTypes[args[1].type];
                  if(typeof level !== "undefined" && t.options.level <= level) {
                    t.send.apply(self.transports[transport], args);
                  }
                } catch (e){
                  console.warn(t.name + ': Sending via transport failed: ' + e);
                }
            }
          }
        }

        // delete the array
       // deleteArray(cmd);

      } else {

        console.log(cmd);
        // Handle Invalid Data
        throw "Expecting array, got " + typeof cmd;

      }
    }

    /**
     * Collector Class
     * @constructor
     * @param {Object} project project which need to connected with collector
     */
    function Collector(project) {

      this.isCollector = true;
      this.project = project;

    }

    /**
     * Extending the prototypes of Collector Class
     * @type {Object}
     */
    Collector.prototype = {

      push: function (cmd) {
        return processCmd(cmd, this.project);
      }
    };

    return {
      init: init,
      process: processProjects
    };

  }(debuggify.win, debuggify.doc, debuggify.extend, debuggify.globals, debuggify.Transports, debuggify.envs));

}(debuggify));<|endoftext|>


<commit_before>var argscheck = require('cordova/argscheck'),
    exec = require('cordova/exec');

var admobExport = {};

/**
 * This enum represents appfeel-cordova-admob plugin events
 */
admobExport.events = {
  onAdLoaded : "appfeel.cordova.admob.onAdLoaded",
  onAdFailedToLoad : "appfeel.cordova.admob.onAdFailedToLoad",
  onAdOpened : "appfeel.cordova.admob.onAdOpened",
  onAdLeftApplication : "appfeel.cordova.admob.onAdLeftApplication",
  onAdClosed : "appfeel.cordova.admob.onAdClosed",
  onInAppPurchaseRequested : "appfeel.cordova.admob.onInAppPurchaseRequested",
};

/**
 * This enum represents AdMob's supported ad sizes.  Use one of these
 * constants as the adSize when calling createBannerView.
 * @const
 */
admobExport.AD_SIZE = {
  BANNER: 'BANNER',
  IAB_MRECT: 'IAB_MRECT',
  IAB_BANNER: 'IAB_BANNER',
  IAB_LEADERBOARD: 'IAB_LEADERBOARD',
  SMART_BANNER: 'SMART_BANNER'
};

admobExport.options = {
  publisherId : "ca-app-pub-8440343014846849/6338199818",
  interstitialId : "ca-app-pub-8440343014846849/9791193812",
  adSize : admobExport.AD_SIZE.SMART_BANNER,
  bannerAtTop : false,
  overlap : false,
  offsetStatusBar : false,
  isTesting : false,
  adExtras : {},
  autoShow : true,
};

/**
 * Initialize appfeel-cordova-admob plugin with options:
 * @param {!Object}    options         AdMob options (use admob.options as template)
 * @param {function()} successCallback Callback on success
 * @param {function()} failureCallback Callback on fail
 */
admobExport.setOptions = function (options, successCallback, failureCallback) {
  if (typeof options === 'function') {
    failureCallback = successCallback;
    successCallback = options;
    options = undefined;
  }

  options = options || admobExport.DEFAULT_OPTIONS;

  if (typeof options === 'object' && typeof options.publisherId === 'string' && options.publisherId.length > 0) {
    cordova.exec(successCallback, failureCallback, 'AdMobAds', 'setOptions', [options]);

  } else {
    if (typeof failureCallback === 'function') {
      failureCallback('options.publisherId should be specified.')
    }
  }
};

/**
 * Creates a new AdMob banner view.
 *
 * @param {!Object}    options         The options used to create a banner. (use admob.options as template)
 * @param {function()} successCallback The function to call if the banner was created successfully.
 * @param {function()} failureCallback The function to call if create banner  was unsuccessful.
 */
admobExport.createBannerView = function (options, successCallback, failureCallback) {
  options = options || {};
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'createBannerView', [ options ]);
};

/*
 * Show or hide Ad.
 *
 * @param {boolean} show true to show, false to hide.
 * @param {function()} successCallback The function to call if the ad was shown successfully.
 * @param {function()} failureCallback The function to call if the ad failed to be shown.
 */
admobExport.showBannerAd = function (show, successCallback, failureCallback) {
  if (show === undefined) {
    show = true;
  }
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'showBannerAd', [ show ]);
};

/**
 * Hides and destroys the banner view. CreateBanner should be called if new ads were to be shown.
 * @param {function()} successCallback The function to call if the view was destroyed successfully.
 * @param {function()} failureCallback The function to call if failed to destroy view.
 */
admobExport.destroyBannerView = function (successCallback, failureCallback) {
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'destroyBannerView', []);
};

/**
 * Request an AdMob interstitial ad.
 *
 * @param {!Object}    options         The options used to request an ad. (use admob.options as template)
 * @param {function()} successCallback The function to call if an ad was requested successfully.
 * @param {function()} failureCallback The function to call if an ad failed to be requested.
 */
admobExport.requestInterstitialAd = function (options, successCallback, failureCallback) {
  options = options || {};
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'requestInterstitialAd', [ options ]);
};

/**
 * Shows an interstitial ad. This function should be called when onAdLoaded occurred.
 *
 * @param {function()} successCallback The function to call if the ad was shown successfully.
 * @param {function()} failureCallback The function to call if the ad failed to be shown.
 */
admobExport.showInterstitialAd = function (successCallback, failureCallback) {
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'showInterstitialAd', []);
};

/**
 * Records a resolution after an inAppPurchase.
 *
 * @param {Integer}    purchaseId      The id of the purchase.
 * @param {Integer}    resolution      The resolution code.
 * @param {function()} successCallback The function to call if the ad was shown successfully.
 * @param {function()} successCallback The function to call if the ad was shown successfully.
 * @param {function()} failureCallback The function to call if the ad failed to be shown.
 */
admobExport.recordResolution = function (purchaseId, resolution, successCallback, failureCallback) {
  if (purchaseId === undefined || resolution === undefined) {
    if (typeof failureCallback === 'function') {
      failureCallback('purchaseId and resolution should be specified.')
    }
  }
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'recordResolution', [ purchaseId, resolution ]);
};

/**
 * Records a resolution after an inAppPurchase.
 *
 * @param {Integer}    purchaseId           The id of the purchase.
 * @param {Integer}    billingResponseCode  The resolution code.
 * @param {function()} successCallback      The function to call if the ad was shown successfully.
 * @param {function()} successCallback      The function to call if the ad was shown successfully.
 * @param {function()} failureCallback      The function to call if the ad failed to be shown.
 */
admobExport.recordPlayBillingResolution = function (purchaseId, billingResponseCode, successCallback, failureCallback) {
  if (purchaseId === undefined || billingResponseCode === undefined) {
    if (typeof failureCallback === 'function') {
      failureCallback('purchaseId and billingResponseCode should be specified.')
    }
  }
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'recordResolution', [ purchaseId, billingResponseCode ]);
};

module.exports = admobExport;
<commit_msg>Change module variable in order to be detected as 'admob' in Brackets<commit_after>var argscheck = require('cordova/argscheck'),
    exec = require('cordova/exec');

var admob = module.exports;

/**
 * This enum represents appfeel-cordova-admob plugin events
 */
admob.events = {
  onAdLoaded : "appfeel.cordova.admob.onAdLoaded",
  onAdFailedToLoad : "appfeel.cordova.admob.onAdFailedToLoad",
  onAdOpened : "appfeel.cordova.admob.onAdOpened",
  onAdLeftApplication : "appfeel.cordova.admob.onAdLeftApplication",
  onAdClosed : "appfeel.cordova.admob.onAdClosed",
  onInAppPurchaseRequested : "appfeel.cordova.admob.onInAppPurchaseRequested",
};

/**
 * This enum represents AdMob's supported ad sizes.  Use one of these
 * constants as the adSize when calling createBannerView.
 * @const
 */
admob.AD_SIZE = {
  BANNER: 'BANNER',
  IAB_MRECT: 'IAB_MRECT',
  IAB_BANNER: 'IAB_BANNER',
  IAB_LEADERBOARD: 'IAB_LEADERBOARD',
  SMART_BANNER: 'SMART_BANNER'
};

admob.options = {
  publisherId : "ca-app-pub-8440343014846849/6338199818",
  interstitialId : "ca-app-pub-8440343014846849/9791193812",
  adSize : admob.AD_SIZE.SMART_BANNER,
  bannerAtTop : false,
  overlap : false,
  offsetStatusBar : false,
  isTesting : false,
  adExtras : {},
  autoShow : true,
};

/**
 * Initialize appfeel-cordova-admob plugin with options:
 * @param {!Object}    options         AdMob options (use admob.options as template)
 * @param {function()} successCallback Callback on success
 * @param {function()} failureCallback Callback on fail
 */
admob.setOptions = function (options, successCallback, failureCallback) {
  if (typeof options === 'function') {
    failureCallback = successCallback;
    successCallback = options;
    options = undefined;
  }

  options = options || admob.DEFAULT_OPTIONS;

  if (typeof options === 'object' && typeof options.publisherId === 'string' && options.publisherId.length > 0) {
    cordova.exec(successCallback, failureCallback, 'AdMobAds', 'setOptions', [options]);

  } else {
    if (typeof failureCallback === 'function') {
      failureCallback('options.publisherId should be specified.')
    }
  }
};

/**
 * Creates a new AdMob banner view.
 *
 * @param {!Object}    options         The options used to create a banner. (use admob.options as template)
 * @param {function()} successCallback The function to call if the banner was created successfully.
 * @param {function()} failureCallback The function to call if create banner  was unsuccessful.
 */
admob.createBannerView = function (options, successCallback, failureCallback) {
  options = options || {};
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'createBannerView', [ options ]);
};

/*
 * Show or hide Ad.
 *
 * @param {boolean} show true to show, false to hide.
 * @param {function()} successCallback The function to call if the ad was shown successfully.
 * @param {function()} failureCallback The function to call if the ad failed to be shown.
 */
admob.showBannerAd = function (show, successCallback, failureCallback) {
  if (show === undefined) {
    show = true;
  }
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'showBannerAd', [ show ]);
};

/**
 * Hides and destroys the banner view. CreateBanner should be called if new ads were to be shown.
 * @param {function()} successCallback The function to call if the view was destroyed successfully.
 * @param {function()} failureCallback The function to call if failed to destroy view.
 */
admob.destroyBannerView = function (successCallback, failureCallback) {
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'destroyBannerView', []);
};

/**
 * Request an AdMob interstitial ad.
 *
 * @param {!Object}    options         The options used to request an ad. (use admob.options as template)
 * @param {function()} successCallback The function to call if an ad was requested successfully.
 * @param {function()} failureCallback The function to call if an ad failed to be requested.
 */
admob.requestInterstitialAd = function (options, successCallback, failureCallback) {
  options = options || {};
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'requestInterstitialAd', [ options ]);
};

/**
 * Shows an interstitial ad. This function should be called when onAdLoaded occurred.
 *
 * @param {function()} successCallback The function to call if the ad was shown successfully.
 * @param {function()} failureCallback The function to call if the ad failed to be shown.
 */
admob.showInterstitialAd = function (successCallback, failureCallback) {
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'showInterstitialAd', []);
};

/**
 * Records a resolution after an inAppPurchase.
 *
 * @param {Integer}    purchaseId      The id of the purchase.
 * @param {Integer}    resolution      The resolution code.
 * @param {function()} successCallback The function to call if the ad was shown successfully.
 * @param {function()} successCallback The function to call if the ad was shown successfully.
 * @param {function()} failureCallback The function to call if the ad failed to be shown.
 */
admob.recordResolution = function (purchaseId, resolution, successCallback, failureCallback) {
  if (purchaseId === undefined || resolution === undefined) {
    if (typeof failureCallback === 'function') {
      failureCallback('purchaseId and resolution should be specified.')
    }
  }
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'recordResolution', [ purchaseId, resolution ]);
};

/**
 * Records a resolution after an inAppPurchase.
 *
 * @param {Integer}    purchaseId           The id of the purchase.
 * @param {Integer}    billingResponseCode  The resolution code.
 * @param {function()} successCallback      The function to call if the ad was shown successfully.
 * @param {function()} successCallback      The function to call if the ad was shown successfully.
 * @param {function()} failureCallback      The function to call if the ad failed to be shown.
 */
admob.recordPlayBillingResolution = function (purchaseId, billingResponseCode, successCallback, failureCallback) {
  if (purchaseId === undefined || billingResponseCode === undefined) {
    if (typeof failureCallback === 'function') {
      failureCallback('purchaseId and billingResponseCode should be specified.')
    }
  }
  cordova.exec(successCallback, failureCallback, 'AdMobAds', 'recordResolution', [ purchaseId, billingResponseCode ]);
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 peeracle contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/* eslint-disable */
'use strict';

if (typeof Peeracle === 'undefined') {
  var Peeracle = require('..');
}

describe('MemoryDataStream', function () {
  var buffer = new Uint8Array(32);
  var floatBuffer = new Uint8Array(32);

  beforeEach(function () {
    var dataView = new DataView(floatBuffer.buffer);

    for (var i = 0; i < 32; ++i) {
      buffer[i] = Math.floor(Math.random() * 256);
    }

    for (var i = 0; i < 32; i += 4) {
      dataView.setFloat32(i, (new Float32Array([Math.random() * (3.40282e+38)]))[0]);
    }
  });

  describe('construct', function () {
    var stream = new Peeracle.MemoryDataStream({buffer: buffer});

    it('should throw error on null argument', function () {
      expect(function () {
        var buf = null;
        var stream = new Peeracle.MemoryDataStream(buf);
      }).toThrowError('buffer should be an Uint8Array');
    });
    it('should throw an error on invalid argument', function () {
      expect(function () {
        var buf = null;
        new Peeracle.MemoryDataStream({});
      }).toThrowError('buffer should be an Uint8Array');
    });
    it('should be initialized', function () {
      expect(function () {
        var buf = new Uint8Array(1);
        new Peeracle.MemoryDataStream({buffer: buffer});
      }).not.toThrow();
    });
    it('should be an instance of DataStream', function () {
      expect(stream).toEqual(jasmine.any(Peeracle.DataStream));
    });
  });

  describe('length', function () {
    var stream = new Peeracle.MemoryDataStream({buffer: buffer});

    it('should be the same length of our buffer', function () {
      expect(stream.length()).toBe(buffer.length);
    });
  });

  describe('tell', function () {
    var stream = new Peeracle.MemoryDataStream({buffer: buffer});

    it('should be at the beginning on initialization', function () {
      expect(stream.tell()).toBe(0);
    });
  });

  describe('seek', function () {
    var stream = new Peeracle.MemoryDataStream({buffer: buffer});

    it('should seek at the beginning', function () {
      expect(stream.seek(0)).toBe(0);
    });
    it('should seek at the end', function () {
      expect(stream.seek(32)).toBe(32);
    });
    it('should throw an error when the value is negative', function () {
      expect(function () {
        stream.seek(-1);
      }).toThrowError('index out of bounds');
    });
    it('should throw an error when the value is out of bounds', function () {
      expect(function () {
        stream.seek(33);
      }).toThrowError('index out of bounds');
    });
  });

  describe('read', function () {
    var stream = new Peeracle.MemoryDataStream({buffer: buffer});

    it('should have an offset set to 0', function () {
      expect(stream.tell()).toEqual(0);
    });
    it('should read the first byte', function () {
      var bytes = stream.read(1);
      expect(bytes).toEqual(jasmine.any(Uint8Array));
      expect(bytes.length).toEqual(1);
      expect(bytes[0]).toEqual(buffer[0]);
    });
    it('should have an offset set to 1', function () {
      expect(stream.tell()).toEqual(1);
    });
    it('should read the two next bytes', function () {
      var bytes = stream.read(2);
      expect(bytes).toEqual(jasmine.any(Uint8Array));
      expect(bytes.length).toEqual(2);
      expect(bytes[0]).toEqual(buffer[1]);
      expect(bytes[1]).toEqual(buffer[2]);
    });
    it('should have an offset set to 3', function () {
      expect(stream.tell()).toEqual(3);
    });
    it('should read the four next bytes', function () {
      var bytes = stream.read(4);
      expect(bytes).toEqual(jasmine.any(Uint8Array));
      expect(bytes.length).toEqual(4);
      expect(bytes[0]).toEqual(buffer[3]);
      expect(bytes[1]).toEqual(buffer[4]);
      expect(bytes[2]).toEqual(buffer[5]);
      expect(bytes[3]).toEqual(buffer[6]);
    });
    it('should have an offset set to 7', function () {
      expect(stream.tell()).toEqual(7);
    });
    it('should throw an error for reading too much', function () {
      expect(function () {
        var bytes = stream.read(buffer.length);
      }).toThrowError('index out of bounds');
    });
    it('should still have an offset set to 7', function () {
      expect(stream.tell()).toEqual(7);
    });
  });
});
<commit_msg>MemoryDataStream: 'offset set to' -> 'offset equal to' inside unit test<commit_after>/*
 * Copyright (c) 2015 peeracle contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/* eslint-disable */
'use strict';

if (typeof Peeracle === 'undefined') {
  var Peeracle = require('..');
}

describe('MemoryDataStream', function () {
  var buffer = new Uint8Array(32);
  var floatBuffer = new Uint8Array(32);

  beforeEach(function () {
    var dataView = new DataView(floatBuffer.buffer);

    for (var i = 0; i < 32; ++i) {
      buffer[i] = Math.floor(Math.random() * 256);
    }

    for (var i = 0; i < 32; i += 4) {
      dataView.setFloat32(i, (new Float32Array([Math.random() * (3.40282e+38)]))[0]);
    }
  });

  describe('construct', function () {
    var stream = new Peeracle.MemoryDataStream({buffer: buffer});

    it('should throw error on null argument', function () {
      expect(function () {
        var buf = null;
        var stream = new Peeracle.MemoryDataStream(buf);
      }).toThrowError('buffer should be an Uint8Array');
    });
    it('should throw an error on invalid argument', function () {
      expect(function () {
        var buf = null;
        new Peeracle.MemoryDataStream({});
      }).toThrowError('buffer should be an Uint8Array');
    });
    it('should be initialized', function () {
      expect(function () {
        var buf = new Uint8Array(1);
        new Peeracle.MemoryDataStream({buffer: buffer});
      }).not.toThrow();
    });
    it('should be an instance of DataStream', function () {
      expect(stream).toEqual(jasmine.any(Peeracle.DataStream));
    });
  });

  describe('length', function () {
    var stream = new Peeracle.MemoryDataStream({buffer: buffer});

    it('should be the same length of our buffer', function () {
      expect(stream.length()).toBe(buffer.length);
    });
  });

  describe('tell', function () {
    var stream = new Peeracle.MemoryDataStream({buffer: buffer});

    it('should be at the beginning on initialization', function () {
      expect(stream.tell()).toBe(0);
    });
  });

  describe('seek', function () {
    var stream = new Peeracle.MemoryDataStream({buffer: buffer});

    it('should seek at the beginning', function () {
      expect(stream.seek(0)).toBe(0);
    });
    it('should seek at the end', function () {
      expect(stream.seek(32)).toBe(32);
    });
    it('should throw an error when the value is negative', function () {
      expect(function () {
        stream.seek(-1);
      }).toThrowError('index out of bounds');
    });
    it('should throw an error when the value is out of bounds', function () {
      expect(function () {
        stream.seek(33);
      }).toThrowError('index out of bounds');
    });
  });

  describe('read', function () {
    var stream = new Peeracle.MemoryDataStream({buffer: buffer});

    it('should have an offset equal to 0', function () {
      expect(stream.tell()).toEqual(0);
    });
    it('should read the first byte', function () {
      var bytes = stream.read(1);
      expect(bytes).toEqual(jasmine.any(Uint8Array));
      expect(bytes.length).toEqual(1);
      expect(bytes[0]).toEqual(buffer[0]);
    });
    it('should have an offset equal to 1', function () {
      expect(stream.tell()).toEqual(1);
    });
    it('should read the two next bytes', function () {
      var bytes = stream.read(2);
      expect(bytes).toEqual(jasmine.any(Uint8Array));
      expect(bytes.length).toEqual(2);
      expect(bytes[0]).toEqual(buffer[1]);
      expect(bytes[1]).toEqual(buffer[2]);
    });
    it('should have an offset equal to 3', function () {
      expect(stream.tell()).toEqual(3);
    });
    it('should read the four next bytes', function () {
      var bytes = stream.read(4);
      expect(bytes).toEqual(jasmine.any(Uint8Array));
      expect(bytes.length).toEqual(4);
      expect(bytes[0]).toEqual(buffer[3]);
      expect(bytes[1]).toEqual(buffer[4]);
      expect(bytes[2]).toEqual(buffer[5]);
      expect(bytes[3]).toEqual(buffer[6]);
    });
    it('should have an offset equal to 7', function () {
      expect(stream.tell()).toEqual(7);
    });
    it('should throw an error for reading too much', function () {
      expect(function () {
        var bytes = stream.read(buffer.length);
      }).toThrowError('index out of bounds');
    });
    it('should still have an offset equal to 7', function () {
      expect(stream.tell()).toEqual(7);
    });
  });

  describe('readChar', function () {
    var stream = new Peeracle.MemoryDataStream({buffer: buffer});

    it('should have an offset equal to 0', function () {
      expect(stream.tell()).toEqual(0);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

angular.module('crmApp.controllers', [])
    .controller('CustomerListController', ['$scope', '$location', 'custDataService', function ($scope, $location, custDataService) {

        $scope.search = function () {
            debugger;
            custDataService.getAllCustomers($scope.criteria, $scope.sortOption, $scope.currentPage)
                .then(function (data) {
                    debugger;
                    $scope.customers = data.results;
                    $scope.totalItems = data.inlineCount;
                    $scope.totalPages = data.inlineCount / 5;
                })
            .catch(function (error) {
                console.log('Error calling api: ' + error.message);
            });
        };

        $scope.search(null, 'companyName', 1);

        //$scope.$watchCollection('customers', function (newValue) {
        //    setPagination(newValue);
        //});

        //function setPagination(newValue) {
        //    if (!newValue) {
        //        return;
        //    }

        //    $scope.totalItems = newValue.length;
        //    $scope.currentPage = 1;
        //    $scope.maxSize = 5;

        //}

        $scope.setPage = function (pageNo) {
            $scope.currentPage = pageNo;
            $scope.search();
        };

        $scope.markForDelete = function (customer) {
            custDataService.deleteCustomer(customer, false);
        };

        $scope.edit = function (id) {
            location.href = '#/customer/' + id + '/edit/';
        };

        $scope.saveChanges = function () {
            custDataService.saveChanges();
        };

    }]).controller('EditCustomerController', ['$scope', '$location', '$routeParams', 'custDataService', function ($scope, $location, $routeParams, custDataService) {

        custDataService.getCustomerById($routeParams.customerId)
            .then(function (data) {
                $scope.customer = data.entity;
            }).catch(function (error) {
                console.log('Error calling api: ' + error.message);
            });

        $scope.cancel = function () {
            $scope.customer.entityAspect.rejectChanges(); //undo pending changes and reset entityState to 'Unchanged'
            $location.path('/');
        };

        $scope.delete = function () {
            custDataService.deleteCustomer($scope.customer, true);
            $location.path('/');
        };

        $scope.canDelete = true;
        $scope.save = function () {
            custDataService.saveChanges();
            $location.path('/');
        };

    }]).controller('CreateCustomerController', ['$scope', '$location', 'custDataService', function ($scope, $location, custDataService) {

        $scope.cancel = function () {
            $location.path('/');
        };

        var customer = custDataService.newCustomer({ customerID: 'TEMP' }); //TEMP is a HACK - Can't create entity w/o ID and 'AutoGeneratedKeyType' is none
        customer.customerID = '';
        $scope.customer = customer;

        $scope.save = function () {
            custDataService.saveChanges();
            $location.path('/');
        };
    }]);<commit_msg>clean up last checkin<commit_after>'use strict';

angular.module('crmApp.controllers', [])
    .controller('CustomerListController', ['$scope', '$location', 'custDataService', function ($scope, $location, custDataService) {

        $scope.search = function () {
            custDataService.getAllCustomers($scope.criteria, $scope.sortOption, $scope.currentPage)
                .then(function (data) {
                    debugger;
                    $scope.customers = data.results;
                    $scope.totalItems = data.inlineCount;
                    $scope.totalPages = data.inlineCount / 5;
                })
            .catch(function (error) {
                console.log('Error calling api: ' + error.message);
            });
        };

        $scope.search();

        $scope.setPage = function (pageNo) {
            $scope.currentPage = pageNo;
            $scope.search();
        };

        $scope.markForDelete = function (customer) {
            custDataService.deleteCustomer(customer, false);
        };

        $scope.edit = function (id) {
            location.href = '#/customer/' + id + '/edit/';
        };

        $scope.saveChanges = function () {
            custDataService.saveChanges();
        };

    }]).controller('EditCustomerController', ['$scope', '$location', '$routeParams', 'custDataService', function ($scope, $location, $routeParams, custDataService) {

        custDataService.getCustomerById($routeParams.customerId)
            .then(function (data) {
                $scope.customer = data.entity;
            }).catch(function (error) {
                console.log('Error calling api: ' + error.message);
            });

        $scope.cancel = function () {
            $scope.customer.entityAspect.rejectChanges(); //undo pending changes and reset entityState to 'Unchanged'
            $location.path('/');
        };

        $scope.delete = function () {
            custDataService.deleteCustomer($scope.customer, true);
            $location.path('/');
        };

        $scope.canDelete = true;
        $scope.save = function () {
            custDataService.saveChanges();
            $location.path('/');
        };

    }]).controller('CreateCustomerController', ['$scope', '$location', 'custDataService', function ($scope, $location, custDataService) {

        $scope.cancel = function () {
            $location.path('/');
        };

        var customer = custDataService.newCustomer({ customerID: 'TEMP' }); //TEMP is a HACK - Can't create entity w/o ID and 'AutoGeneratedKeyType' is none
        customer.customerID = '';
        $scope.customer = customer;

        $scope.save = function () {
            custDataService.saveChanges();
            $location.path('/');
        };
    }]);<|endoftext|>


<commit_before>define(['jquery'], function ($) {
    'use strict';
    var menuItem, util;

    var init = function (menu, utility, params, callback) {
        menuItem = menu;
        util = utility;

        if (typeof callback === 'function') {
            callback();
        }
    };

    var onClick = function () {
        var mode = "View";

        util.sf.moduleRoot = 'internalservices';
        util.sf.controller = "controlBar";
        util.sf.post('ToggleUserMode', { UserMode: mode }, function handleToggleUserMode() {
            window.parent.location.reload();
        });
    }

    return {
        init: init,
        onClick: onClick
    };
});
<commit_msg>DNN-9207: set location instead of reload to avoid post page again.<commit_after>define(['jquery'], function ($) {
    'use strict';
    var menuItem, util;

    var init = function (menu, utility, params, callback) {
        menuItem = menu;
        util = utility;

        if (typeof callback === 'function') {
            callback();
        }
    };

    var onClick = function () {
        var mode = "View";

        util.sf.moduleRoot = 'internalservices';
        util.sf.controller = "controlBar";
        util.sf.post('ToggleUserMode', { UserMode: mode }, function handleToggleUserMode() {
            window.top.location.href = window.top.location.href;
        });
    }

    return {
        init: init,
        onClick: onClick
    };
});
<|endoftext|>


<commit_before>angular.module('dynamicForms').directive('dfModel', function($compile, $templateCache, DfSchemaService) {
    return {
        restrict: 'EA',
        priority: 1100,
        compile: function(element, attrs) {
            element.removeAttr('df-model');

            var columns = DfSchemaService.extractColumns(attrs.dfSchema),
                mode = attrs.mode;

            var template = $templateCache.get('dynamic-forms/templates/column.html');

            _.each(columns, function(it) {
                element.append( $templateCache.get(it.template) || _.template(template)({column: it.column, layout: mode === 'summary' ? 'form' : 'form'}) );
            });
        }
    }
});<commit_msg>Fix up template<commit_after>angular.module('dynamicForms').directive('dfModel', function($compile, $templateCache, DfSchemaService) {
    return {
        restrict: 'EA',
        priority: 1100,
        compile: function(element, attrs) {
            element.removeAttr('df-model');

            var columns = DfSchemaService.extractColumns(attrs.dfSchema),
                mode = attrs.mode;

            var template = $templateCache.get('templates/column.html');

            _.each(columns, function(it) {
                element.append( $templateCache.get(it.template) || _.template(template)({column: it.column, layout: mode === 'summary' ? 'form' : 'form'}) );
            });
        }
    }
});<|endoftext|>