<commit_before>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function() {
  var Pos = CodeMirror.Pos;

  namespace = "html-hint_";

  testData =[
    {
      name: "html-element",
      value: "<htm",
      list: ["<html"]
    },
    {
      name: "element-close",
      value: "\n</",
      list: [""]
    },
    {
      name: "linkref-attribute",
      value: "<link hreflang='z",
      from: Pos(0,"<link hreflang=".length),
      list: ["'zh'","'za'","'zu'"]
    },
    {
      name: "html-completion",
      value: "\n",
      list: ["<head","<body",""]
    }
  ];

  function escapeHtmlList(o) {
    return '' +
      JSON.stringify(o.list,null,2)
      .replace(/</g, "<")
      .replace(/>/g, ">") +
      ''
      ;
  }

  function test(name, spec) {
    testCM(name, function(cm) {
      cm.setValue(spec.value);
      cm.setCursor(spec.cursor);
      var completion = CodeMirror.hint.html(cm);
      if (!deepCompare(completion.list, spec.list))
        throw new Failure("Wrong completion results. Got" +
          escapeHtmlList(completion) +" but expected" +
          escapeHtmlList(spec));
      eqCharPos(completion.from, spec.from,'from-failed');
      eqCharPos(completion.to, spec.to, 'to-failed');
    }, {
      value: spec.value,
      mode: spec.mode || "text/html"
    });
  }

  testData.forEach(function (value) {
    // Use sane defaults
    var lines = value.value.split(/\n/);
    value.to = value.pos || Pos(lines.length-1, lines[lines.length-1].length);
    value.from = value.from || Pos(lines.length-1,0);
    value.cursor = value.cursor || value.to;
    var name = value.name ||value.value;
    test(name,value) });

  function deepCompare(a, b) {
    if (a === b) return true;
    if (!(a && typeof a === "object") ||
        !(b && typeof b === "object")) return false;
    var array = Array.isArray(a);
    if (Array.isArray(b) !== array) return false;
    if (array) {
      if (a.length !== b.length) return false;
      for (var i = 0; i < a.length; i++) if (!deepCompare(a[i], b[i])) return false
    } else {
      for (var p in a) if (!(p in b) || !deepCompare(a[p], b[p])) return false;
      for (var p in b) if (!(p in a)) return false
    }
    return true
  }
})();
<commit_msg>Small cleanups for d232e5075<commit_after>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function() {
  var Pos = CodeMirror.Pos;

  namespace = "html-hint_";

  testData =[
    {
      name: "html-element",
      value: "<htm",
      list: ["<html"]
    },
    {
      name: "element-close",
      value: "\n</",
      list: [""]
    },
    {
      name: "linkref-attribute",
      value: "<link hreflang='z",
      from: Pos(0,"<link hreflang=".length),
      list: ["'zh'","'za'","'zu'"]
    },
    {
      name: "html-completion",
      value: "\n",
      list: ["<head","<body",""]
    }
  ];

  function escapeHtmlList(o) {
    return '' +
      JSON.stringify(o.list,null,2)
      .replace(/</g, "<")
      .replace(/>/g, ">") +
      ''
  }

  function test(name, spec) {
    testCM(name, function(cm) {
      cm.setValue(spec.value);
      cm.setCursor(spec.cursor);
      var completion = CodeMirror.hint.html(cm);
      if (!deepCompare(completion.list, spec.list))
        throw new Failure("Wrong completion results. Got" +
          escapeHtmlList(completion) +" but expected" +
          escapeHtmlList(spec));
      eqCharPos(completion.from, spec.from,'from-failed');
      eqCharPos(completion.to, spec.to, 'to-failed');
    }, {
      value: spec.value,
      mode: spec.mode || "text/html"
    });
  }

  testData.forEach(function (value) {
    // Use sane defaults
    var lines = value.value.split(/\n/);
    value.to = value.pos || Pos(lines.length-1, lines[lines.length-1].length);
    value.from = value.from || Pos(lines.length-1,0);
    value.cursor = value.cursor || value.to;
    var name = value.name ||value.value;
    test(name,value)
  });

  function deepCompare(a, b) {
    if (a === b) return true;
    if (!(a && typeof a === "object") ||
        !(b && typeof b === "object")) return false;
    var array = a instanceof Array
    if ((b instanceof Array) !== array) return false;
    if (array) {
      if (a.length !== b.length) return false;
      for (var i = 0; i < a.length; i++) if (!deepCompare(a[i], b[i])) return false
    } else {
      for (var p in a) if (!(p in b) || !deepCompare(a[p], b[p])) return false;
      for (var p in b) if (!(p in a)) return false
    }
    return true
  }
})();
<|endoftext|>


<commit_before>/* eslint-disable */
/* bender-tags: editor,unit */
/* bender-ckeditor-plugins: wysiwygarea,structuredheadings,toolbar,basicstyles,dialog,richcombo,undo */
/* eslint-enable */

// Clean up all instances been created on the page.
(function () {

  bender.editor = {
    allowedForTests: "h1; h2; h3; h4; h5; p"
  };

  function getDetectedPreset(editor) {
    return editor.plugins.structuredheadings.getCurrentPreset();
  };

  bender.test({
    setUp: function () {
      //Anything to be run before each test if needed
    },

    tearDown: function () {
      // reset the plugin between tests
      var editor = this.editorBot.editor;
      editor.plugins.structuredheadings.currentPreset = null;
    },

    "default is numbered": function () {
      var bot = this.editorBot;
      var editor = bot.editor;
      bot.setHtmlWithSelection(
        "
^foo
" +
        "
bar
"
      );

      assert.areEqual(
        "1.1.1.1.1.",
        getDetectedPreset(editor)
      );
    },

    "invalid combos return numbered": function () {
      var bot = this.editorBot;
      var editor = bot.editor;
      bot.setHtmlWithSelection(
        "
^foo
" +
        "
bar
"
      );

      assert.areEqual(
        "1.1.1.1.1.",
        getDetectedPreset(editor)
      );
    }

  });
})();
<commit_msg>add actual detection.  quelle surprise, my first implementation is bugged on this.<commit_after>/* eslint-disable */
/* bender-tags: editor,unit */
/* bender-ckeditor-plugins: wysiwygarea,structuredheadings,toolbar,basicstyles,dialog,richcombo,undo */
/* eslint-enable */

// Clean up all instances been created on the page.
(function () {

  bender.editor = {
    allowedForTests: "h1; h2; h3; h4; h5; p"
  };

  function getDetectedPreset(editor) {
    return editor.plugins.structuredheadings.getCurrentPreset();
  };

  bender.test({
    setUp: function () {
      //Anything to be run before each test if needed
    },

    tearDown: function () {
      // reset the plugin between tests
      var editor = this.editorBot.editor;
      editor.plugins.structuredheadings.currentPreset = null;
    },

    "default is numbered": function () {
      var bot = this.editorBot;
      var editor = bot.editor;
      bot.setHtmlWithSelection(
        "
^foo
" +
        "
bar
"
      );

      assert.areEqual(
        "1.1.1.1.1.",
        getDetectedPreset(editor)
      );
    },

    "invalid combos return numbered": function () {
      var bot = this.editorBot;
      var editor = bot.editor;
      bot.setHtmlWithSelection(
        "
^foo
" +
        "
bar
"
      );

      assert.areEqual(
        "1.1.1.1.1.",
        getDetectedPreset(editor)
      );
    },

    "can detect based off of one level": function () {
      var bot = this.editorBot;
      var editor = bot.editor;
      bot.setHtmlWithSelection(
        "
^foo
"
      );

      assert.areEqual(
        "1. a. i. a. i.",
        getDetectedPreset(editor)
      );
    }

  });
})();
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*jshint node: true*/

var Q     = require('q'),
    nopt  = require('nopt'),
    path  = require('path'),
    shell = require('shelljs'),
    spawn = require('./spawn'),
    check_reqs = require('./check_reqs');

var projectPath = path.join(__dirname, '..', '..');

module.exports.run = function (argv) {

    var args = nopt({
        // "archs": String,     // TODO: add support for building different archs
        'debug': Boolean,
        'release': Boolean,
        'device': Boolean,
        'emulator': Boolean,
    }, {'-r': '--release'}, argv);

    if (args.debug && args.release) {
        return Q.reject('Only one of "debug"/"release" options should be specified');
    }

    if (args.device && args.emulator) {
        return Q.reject('Only one of "device"/"emulator" options should be specified');
    }

    return check_reqs.run().then(function () {
        return findXCodeProjectIn(projectPath);
    }).then(function (projectName) {
        var configuration = args.release ? 'Release' : 'Debug';

        console.log('Building project  : ' + path.join(projectPath, projectName + '.xcodeproj'));
        console.log('\tConfiguration : ' + configuration);
        console.log('\tPlatform      : ' + (args.device ? 'device' : 'emulator'));

        var xcodebuildArgs = getXcodeArgs(projectName, projectPath, configuration, args.device);
        return spawn('xcodebuild', xcodebuildArgs, projectPath);
    });
};

/**
 * Searches for first XCode project in specified folder
 * @param  {String} projectPath Path where to search project
 * @return {Promise}            Promise either fulfilled with project name or rejected
 */
function findXCodeProjectIn(projectPath) {
    // 'Searching for Xcode project in ' + projectPath);
    var xcodeProjFiles = shell.ls(projectPath).filter(function (name) {
        return path.extname(name) === '.xcodeproj';
    });

    if (xcodeProjFiles.length === 0) {
        return Q.reject('No Xcode project found in ' + projectPath);
    }
    if (xcodeProjFiles.length > 1) {
        console.warn('Found multiple .xcodeproj directories in \n' +
            projectPath + '\nUsing first one');
    }

    var projectName = path.basename(xcodeProjFiles[0], '.xcodeproj');
    return Q.resolve(projectName);
}

module.exports.findXCodeProjectIn = findXCodeProjectIn;

/**
 * Returns array of arguments for xcodebuild
 * @param  {String}  projectName   Name of xcode project
 * @param  {String}  projectPath   Path to project file. Will be used to set CWD for xcodebuild
 * @param  {String}  configuration Configuration name: debug|release
 * @param  {Boolean} isDevice      Flag that specify target for package (device/emulator)
 * @return {Array}                 Array of arguments that could be passed directly to spawn method
 */
function getXcodeArgs(projectName, projectPath, configuration, isDevice) {
    var xcodebuildArgs;
    if (isDevice) {
        xcodebuildArgs = [
            '-xcconfig', path.join(__dirname, '..', 'build-' + configuration.toLowerCase() + '.xcconfig'),
            '-project', projectName + '.xcodeproj',
            'ARCHS="armv7 armv7s arm64"',
            '-target', projectName,
            '-configuration', configuration,
            '-sdk', 'iphoneos',
            'build',
            'VALID_ARCHS="armv7 armv7s arm64"',
            'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'device'),
            'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')
        ];
    } else { // emulator
        xcodebuildArgs = [
            '-xcconfig', path.join(__dirname, '..', 'build-' + configuration.toLowerCase() + '.xcconfig'),
            '-project', projectName + '.xcodeproj',
            'ARCHS="i386"',
            '-target', projectName ,
            '-configuration', configuration,
            '-sdk', 'iphonesimulator',
            'build',
            'VALID_ARCHS="i386"',
            'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'emulator'),
            'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')
        ];
    }
    return xcodebuildArgs;
}

// help/usage function
module.exports.help = function help() {
    console.log('');
    console.log('Usage: build [ --debug | --release ] [--archs=\"<list of architectures...>\"] [--device | --simulator]');
    console.log('    --help    : Displays this dialog.');
    console.log('    --debug   : Builds project in debug mode. (Default)');
    console.log('    --release : Builds project in release mode.');
    console.log('    -r        : Shortcut :: builds project in release mode.');
    // TODO: add support for building different archs
    // console.log("    --archs   : Builds project binaries for specific chip architectures (`anycpu`, `arm`, `x86`, `x64`).");
    console.log('    --device, --simulator');
    console.log('              : Specifies, what type of project to build');
    console.log('examples:');
    console.log('    build ');
    console.log('    build --debug');
    console.log('    build --release');
    // TODO: add support for building different archs
    // console.log("    build --release --archs=\"armv7\"");
    console.log('');
    process.exit(0);
};
<commit_msg>CB-8436 Remove unneeded "" when composing xcodebuild arguments (close #130)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*jshint node: true*/

var Q     = require('q'),
    nopt  = require('nopt'),
    path  = require('path'),
    shell = require('shelljs'),
    spawn = require('./spawn'),
    check_reqs = require('./check_reqs');

var projectPath = path.join(__dirname, '..', '..');

module.exports.run = function (argv) {

    var args = nopt({
        // "archs": String,     // TODO: add support for building different archs
        'debug': Boolean,
        'release': Boolean,
        'device': Boolean,
        'emulator': Boolean,
    }, {'-r': '--release'}, argv);

    if (args.debug && args.release) {
        return Q.reject('Only one of "debug"/"release" options should be specified');
    }

    if (args.device && args.emulator) {
        return Q.reject('Only one of "device"/"emulator" options should be specified');
    }

    return check_reqs.run().then(function () {
        return findXCodeProjectIn(projectPath);
    }).then(function (projectName) {
        var configuration = args.release ? 'Release' : 'Debug';

        console.log('Building project  : ' + path.join(projectPath, projectName + '.xcodeproj'));
        console.log('\tConfiguration : ' + configuration);
        console.log('\tPlatform      : ' + (args.device ? 'device' : 'emulator'));

        var xcodebuildArgs = getXcodeArgs(projectName, projectPath, configuration, args.device);
        return spawn('xcodebuild', xcodebuildArgs, projectPath);
    });
};

/**
 * Searches for first XCode project in specified folder
 * @param  {String} projectPath Path where to search project
 * @return {Promise}            Promise either fulfilled with project name or rejected
 */
function findXCodeProjectIn(projectPath) {
    // 'Searching for Xcode project in ' + projectPath);
    var xcodeProjFiles = shell.ls(projectPath).filter(function (name) {
        return path.extname(name) === '.xcodeproj';
    });

    if (xcodeProjFiles.length === 0) {
        return Q.reject('No Xcode project found in ' + projectPath);
    }
    if (xcodeProjFiles.length > 1) {
        console.warn('Found multiple .xcodeproj directories in \n' +
            projectPath + '\nUsing first one');
    }

    var projectName = path.basename(xcodeProjFiles[0], '.xcodeproj');
    return Q.resolve(projectName);
}

module.exports.findXCodeProjectIn = findXCodeProjectIn;

/**
 * Returns array of arguments for xcodebuild
 * @param  {String}  projectName   Name of xcode project
 * @param  {String}  projectPath   Path to project file. Will be used to set CWD for xcodebuild
 * @param  {String}  configuration Configuration name: debug|release
 * @param  {Boolean} isDevice      Flag that specify target for package (device/emulator)
 * @return {Array}                 Array of arguments that could be passed directly to spawn method
 */
function getXcodeArgs(projectName, projectPath, configuration, isDevice) {
    var xcodebuildArgs;
    if (isDevice) {
        xcodebuildArgs = [
            '-xcconfig', path.join(__dirname, '..', 'build-' + configuration.toLowerCase() + '.xcconfig'),
            '-project', projectName + '.xcodeproj',
            'ARCHS=armv7 armv7s arm64',
            '-target', projectName,
            '-configuration', configuration,
            '-sdk', 'iphoneos',
            'build',
            'VALID_ARCHS=armv7 armv7s arm64',
            'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'device'),
            'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')
        ];
    } else { // emulator
        xcodebuildArgs = [
            '-xcconfig', path.join(__dirname, '..', 'build-' + configuration.toLowerCase() + '.xcconfig'),
            '-project', projectName + '.xcodeproj',
            'ARCHS="i386"',
            '-target', projectName ,
            '-configuration', configuration,
            '-sdk', 'iphonesimulator',
            'build',
            'VALID_ARCHS="i386"',
            'CONFIGURATION_BUILD_DIR=' + path.join(projectPath, 'build', 'emulator'),
            'SHARED_PRECOMPS_DIR=' + path.join(projectPath, 'build', 'sharedpch')
        ];
    }
    return xcodebuildArgs;
}

// help/usage function
module.exports.help = function help() {
    console.log('');
    console.log('Usage: build [ --debug | --release ] [--archs=\"<list of architectures...>\"] [--device | --simulator]');
    console.log('    --help    : Displays this dialog.');
    console.log('    --debug   : Builds project in debug mode. (Default)');
    console.log('    --release : Builds project in release mode.');
    console.log('    -r        : Shortcut :: builds project in release mode.');
    // TODO: add support for building different archs
    // console.log("    --archs   : Builds project binaries for specific chip architectures (`anycpu`, `arm`, `x86`, `x64`).");
    console.log('    --device, --simulator');
    console.log('              : Specifies, what type of project to build');
    console.log('examples:');
    console.log('    build ');
    console.log('    build --debug');
    console.log('    build --release');
    // TODO: add support for building different archs
    // console.log("    build --release --archs=\"armv7\"");
    console.log('');
    process.exit(0);
};
<|endoftext|>


<commit_before>module('Testimonial slide tests');
var dataForSlide = {
  authorHref: 'https://github.com/AlekseyLeshko',
  company: 'Company',
  companyHref: 'https://github.com/AlekseyLeshko',
  fotoSrc: 'http://2.gravatar.com/avatar/027ed55733da6f7037335e0af0c46591?s=146',
  fullName: 'Aleksey Leshko',
  quote: 'quote'
};

var emptydata = {
  authorHref: '',
  company: '',
  companyHref: '',
  fotoSrc: '',
  fullName: '',
  quote: ''
};

function compareSlideData(x, y) {
  ok(x.authorHref === y.authorHref, '');
  ok(x.company === y.company, '');
  ok(x.companyHref === y.companyHref, '');
  ok(x.fotoSrc === y.fotoSrc, '');
  ok(x.fullName === y.fullName, '');
  ok(x.quote === y.quote, '');
}

test('Create slide with correct data', function() {
  var slide = new TestimonialSlide(dataForSlide);
  compareSlideData(slide.data, dataForSlide);
  ok(slide.$domNode !== undefined, 'Slide has DOM node');
});

test('Create slide with empty data', function() {
  var slide = new TestimonialSlide();
  ok(slide.data !== undefined, 'Slide has empty data');
  ok(slide.$domNode !== undefined, 'Slide has DOM node');
});

test('Slide css class', function() {
  var slide = new TestimonialSlide(dataForSlide);
  ok(slide.$domNode.attr('class') === 'testimonial_slide', 'New slide has correct css class');
});

test('Create slide data of empty data', function() {
  var slideData = TestimonialSlide.prototype.createData();
  ok(slideData !== undefined, 'Slide data not empty');
  compareSlideData(slideData, emptydata);
});

test('Create slide data of correct data', function() {
  var slideData = TestimonialSlide.prototype.createData(dataForSlide);
  compareSlideData(slideData, dataForSlide);
});

test('Create options', function() {
  TestimonialSlide.prototype.createOptions();
  ok(TestimonialSlide.prototype.options.duration === 750, '');
  ok(TestimonialSlide.prototype.options.distance === 250, '');
  ok(TestimonialSlide.prototype.options.cssClass === 'testimonial_slide', '');
});

test('Get DOM node', function() {
  var testId = 'testId';
  var domNode = $('<div />', {
    id: testId
  });
  TestimonialSlide.prototype.$domNode = domNode;
  var $expectedDomNode = TestimonialSlide.prototype.getDomNode();
  ok($expectedDomNode.attr('id') === testId, '');
});

test('Create empty dom node', function() {
  var expectedCssClass = 'testimonial_slide';
  TestimonialSlide.prototype.createOptions();
  TestimonialSlide.prototype.createStandardDomNode();
  var cssClass = TestimonialSlide.prototype.$domNode.attr('class');
  ok(cssClass === expectedCssClass, '');
  ok(cssClass === TestimonialSlide.prototype.options.cssClass, '');
});

test('Height dom node', function() {
  var height = 2014;
  var $domNode = $('<div />', {
    height: height
  });
  TestimonialSlide.prototype.$domNode = $domNode;
  ok(TestimonialSlide.prototype.height() === height, '');
});

test('Hide slide', function() {
  TestimonialSlide.prototype.createOptions();
  TestimonialSlide.prototype.createStandardDomNode();
  TestimonialSlide.prototype.hideSlide();
  var $domNode = TestimonialSlide.prototype.$domNode;
  var distanceVal = '-' + TestimonialSlide.prototype.options.distance + 'px';
  ok($domNode.css('display') === 'none', '');
  ok($domNode.css('opacity') === '0', '');
  ok($domNode.css('margin-left') === distanceVal, '');
});

asyncTest('Animate show', function() {
  TestimonialSlide.prototype.createOptions();
  var duration = (TestimonialSlide.prototype.options.duration * 2) + 50;
  TestimonialSlide.prototype.createStandardDomNode();
  TestimonialSlide.prototype.hideSlide();

  TestimonialSlide.prototype.animateShow();
  setTimeout(function() {
    var $domNode = TestimonialSlide.prototype.$domNode;
    ok($domNode.css('display') === '', 'Slide is show');
    ok(parseInt($domNode.css('opacity')) === 1, 'Slide opacity is not 0');
    ok($domNode.css('margin-left') === '0px', 'Slide margin-left is 0');

    start();
  }, duration);
});

asyncTest('Animate show', function() {
  TestimonialSlide.prototype.createOptions();
  var duration = TestimonialSlide.prototype.options.duration + 50;
  var distanceVal = '-' + TestimonialSlide.prototype.options.distance + 'px';
  TestimonialSlide.prototype.createStandardDomNode();

  TestimonialSlide.prototype.animateHide();
  setTimeout(function() {
    var $domNode = TestimonialSlide.prototype.$domNode;

    ok($domNode.css('display') === 'none', 'Slidedisplay is none');
    ok($domNode.css('opacity') === '0', 'Slide opacity is 0');
    ok($domNode.css('margin-left') === distanceVal, 'Slide margin-left is ' + distanceVal);
    start();
  }, duration);
});

test('Create dom node with author foto', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $img = TestimonialSlide.prototype.createImgAuthorFoto();
  ok($img.prop('nodeName') === 'IMG', 'Dom node is img');
  ok($img.attr('class') === 'author_foto', 'Css class dom node is correct');
  ok($img.attr('src') === dataForSlide.fotoSrc, 'Src dom node is correct');
});

test('Create link node', function() {
  var href = 'http://test.com';
  var text = 'test text';
  var $link = TestimonialSlide.prototype.createLinkNode(href, text);
  ok($link.prop('nodeName') === 'A', 'Dom node is link');
  ok($link.attr('target') === '_blank', 'link target is blank');
  ok($link.attr('href') === href, 'Link href is correct');
  ok($link.text() === text, 'link text is correct');
});

test('Create company node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createCompanyNode();
  ok($node.prop('nodeName') === 'DIV', 'Company node is div');
  ok($node.attr('class') === 'company', 'Css class dom node is correct');

  var $link = $node.children().first();
  ok($link.prop('nodeName') === 'A', 'Present link in company node');
  ok($link.attr('target') === '_blank', 'Link target is blank');
  ok($link.attr('href') === dataForSlide.companyHref, 'Link href is correct');
  ok($link.text() === dataForSlide.company, 'Link text is correct');
});

test('Create author node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createAuthorNode();
  ok($node.prop('nodeName') === 'DIV', 'Author node is div');
  ok($node.attr('class') === 'author', 'Css class dom node is correct');
  ok($node.text() === '- ' + dataForSlide.fullName, 'Text in node is correct');

  var $link = $node.children().first();
  ok($link.prop('nodeName') === 'A', 'Present link in author node');
  ok($link.attr('target') === '_blank', 'Link target is blank');
  ok($link.attr('href') === dataForSlide.authorHref, 'Link href is correct');
  ok($link.text() === dataForSlide.fullName, 'Link text is correct');
});

test('Create signature node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createSignatureNode();
  ok($node.prop('nodeName') === 'DIV', 'Signature node is div');
  ok($node.attr('class') === 'signature', 'Css class dom node is correct');

  var $children = $node.children();
  ok($children.length === 2, '2 nodes in signature node');
  ok($children.first().attr('class') === 'author', 'Css class first child node is correct');
  ok($children.last().attr('class') === 'company', 'Css class last child node is correct');
});

test('Create quotation mark inverted', function() {
  var $node = TestimonialSlide.prototype.createQuotationMarkInverted();
  ok($node.prop('nodeName') === 'DIV', 'Quotation mark inverted node is div');
  ok($node.attr('class') === 'quotation_mark_inverted', 'Css class dom node is correct');
});

test('Create quotation mark', function() {
  var $node = TestimonialSlide.prototype.createQuotationMark();
  ok($node.prop('nodeName') === 'DIV', 'Quotation mark node is div');
  ok($node.attr('class') === 'quotation_mark', 'Css class dom node is correct');
});

test('Create text node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createTextNode();
  ok($node.prop('nodeName') === 'DIV', 'Text node is div');
  ok($node.attr('class') === 'text', 'Css class dom node is correct');
});

test('Create quote node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createQuoteNode();
  ok($node.prop('nodeName') === 'DIV', 'Quote node is div');
  ok($node.attr('class') === 'quote', 'Css class dom node is correct');

  var $children = $node.children();
  ok($children.length === 4, '4 nodes in quote node');
  ok($children.first().attr('class') === 'quotation_mark', 'Css class 1st child node is correct');
  ok($($children[1]).attr('class') === 'text', 'Css class 2nd child node is correct');
  ok($($children[2]).attr('class') === 'quotation_mark_inverted', 'Css class 3rd child node is correct');
  ok($children.last().attr('class') === 'signature', 'Css class 4th child node is correct');
});

test('Create slide', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  TestimonialSlide.prototype.createOptions();
  TestimonialSlide.prototype.createSlide();
  var $node = TestimonialSlide.prototype.$domNode;
  ok($node.prop('nodeName') === 'DIV', 'Slide node is div');
  ok($node.attr('class') === TestimonialSlide.prototype.options.cssClass, 'Css class dom node is correct');

  var $children = $node.children();
  ok($children.length === 2, '2 nodes in slide node');
  ok($children.first().attr('class') === 'quote', 'Css class first child node is correct');
  ok($children.last().attr('class') === 'author_foto', 'Css class last child node is correct');
});
<commit_msg>Fix test<commit_after>module('Testimonial slide tests');
var dataForSlide = {
  authorHref: 'https://github.com/AlekseyLeshko',
  company: 'Company',
  companyHref: 'https://github.com/AlekseyLeshko',
  fotoSrc: 'http://2.gravatar.com/avatar/027ed55733da6f7037335e0af0c46591?s=146',
  fullName: 'Aleksey Leshko',
  quote: 'quote'
};

var emptydata = {
  authorHref: '',
  company: '',
  companyHref: '',
  fotoSrc: '',
  fullName: '',
  quote: ''
};

function compareSlideData(x, y) {
  ok(x.authorHref === y.authorHref, '');
  ok(x.company === y.company, '');
  ok(x.companyHref === y.companyHref, '');
  ok(x.fotoSrc === y.fotoSrc, '');
  ok(x.fullName === y.fullName, '');
  ok(x.quote === y.quote, '');
}

test('Create slide with correct data', function() {
  var slide = new TestimonialSlide(dataForSlide);
  compareSlideData(slide.data, dataForSlide);
  ok(slide.$domNode !== undefined, 'Slide has DOM node');
});

test('Create slide with empty data', function() {
  var slide = new TestimonialSlide();
  ok(slide.data !== undefined, 'Slide has empty data');
  ok(slide.$domNode !== undefined, 'Slide has DOM node');
});

test('Slide css class', function() {
  var slide = new TestimonialSlide(dataForSlide);
  ok(slide.$domNode.attr('class') === 'testimonial_slide', 'New slide has correct css class');
});

test('Create slide data of empty data', function() {
  var slideData = TestimonialSlide.prototype.createData();
  ok(slideData !== undefined, 'Slide data not empty');
  compareSlideData(slideData, emptydata);
});

test('Create slide data of correct data', function() {
  var slideData = TestimonialSlide.prototype.createData(dataForSlide);
  compareSlideData(slideData, dataForSlide);
});

test('Create options', function() {
  TestimonialSlide.prototype.createOptions();
  ok(TestimonialSlide.prototype.options.duration === 750, '');
  ok(TestimonialSlide.prototype.options.distance === 250, '');
  ok(TestimonialSlide.prototype.options.cssClass === 'testimonial_slide', '');
});

test('Get DOM node', function() {
  var testId = 'testId';
  var domNode = $('<div />', {
    id: testId
  });
  TestimonialSlide.prototype.$domNode = domNode;
  var $expectedDomNode = TestimonialSlide.prototype.getDomNode();
  ok($expectedDomNode.attr('id') === testId, '');
});

test('Create empty dom node', function() {
  var expectedCssClass = 'testimonial_slide';
  TestimonialSlide.prototype.createOptions();
  TestimonialSlide.prototype.createStandardDomNode();
  var cssClass = TestimonialSlide.prototype.$domNode.attr('class');
  ok(cssClass === expectedCssClass, '');
  ok(cssClass === TestimonialSlide.prototype.options.cssClass, '');
});

test('Height dom node', function() {
  var height = 2014;
  var $domNode = $('<div />', {
    height: height
  });
  TestimonialSlide.prototype.$domNode = $domNode;
  ok(TestimonialSlide.prototype.height() === height, '');
});

test('Hide slide', function() {
  TestimonialSlide.prototype.createOptions();
  TestimonialSlide.prototype.createStandardDomNode();
  TestimonialSlide.prototype.hideSlide();
  var $domNode = TestimonialSlide.prototype.$domNode;
  var distanceVal = '-' + TestimonialSlide.prototype.options.distance + 'px';
  ok($domNode.css('display') === 'none', '');
  ok($domNode.css('opacity') === '0', '');
  ok($domNode.css('margin-left') === distanceVal, '');
});

var delay = 500;

asyncTest('Animate show', function() {
  TestimonialSlide.prototype.createOptions();
  var duration = (TestimonialSlide.prototype.options.duration * 2) + delay;
  TestimonialSlide.prototype.createStandardDomNode();
  TestimonialSlide.prototype.hideSlide();

  TestimonialSlide.prototype.animateShow();
  setTimeout(function() {
    var $domNode = TestimonialSlide.prototype.$domNode;
    ok($domNode.css('display') === '', 'Slide is show');
    ok(parseInt($domNode.css('opacity')) === 1, 'Slide opacity is not 0');
    ok($domNode.css('margin-left') === '0px', 'Slide margin-left is 0');

    start();
  }, duration);
});

asyncTest('Animate hide', function() {
  TestimonialSlide.prototype.createOptions();
  var duration = TestimonialSlide.prototype.options.duration + delay;
  var distanceVal = '-' + TestimonialSlide.prototype.options.distance + 'px';
  TestimonialSlide.prototype.createStandardDomNode();

  TestimonialSlide.prototype.animateHide();
  setTimeout(function() {
    var $domNode = TestimonialSlide.prototype.$domNode;

    ok($domNode.css('display') === 'none', 'Slidedisplay is none');
    ok($domNode.css('opacity') === '0', 'Slide opacity is 0');
    ok($domNode.css('margin-left') === distanceVal, 'Slide margin-left is ' + distanceVal);
    start();
  }, duration);
});

test('Create dom node with author foto', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $img = TestimonialSlide.prototype.createImgAuthorFoto();
  ok($img.prop('nodeName') === 'IMG', 'Dom node is img');
  ok($img.attr('class') === 'author_foto', 'Css class dom node is correct');
  ok($img.attr('src') === dataForSlide.fotoSrc, 'Src dom node is correct');
});

test('Create link node', function() {
  var href = 'http://test.com';
  var text = 'test text';
  var $link = TestimonialSlide.prototype.createLinkNode(href, text);
  ok($link.prop('nodeName') === 'A', 'Dom node is link');
  ok($link.attr('target') === '_blank', 'link target is blank');
  ok($link.attr('href') === href, 'Link href is correct');
  ok($link.text() === text, 'link text is correct');
});

test('Create company node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createCompanyNode();
  ok($node.prop('nodeName') === 'DIV', 'Company node is div');
  ok($node.attr('class') === 'company', 'Css class dom node is correct');

  var $link = $node.children().first();
  ok($link.prop('nodeName') === 'A', 'Present link in company node');
  ok($link.attr('target') === '_blank', 'Link target is blank');
  ok($link.attr('href') === dataForSlide.companyHref, 'Link href is correct');
  ok($link.text() === dataForSlide.company, 'Link text is correct');
});

test('Create author node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createAuthorNode();
  ok($node.prop('nodeName') === 'DIV', 'Author node is div');
  ok($node.attr('class') === 'author', 'Css class dom node is correct');
  ok($node.text() === '- ' + dataForSlide.fullName, 'Text in node is correct');

  var $link = $node.children().first();
  ok($link.prop('nodeName') === 'A', 'Present link in author node');
  ok($link.attr('target') === '_blank', 'Link target is blank');
  ok($link.attr('href') === dataForSlide.authorHref, 'Link href is correct');
  ok($link.text() === dataForSlide.fullName, 'Link text is correct');
});

test('Create signature node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createSignatureNode();
  ok($node.prop('nodeName') === 'DIV', 'Signature node is div');
  ok($node.attr('class') === 'signature', 'Css class dom node is correct');

  var $children = $node.children();
  ok($children.length === 2, '2 nodes in signature node');
  ok($children.first().attr('class') === 'author', 'Css class first child node is correct');
  ok($children.last().attr('class') === 'company', 'Css class last child node is correct');
});

test('Create quotation mark inverted', function() {
  var $node = TestimonialSlide.prototype.createQuotationMarkInverted();
  ok($node.prop('nodeName') === 'DIV', 'Quotation mark inverted node is div');
  ok($node.attr('class') === 'quotation_mark_inverted', 'Css class dom node is correct');
});

test('Create quotation mark', function() {
  var $node = TestimonialSlide.prototype.createQuotationMark();
  ok($node.prop('nodeName') === 'DIV', 'Quotation mark node is div');
  ok($node.attr('class') === 'quotation_mark', 'Css class dom node is correct');
});

test('Create text node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createTextNode();
  ok($node.prop('nodeName') === 'DIV', 'Text node is div');
  ok($node.attr('class') === 'text', 'Css class dom node is correct');
});

test('Create quote node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createQuoteNode();
  ok($node.prop('nodeName') === 'DIV', 'Quote node is div');
  ok($node.attr('class') === 'quote', 'Css class dom node is correct');

  var $children = $node.children();
  ok($children.length === 4, '4 nodes in quote node');
  ok($children.first().attr('class') === 'quotation_mark', 'Css class 1st child node is correct');
  ok($($children[1]).attr('class') === 'text', 'Css class 2nd child node is correct');
  ok($($children[2]).attr('class') === 'quotation_mark_inverted', 'Css class 3rd child node is correct');
  ok($children.last().attr('class') === 'signature', 'Css class 4th child node is correct');
});

test('Create slide', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  TestimonialSlide.prototype.createOptions();
  TestimonialSlide.prototype.createSlide();
  var $node = TestimonialSlide.prototype.$domNode;
  ok($node.prop('nodeName') === 'DIV', 'Slide node is div');
  ok($node.attr('class') === TestimonialSlide.prototype.options.cssClass, 'Css class dom node is correct');

  var $children = $node.children();
  ok($children.length === 2, '2 nodes in slide node');
  ok($children.first().attr('class') === 'quote', 'Css class first child node is correct');
  ok($children.last().attr('class') === 'author_foto', 'Css class last child node is correct');
});
<|endoftext|>


<commit_before>var fs = require("fs");
var util = require('util');
var EOL = require('os').EOL;
var log = "";

module.exports.toString = toString;
module.exports.debug = debug;
module.exports.info = info;
module.exports.warn = warn;
module.exports.error = error;
module.exports.err = error;
module.exports.fatal = fatal;
module.exports.print = print;
module.exports.write = write;
module.exports.start = start;
module.exports.prompt = prompt;
module.exports.clear = clear;
module.exports.green = green;
module.exports.white = white;

function toString()
{
    return log;
}

function debug(message) {
    message = util.format(message);
    writeCon(colorWhite, "[DEBUG] " + message);
    writeLog("[DEBUG][" + getTimeString() + "] " + message);
};

function info(message) {
    message = util.format(message);
    writeCon(colorWhite + colorBright, "[INFO ] " + message);
    writeLog("[INFO ][" + getTimeString() + "] " + message);
};

function warn(message) {
    message = util.format(message);
    writeCon(colorYellow + colorBright, "[WARN ] " + message);
    writeLog("[WARN ][" + getTimeString() + "] " + message);
};

function error(message) {
    message = util.format(message);
    writeCon(colorRed + colorBright, "[ERROR] " + message);
    writeLog("[ERROR][" + getTimeString() + "] " + message);
};

function fatal(message) {
    message = util.format(message);
    writeCon(colorRed + colorBright, "[FATAL] " + message);
    writeLog("[FATAL][" + getTimeString() + "] " + message);
};

function print(message) {
    message = util.format(message);
    writeCon(colorWhite, message);
    writeLog("[NONE ][" + getTimeString() + "] " + message);
};

function write(message) {
    message = util.format(message);
    writeLog("[NONE ][" + getTimeString() + "] " + message);
};

function green(message) {
    message = util.format(message);
    writeCon(colorGreen + colorBright, message);
};

function white(message) {
    message = util.format(message);
    writeCon(colorWhite + colorBright, message);
};

function getDateTimeString() {
    var date = new Date();
    var dy = date.getFullYear();
    var dm = date.getMonth();
    var dd = date.getDay();
    var th = date.getHours();
    var tm = date.getMinutes();
    var ts = date.getSeconds();
    var tz = date.getMilliseconds();
    dy = ("0000" + dy).slice(-4);
    dm = ("00" + dm).slice(-2);
    dd = ("00" + dd).slice(-2);
    th = ("00" + th).slice(-2);
    tm = ("00" + tm).slice(-2);
    ts = ("00" + ts).slice(-2);
    tz = ("000" + tz).slice(-3);
    return dy + "-" + dm + "-" + dd + "T" + th + "-" + tm + "-" + ts + "-" + tz;
};

function getTimeString() {
    var date = new Date();
    var th = date.getHours();
    var tm = date.getMinutes();
    var ts = date.getSeconds();
    th = ("00" + th).slice(-2);
    tm = ("00" + tm).slice(-2);
    ts = ("00" + ts).slice(-2);
    return th + "-" + tm + "-" + ts;
};

function prompt(callback)
{
    rl.setPrompt("# ");
    rl.question('# ', callback);
}

function clear()
{
    log = "";
    process.stdout.write('\033c');
    readline.cursorTo(process.stdout, 0);
    process.stdout.write("\r\x1b[K");
    readline.clearLine(process.stdout, 0);
    log = "";
}

function writeCon(color, message) {
    log += message + "\u001B[0m" + EOL;
    readline.cursorTo(process.stdout, 0);
    process.stdout.write(color + message + "\u001B[0m" + EOL);
    rl.prompt(true);
};

function writeLog(message) {
    //Do nothing!!! lmao xd
};

function start() {
    if (consoleLog != null)
        return;
    var timeString = getDateTimeString();
    var fileName = logFolder + "/" + logFileName + ".log";
    var fileName2 = logBackupFolder + "/" + logFileName + "-" + timeString + ".log";
    console.log = function (message) { print(message); };
}

var logFolder = "./logs";
var logBackupFolder = "./logs/LogBackup";
var logFileName = "xQube";

var consoleLog = null;
var colorBlack = "\u001B[30m";
var colorRed = "\u001B[31m";
var colorGreen = "\u001B[32m";
var colorYellow = "\u001B[33m";
var colorBlue = "\u001B[34m";
var colorMagenta = "\u001B[35m";
var colorCyan = "\u001B[36m";
var colorWhite = "\u001B[37m";
var colorBright = "\u001B[1m";
<commit_msg>Change octal literal formatting?<commit_after>var fs = require("fs");
var util = require('util');
var EOL = require('os').EOL;
var log = "";

module.exports.toString = toString;
module.exports.debug = debug;
module.exports.info = info;
module.exports.warn = warn;
module.exports.error = error;
module.exports.err = error;
module.exports.fatal = fatal;
module.exports.print = print;
module.exports.write = write;
module.exports.start = start;
module.exports.prompt = prompt;
module.exports.clear = clear;
module.exports.green = green;
module.exports.white = white;

function toString()
{
    return log;
}

function debug(message) {
    message = util.format(message);
    writeCon(colorWhite, "[DEBUG] " + message);
    writeLog("[DEBUG][" + getTimeString() + "] " + message);
};

function info(message) {
    message = util.format(message);
    writeCon(colorWhite + colorBright, "[INFO ] " + message);
    writeLog("[INFO ][" + getTimeString() + "] " + message);
};

function warn(message) {
    message = util.format(message);
    writeCon(colorYellow + colorBright, "[WARN ] " + message);
    writeLog("[WARN ][" + getTimeString() + "] " + message);
};

function error(message) {
    message = util.format(message);
    writeCon(colorRed + colorBright, "[ERROR] " + message);
    writeLog("[ERROR][" + getTimeString() + "] " + message);
};

function fatal(message) {
    message = util.format(message);
    writeCon(colorRed + colorBright, "[FATAL] " + message);
    writeLog("[FATAL][" + getTimeString() + "] " + message);
};

function print(message) {
    message = util.format(message);
    writeCon(colorWhite, message);
    writeLog("[NONE ][" + getTimeString() + "] " + message);
};

function write(message) {
    message = util.format(message);
    writeLog("[NONE ][" + getTimeString() + "] " + message);
};

function green(message) {
    message = util.format(message);
    writeCon(colorGreen + colorBright, message);
};

function white(message) {
    message = util.format(message);
    writeCon(colorWhite + colorBright, message);
};

function getDateTimeString() {
    var date = new Date();
    var dy = date.getFullYear();
    var dm = date.getMonth();
    var dd = date.getDay();
    var th = date.getHours();
    var tm = date.getMinutes();
    var ts = date.getSeconds();
    var tz = date.getMilliseconds();
    dy = ("0000" + dy).slice(-4);
    dm = ("00" + dm).slice(-2);
    dd = ("00" + dd).slice(-2);
    th = ("00" + th).slice(-2);
    tm = ("00" + tm).slice(-2);
    ts = ("00" + ts).slice(-2);
    tz = ("000" + tz).slice(-3);
    return dy + "-" + dm + "-" + dd + "T" + th + "-" + tm + "-" + ts + "-" + tz;
};

function getTimeString() {
    var date = new Date();
    var th = date.getHours();
    var tm = date.getMinutes();
    var ts = date.getSeconds();
    th = ("00" + th).slice(-2);
    tm = ("00" + tm).slice(-2);
    ts = ("00" + ts).slice(-2);
    return th + "-" + tm + "-" + ts;
};

function prompt(callback)
{
    rl.setPrompt("# ");
    rl.question('# ', callback);
}

function clear()
{
    log = "";
    process.stdout.write("\033c");
    readline.cursorTo(process.stdout, 0);
    process.stdout.write("\r\x1b[K");
    readline.clearLine(process.stdout, 0);
    log = "";
}

function writeCon(color, message) {
    log += message + "\u001B[0m" + EOL;
    readline.cursorTo(process.stdout, 0);
    process.stdout.write(color + message + "\u001B[0m" + EOL);
    rl.prompt(true);
};

function writeLog(message) {
    //Do nothing!!! lmao xd
};

function start() {
    if (consoleLog != null)
        return;
    var timeString = getDateTimeString();
    var fileName = logFolder + "/" + logFileName + ".log";
    var fileName2 = logBackupFolder + "/" + logFileName + "-" + timeString + ".log";
    console.log = function (message) { print(message); };
}

var logFolder = "./logs";
var logBackupFolder = "./logs/LogBackup";
var logFileName = "xQube";

var consoleLog = null;
var colorBlack = "\u001B[30m";
var colorRed = "\u001B[31m";
var colorGreen = "\u001B[32m";
var colorYellow = "\u001B[33m";
var colorBlue = "\u001B[34m";
var colorMagenta = "\u001B[35m";
var colorCyan = "\u001B[36m";
var colorWhite = "\u001B[37m";
var colorBright = "\u001B[1m";
<|endoftext|>


<commit_before>define(["widgetjs/htmlCanvas", "jquery", "chai"], function(htmlCanvas, jQuery, chai) {

    var assert = chai.assert;

    // Helper

    var withCanvas = function(callback) {
        $("BODY").append("

");
        var sandbox = jQuery('#sandbox');

        var html = htmlCanvas(sandbox);
        callback(html);

        sandbox.remove();
    };

    suite("htmlCanvas");

    test("htmlCanvas library", function() {
        assert.ok(htmlCanvas, "exported correcly.");
    });

    test("can be created on a jQuery", function() {
        // Arrange: a canvas on BODY
        var html = htmlCanvas("BODY");

        // Assert that:
        assert.ok(html, 'canvas was created');
        assert.ok(html.root, 'have a root');
        assert.ok(html.root.element(), 'have an element');
        assert.ok($("BODY").is(html.root.element()), 'element is BODY.');
    });

    test("throws exception if jQuery dont match element", function() {
        assert.throws(
            function() { htmlCanvas("#notfound"); },
            Error,
            'jQuery did not match an element',
            'throws exception if no matching element'
        );
    });

    test("can render HTML tags", function() {
        withCanvas(function(html) {
            // Arrange: a Hello World! H1
            html.h1('Hello World!');

            // Assert: that H1 was rendered
            var h1El = jQuery("#sandbox > H1");
            assert.ok(h1El.get(0), 'element rendered');

            // and class was set
            assert.equal(h1El.text(), 'Hello World!', 'text rendered');
        });
    });

    test("standard attributes are supported", function() {
        withCanvas(function(html) {
            // Arrange: a Google link
            html.a('Google').id('test_id').href('http://www.google.se');

            // Assert: that A was rendered
            var linkEl = jQuery("#test_id");
            assert.ok(linkEl.get(0), 'element rendered');

            // and href was set
            assert.equal(linkEl.attr('href'), 'http://www.google.se', 'href attribute rendered');
        });
    });

    test("render object literal attributes", function() {
        withCanvas(function(html) {
            // Arrange: a div with attributes
            html.div({id: 'test_div', klass : 'test_class', 'special_attribute' : 'test'}, 'content');

            // Assert: that DIV was rendered
            var divEl = jQuery("#test_div");
            assert.ok(divEl.get(0), 'element rendered');

            // and class was set
            assert.equal(divEl.attr('class'), 'test_class', 'attribute class rendered');

            // and class was set
            assert.equal(divEl.attr('special_attribute'), 'test', 'attribute special_attribute rendered');
        });
    });

    test("callbacks can be attached to events", function() {
        withCanvas(function(html) {
            var clicked = false;

            // Arrange: a link with a click callback
            html.a('Click me!').id('test_link').click(function() { clicked = true; });

            // Assert: that link was rendered
            var linkEl = jQuery("#test_link");
            assert.ok(linkEl.get(0), 'element rendered');

            // and click triggers callback
            linkEl.click(); // execute click
            assert.equal(clicked, true, 'click callback executed');
        });
    });

    test("tags can be nested", function() {
        withCanvas(function(html) {
            // Arrange: a inner and outer div with a span as inner child
            html.div({'id' : 'outer_div'},
                html.div({'id' : 'inner_div'},
                    html.span('Some text')
                )
            );

            // Assert: that outer div rendered
            assert.ok(jQuery("#outer_div").get(0), 'outer div rendered');
            assert.ok(jQuery("#inner_div").get(0), 'inner div rendered');
            assert.ok(jQuery("#inner_div > SPAN").get(0), 'inner SPAN rendered');
        });
    });

    test("parts can be assigned to variables", function() {
        withCanvas(function(html) {
            // Arrange a button, assign to variable and then set class
            var button = html.a('Home').id('test_button').href('/');
            button.addClass('button');

            // Assert:
            assert.ok(jQuery("#test_button").get(0), 'button rendered');
            assert.equal(jQuery('#test_button').attr('class'), 'button', 'attribute class rendered');
        });
    });

    test("render() can append objects to brush", function() {
        withCanvas(function(html) {
            // Arrange: a DIV
            var div = html.div().id('aDiv');

            // Act: render a SPAN in it
            div.render(html.span('test').addClass('aSpan'));

            // Assert:
            assert.ok(jQuery("#aDiv > .aSpan").get(0), 'SPAN rendered inside DIV');
        });
    });

    test("can render arrays", function() {
        withCanvas(function(html) {
            // Arrange a div with10 sub span supplied to DIV as an array
            var div = html.div($.map([1,2,3,4,5,6,7,8,9,10], function(num) {
                return html.span(num.toString());
            })).id('test_div');

            // Assert:
            assert.equal(jQuery("#test_div > SPAN").length, 10, 'div rendered with children from array');

        });
    });

    test("throws error if object to append is null or undefined", function () {
        withCanvas(function(html) {
            assert.throws(
                function() { html.render(null); },
                Error,
                'cannot append null or undefined to brush',
                'throws error if null'
            );
            assert.throws(
                function() { html.render(undefined); },
                Error,
                'cannot append null or undefined to brush',
                'throws error if undefined'
            );
        });
    });

    test("can render with html function", function() {
        withCanvas(function(html) {
            // Arrange a function that take a canvas as argument.
            var htmlFn = function(html2) {
                html2.span('Test').addClass('aSpan');
            };

            // and render a DIV with function as argument
            html.div({id : 'aDiv'}, htmlFn);

            // Assert
            assert.ok(jQuery("#aDiv").get(0), 'div was rendered');
            assert.ok(jQuery("#aDiv > .aSpan").get(0), 'child div from function was rendered inside div');
        });
    });

    test("delegates rendering to objects implementing appendToBrush()", function() {
        withCanvas(function(html) {
            var appendableObject = function() {
                var that = {};

                that.appendToBrush = function(aTagBrush) {
                    aTagBrush.render('
content
');
                };

                return that;
            };

            // Act: render object
            html.render(appendableObject());

            // Assert
            assert.ok(jQuery("#aDiv").get(0), 'div was rendered');
        });
    });

    test("delegates rendering to widgets implementing appendToBrush()", function() {
        withCanvas(function(html) {
            // Arrange simplest possible widget that
            // implements 'appendToBrush()' and renders a DIV
            var simpleWidget = function() {
                var that = {};

                that.renderOn = function(html2) {
                    html2.div('Test').id('aDiv');
                };

                that.appendToBrush = function(aTagBrush) {
                    that.renderOn(htmlCanvas(aTagBrush.asJQuery()));
                };

                return that;
            };

            // Act: render widget
            html.render(simpleWidget());

            // Assert
            assert.ok(jQuery("#aDiv").get(0), 'div was rendered');
        });
    });

    test("element() returns brush element", function() {
        withCanvas(function(html) {
            // Arrange: a heading
            var h1 = html.h1().id('aHeading');

            // Assert
            assert.equal(h1.element(), jQuery("#aHeading").get(0), 'element acessor returns correct element.');
        });
    });

    test("setAttribute() get/set style using key/value", function () {
        withCanvas(function(html) {
            // Arrange: a heading with id
            var h1 = html.h1().setAttribute('id', 'aHeading');

            // Assert: id set
            assert.equal(h1.asJQuery().attr('id'), ('aHeading'), 'attribute set');
        });
    });

    test("css() get/set style", function () {
        withCanvas(function(html) {
            // Arrange: a div
            var div = html.div();

            div.css('width', '100px');
            assert.equal(div.asJQuery().css('width'), '100px');
        });
    });

    test("attr() get/set style", function () {
        withCanvas(function(html) {
            // Arrange: a heading with id (set using map)
            var h1 = html.h1().attr({id : 'aHeading'});

            // Assert: that id is set
            assert.equal(h1.asJQuery().attr("id"), 'aHeading', 'attribute set');
        });
    });

    test("addClass()/removeClass() add/remove class", function () {
        withCanvas(function(html) {
            // Arrange: a heading
            var h1 = html.h1().id('aHeading');

            // addClass()
            h1.addClass('foo');
            assert.ok(h1.asJQuery().hasClass('foo'));

            // removeClass()
            h1.removeClass('foo');
            assert.ok(!h1.asJQuery().hasClass('foo'));
        });
    });

    test("asJQuery() returns jQuery that match brush element", function() {
        withCanvas(function(html) {
            // Arrange: a heading
            var h1 = html.h1().id('aHeading');

            // Assert
            assert.equal(h1.asJQuery().get(0), jQuery("#aHeading").get(0), 'asJQuery() acessor returns hquery that match element.');
        });
    });

    //TODO: allow or throw exception?
    test("can render almost everything", function () {
        withCanvas(function(html) {
            html.render(0); // toString()
            html.render(3.14159265359); // toString()
            html.render('
test
'); // => DIV element
            html.render(true); // => nothing
            html.render(false); // => nothing
            html.render({}); // as attributes but since it have no keys => nothing
            html.render([]); // as array but since empty => nothing

            assert.ok(true);
        });
    });
});
<commit_msg>Adds tests for string escaping<commit_after>define(["widgetjs/htmlCanvas", "jquery", "chai"], function(htmlCanvas, jQuery, chai) {

    var assert = chai.assert;

    // Helper

    var withCanvas = function(callback) {
        $("BODY").append("

");
        var sandbox = jQuery('#sandbox');

        var html = htmlCanvas(sandbox);
        callback(html);

        sandbox.remove();
    };

    suite("htmlCanvas");

    test("htmlCanvas library", function() {
        assert.ok(htmlCanvas, "exported correcly.");
    });

    test("can be created on a jQuery", function() {
        // Arrange: a canvas on BODY
        var html = htmlCanvas("BODY");

        // Assert that:
        assert.ok(html, 'canvas was created');
        assert.ok(html.root, 'have a root');
        assert.ok(html.root.element(), 'have an element');
        assert.ok($("BODY").is(html.root.element()), 'element is BODY.');
    });

    test("throws exception if jQuery dont match element", function() {
        assert.throws(
            function() { htmlCanvas("#notfound"); },
            Error,
            'jQuery did not match an element',
            'throws exception if no matching element'
        );
    });

    test("can render HTML tags", function() {
        withCanvas(function(html) {
            // Arrange: a Hello World! H1
            html.h1('Hello World!');

            // Assert: that H1 was rendered
            var h1El = jQuery("#sandbox > H1");
            assert.ok(h1El.get(0), 'element rendered');

            // and class was set
            assert.equal(h1El.text(), 'Hello World!', 'text rendered');
        });
    });

    test("standard attributes are supported", function() {
        withCanvas(function(html) {
            // Arrange: a Google link
            html.a('Google').id('test_id').href('http://www.google.se');

            // Assert: that A was rendered
            var linkEl = jQuery("#test_id");
            assert.ok(linkEl.get(0), 'element rendered');

            // and href was set
            assert.equal(linkEl.attr('href'), 'http://www.google.se', 'href attribute rendered');
        });
    });

    test("render object literal attributes", function() {
        withCanvas(function(html) {
            // Arrange: a div with attributes
            html.div({id: 'test_div', klass : 'test_class', 'special_attribute' : 'test'}, 'content');

            // Assert: that DIV was rendered
            var divEl = jQuery("#test_div");
            assert.ok(divEl.get(0), 'element rendered');

            // and class was set
            assert.equal(divEl.attr('class'), 'test_class', 'attribute class rendered');

            // and class was set
            assert.equal(divEl.attr('special_attribute'), 'test', 'attribute special_attribute rendered');
        });
    });

    test("callbacks can be attached to events", function() {
        withCanvas(function(html) {
            var clicked = false;

            // Arrange: a link with a click callback
            html.a('Click me!').id('test_link').click(function() { clicked = true; });

            // Assert: that link was rendered
            var linkEl = jQuery("#test_link");
            assert.ok(linkEl.get(0), 'element rendered');

            // and click triggers callback
            linkEl.click(); // execute click
            assert.equal(clicked, true, 'click callback executed');
        });
    });

    test("tags can be nested", function() {
        withCanvas(function(html) {
            // Arrange: a inner and outer div with a span as inner child
            html.div({'id' : 'outer_div'},
                html.div({'id' : 'inner_div'},
                    html.span('Some text')
                )
            );

            // Assert: that outer div rendered
            assert.ok(jQuery("#outer_div").get(0), 'outer div rendered');
            assert.ok(jQuery("#inner_div").get(0), 'inner div rendered');
            assert.ok(jQuery("#inner_div > SPAN").get(0), 'inner SPAN rendered');
        });
    });

    test("parts can be assigned to variables", function() {
        withCanvas(function(html) {
            // Arrange a button, assign to variable and then set class
            var button = html.a('Home').id('test_button').href('/');
            button.addClass('button');

            // Assert:
            assert.ok(jQuery("#test_button").get(0), 'button rendered');
            assert.equal(jQuery('#test_button').attr('class'), 'button', 'attribute class rendered');
        });
    });

    test("render() can append objects to brush", function() {
        withCanvas(function(html) {
            // Arrange: a DIV
            var div = html.div().id('aDiv');

            // Act: render a SPAN in it
            div.render(html.span('test').addClass('aSpan'));

            // Assert:
            assert.ok(jQuery("#aDiv > .aSpan").get(0), 'SPAN rendered inside DIV');
        });
    });

    test("can render arrays", function() {
        withCanvas(function(html) {
            // Arrange a div with10 sub span supplied to DIV as an array
            var div = html.div($.map([1,2,3,4,5,6,7,8,9,10], function(num) {
                return html.span(num.toString());
            })).id('test_div');

            // Assert:
            assert.equal(jQuery("#test_div > SPAN").length, 10, 'div rendered with children from array');

        });
    });

    test("throws error if object to append is null or undefined", function () {
        withCanvas(function(html) {
            assert.throws(
                function() { html.render(null); },
                Error,
                'cannot append null or undefined to brush',
                'throws error if null'
            );
            assert.throws(
                function() { html.render(undefined); },
                Error,
                'cannot append null or undefined to brush',
                'throws error if undefined'
            );
        });
    });

    test("can render with html function", function() {
        withCanvas(function(html) {
            // Arrange a function that take a canvas as argument.
            var htmlFn = function(html2) {
                html2.span('Test').addClass('aSpan');
            };

            // and render a DIV with function as argument
            html.div({id : 'aDiv'}, htmlFn);

            // Assert
            assert.ok(jQuery("#aDiv").get(0), 'div was rendered');
            assert.ok(jQuery("#aDiv > .aSpan").get(0), 'child div from function was rendered inside div');
        });
    });

    test("delegates rendering to objects implementing appendToBrush()", function() {
        withCanvas(function(html) {
            var appendableObject = function() {
                var that = {};

                that.appendToBrush = function(aTagBrush) {
                    aTagBrush.render('content');
                };

                return that;
            };

            // Act: render object
            html.render(appendableObject());

            // Assert
            assert.equal(jQuery("#sandbox").html(), 'content',  'div was rendered');
        });
    });

    test("delegates rendering to objects implementing appendToBrush()", function() {
        withCanvas(function(html) {
            var appendableObject = function() {
                var that = {};

                that.appendToBrush = function(aTagBrush) {
                    aTagBrush.render('content');
                };

                return that;
            };

            // Act: render object
            html.render(appendableObject());

            // Assert
            assert.equal(jQuery("#sandbox").html(), 'content',  'div was rendered');
        });
    });

    test("rendering html strings not allowed by default", function() {
        withCanvas(function(html) {
			// Arrange:
			var htmlString = '
foo
';

            // Act: render the string
			var result = html.render(htmlString);

            // Assert
            assert.notOk(jQuery("#unescaped").get(0), 'div was not injected');
		});
    });

    test("rendering of strings is escaped ", function() {
        withCanvas(function(html) {
			// Arrange:
			var htmlString = '<>&foo';

            // Act: render the string
			var result = html.render(htmlString);

            // Assert
            assert.equal(jQuery("#sandbox").html(), '<>&foo', 'content was escaped');
		});
    });

    test("rendering using `html()` does not escape ", function() {
        withCanvas(function(html) {
			// Arrange:
			var htmlString = '
hello
';

            // Act: render the string
			var result = html.div({id: 'not-escaped'}).html(htmlString);

            // Assert
            assert.equal(jQuery("#not-escaped").html(), htmlString, 'content was not escaped');
		});
    });

    test("element() returns brush element", function() {
        withCanvas(function(html) {
            // Arrange: a heading
            var h1 = html.h1().id('aHeading');

            // Assert
            assert.equal(h1.element(), jQuery("#aHeading").get(0), 'element acessor returns correct element.');
        });
    });

    test("setAttribute() get/set style using key/value", function () {
        withCanvas(function(html) {
            // Arrange: a heading with id
            var h1 = html.h1().setAttribute('id', 'aHeading');

            // Assert: id set
            assert.equal(h1.asJQuery().attr('id'), ('aHeading'), 'attribute set');
        });
    });

    test("css() get/set style", function () {
        withCanvas(function(html) {
            // Arrange: a div
            var div = html.div();

            div.css('width', '100px');
            assert.equal(div.asJQuery().css('width'), '100px');
        });
    });

    test("attr() get/set style", function () {
        withCanvas(function(html) {
            // Arrange: a heading with id (set using map)
            var h1 = html.h1().attr({id : 'aHeading'});

            // Assert: that id is set
            assert.equal(h1.asJQuery().attr("id"), 'aHeading', 'attribute set');
        });
    });

    test("addClass()/removeClass() add/remove class", function () {
        withCanvas(function(html) {
            // Arrange: a heading
            var h1 = html.h1().id('aHeading');

            // addClass()
            h1.addClass('foo');
            assert.ok(h1.asJQuery().hasClass('foo'));

            // removeClass()
            h1.removeClass('foo');
            assert.ok(!h1.asJQuery().hasClass('foo'));
        });
    });

    test("asJQuery() returns jQuery that match brush element", function() {
        withCanvas(function(html) {
            // Arrange: a heading
            var h1 = html.h1().id('aHeading');

            // Assert
            assert.equal(h1.asJQuery().get(0), jQuery("#aHeading").get(0), 'asJQuery() acessor returns hquery that match element.');
        });
    });

    //TODO: allow or throw exception?
    test("can render almost everything", function () {
        withCanvas(function(html) {
            html.render(0); // toString()
            html.render(3.14159265359); // toString()
            html.render('
test
'); // => DIV element
            html.render(true); // => nothing
            html.render(false); // => nothing
            html.render({}); // as attributes but since it have no keys => nothing
            html.render([]); // as array but since empty => nothing

            assert.ok(true);
        });
    });
});
<|endoftext|>


<commit_before>Travis.Views.Repository.Show = Backbone.View.extend({
  tabs: {},
  initialize: function() {
    _.extend(this, this.options);
    _.bindAll(this, 'repositorySelected', '_createTab', '_renderTab', '_activateTab');

    this.template = Travis.templates['repository/show'];
    _.each(['current', 'history', 'build'], this._createTab);
  },
  render: function() {
    this.el = $(this.template({}));
    _.each(this.tabs, this._renderTab);
    return this;
  },
  detach: function() {
    if(this.collection) {
      this.collection.unbind('select', this.repositorySelected);
    }
  },
  attachTo: function(collection) {
    this.detach();
    this.collection = collection;
    this.collection.bind('select', this.repositorySelected);
  },
  repositorySelected: function(repository) {
    this.repository = repository;
    this._setTitle();
    _.each(this.tabs, function(tab) { tab.attachTo(repository); }.bind(this));
  },
  activateTab: function(name) {
    _.each(this.tabs, function(tab) { if(tab.name != name) tab.deactivate(); })
    this.tabs[name].activate();
  },
  _createTab: function(name) {
    this.tabs[name] = new Travis.Views.Repository.Tab({ name: name });
  },
  _renderTab: function(tab) {
    this.el.find('.tabs').append(tab.render().el);
  },
  _setTitle: function() {
    this.el.find('h3 a').attr('href', 'http://github.com/' + this.repository.get('slug')).text(this.repository.get('slug'));
    this.el.updateGithubStats(this.repository);
  }
});
<commit_msg>Adding link to Repository from Build.<commit_after>Travis.Views.Repository.Show = Backbone.View.extend({
  tabs: {},
  initialize: function() {
    _.extend(this, this.options);
    _.bindAll(this, 'repositorySelected', '_createTab', '_renderTab', '_activateTab');

    this.template = Travis.templates['repository/show'];
    _.each(['current', 'history', 'build'], this._createTab);
  },
  render: function() {
    this.el = $(this.template({}));
    _.each(this.tabs, this._renderTab);
    return this;
  },
  detach: function() {
    if(this.collection) {
      this.collection.unbind('select', this.repositorySelected);
    }
  },
  attachTo: function(collection) {
    this.detach();
    this.collection = collection;
    this.collection.bind('select', this.repositorySelected);
  },
  repositorySelected: function(repository) {
    this.repository = repository;
    this._setTitle();
    _.each(this.tabs, function(tab) {
      tab.attachTo(repository);
    }.bind(this));
  },
  activateTab: function(name) {
    _.each(this.tabs, function(tab) { if(tab.name != name) tab.deactivate(); })
    this.tabs[name].activate();
  },
  _createTab: function(name) {
     this.tabs[name] = new Travis.Views.Repository.Tab({ name: name, parent: this  });
  },
  _renderTab: function(tab) {
    this.el.find('.tabs').append(tab.render().el);
  },
  _setTitle: function() {
    this.el.find('h3 a').attr('href', 'http://github.com/' + this.repository.get('slug')).text(this.repository.get('slug'));
    this.el.updateGithubStats(this.repository);
  }
});
<|endoftext|>


<commit_before>angular.module('TemaNode', [
    "TemaService",
    "TemaHelperModule",
    "TemaService"
])

.controller('TemaLayoutController', function($scope) {
    console.info("[TemaLayoutController]");
    //window.history.pushState({}, "Contacto","Contacto");
    $("title").html("Tema | Clarity");
})

.controller('TemaItemsController', function($scope, $rootScope, Tema, $timeout) {
    console.info("[TemaItemsController]");
    Tema.query({
        pageNumber: 1,
        itemsPerPage: 100
    }, function(res) { //res -> data (page)
        $scope.items = res.data.Items;
    });
})

.controller('TemaCreateController', function($scope, $state, $rootScope, Tema, TemaHelper, $timeout) {
    console.info("[TemaCreateController]");
    $scope.trysave = function() {
        console.info("[TemaCreateController][" + "trysave" + "]");
        $('.ui.form').form('validate form');
    }
    $scope.save = function() {
        console.info("[TemaCreateController][" + "validaciones ok" + "]");

        //CABLEADO: POR AHORA
        $scope.item.GrupoID = 1;

        Tema.save({}, $scope.item, function(data) {
            $state.go("clarity.tema.list");
            console.info("[TemaCreateController][" + "save success" + "]");
        }, function(data) {
            $state.go("clarity.tema.list");
            console.info("[TemaCreateController][" + "save failure" + "]");
        });

    }
    //
    TemaHelper.FormValidationDefinition($scope.save, null);
})

.controller('TemaEditController', function($scope, $state, $rootScope, Tema, TemaHelper, $timeout) {
    console.info("[TemaEditController]");
    $scope.trysave = function() {
        console.info("[TemaEditController][" + "trysave" + "]");
        $('.ui.form').form('validate form');
    }
    $scope.save = function() {
        console.info("[TemaEditController][" + "validaciones ok" + "]");
        Tema.save({}, $scope.item, function(data) {
            $state.go("clarity.tema.list");
            console.info("[TemaEditController][" + "save success" + "]");
        }, function(data) {
            $state.go("clarity.tema.list");
            console.info("[TemaEditController][" + "save failure" + "]");
        });
    }
    $scope.delete = function() {
        console.info("[TemaEditController][" + "delete?" + "]");
        if (confirm("Borrar?")) {
            Tema.delete({
                id: $scope.item.TemaID
            }, {}, function() {
                console.info("[TemaEditController][" + "delete success" + "]");
                $state.go("clarity.tema.list");
            }, function() {
                console.info("[TemaEditController][" + "delete failure" + "]");
                $state.go("clarity.tema.list");
            });
        }
    }
    //
    TemaHelper.FormValidationDefinition($scope.save, null);
    Tema.get({
        id: $state.params.id
    }, function(res) {
        console.log(res);
        $scope.item = res.data;
    });
});

angular.module("TemaHelperModule", []).factory("TemaHelper", [

    function() {
        return {
            FormValidationDefinition: function(onSuccess, onFailure) {
                $('.ui.form')
                    .form({
                        asunto: {
                            description: 'description',
                            rules: [{
                                type: 'empty',
                                prompt: 'Desripcion requerida'
                            }]
                        }
                    }, {
                        onSuccess: onSuccess,
                        onFailure: onFailure
                    });
            }
        }
    }
]);

angular.module('TemaService', ['ngResource']).
factory('Tema', ['$resource', 'AppConfig',
    function($resource, AppConfig) {
        return $resource(AppConfig.apiClarity + 'tema/:action/:id', {}, {
            query: {
                method: "GET",
                isArray: false,
                params: {
                    action: "get"
                }
            },
            get: {
                method: "GET",
                isArray: false,
                params: {
                    action: "get"
                }
            },
            update: {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                params: {
                    action: "post"
                }
            },
            delete: {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                params: {
                    action: "DELETE"
                }
            },
            save: {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                params: {
                    action: "post"

                }
            }
        });
    }
]);<commit_msg>Tema: Añadido warning de elemento relacionado al eliminar<commit_after>angular.module('TemaNode', [
    "TemaService",
    "TemaHelperModule",
    "TemaService"
])

.controller('TemaLayoutController', function($scope) {
    console.info("[TemaLayoutController]");
    //window.history.pushState({}, "Contacto","Contacto");
    $("title").html("Tema | Clarity");
})

.controller('TemaItemsController', function($scope, $rootScope, Tema, $timeout) {
    console.info("[TemaItemsController]");
    Tema.query({
        pageNumber: 1,
        itemsPerPage: 100
    }, function(res) { //res -> data (page)
        $scope.items = res.data.Items;
    });
})

.controller('TemaCreateController', function($scope, $state, $rootScope, Tema, TemaHelper, $timeout) {
    console.info("[TemaCreateController]");
    $scope.trysave = function() {
        console.info("[TemaCreateController][" + "trysave" + "]");
        $('.ui.form').form('validate form');
    }
    $scope.save = function() {
        console.info("[TemaCreateController][" + "validaciones ok" + "]");

        //CABLEADO: POR AHORA
        $scope.item.GrupoID = 1;

        Tema.save({}, $scope.item, function(data) {
            $state.go("clarity.tema.list");
            console.info("[TemaCreateController][" + "save success" + "]");
        }, function(data) {
            $state.go("clarity.tema.list");
            console.info("[TemaCreateController][" + "save failure" + "]");
        });

    }
    //
    TemaHelper.FormValidationDefinition($scope.save, null);
})

.controller('TemaEditController', function($scope, $state, $rootScope, Tema, TemaHelper, $timeout) {
    console.info("[TemaEditController]");
    $scope.trysave = function() {
        console.info("[TemaEditController][" + "trysave" + "]");
        $('.ui.form').form('validate form');
    }
    $scope.save = function() {
        console.info("[TemaEditController][" + "validaciones ok" + "]");
        Tema.save({}, $scope.item, function(data) {
            $state.go("clarity.tema.list");
            console.info("[TemaEditController][" + "save success" + "]");
        }, function(data) {
            $state.go("clarity.tema.list");
            console.info("[TemaEditController][" + "save failure" + "]");
        });
    }
    $scope.delete = function() {
        console.info("[TemaEditController][" + "delete?" + "]");
        if (confirm("Borrar?")) {
            Tema.delete({
                id: $scope.item.TemaID
            }, {}, function(data) {

                if(data.ok){
                    console.info("[TemaEditController][" + "delete success" + "]");
                    $state.go("clarity.tema.list");
                }else{
                    alert("Elementos relacionados");
                    console.info("[TemaEditController] "+data.error);
                }

            }, function() {
                console.info("[TemaEditController][" + "delete failure" + "]");
                $state.go("clarity.tema.list");
            });
        }
    }
    //
    TemaHelper.FormValidationDefinition($scope.save, null);
    Tema.get({
        id: $state.params.id
    }, function(res) {
        console.log(res);
        $scope.item = res.data;
    });
});

angular.module("TemaHelperModule", []).factory("TemaHelper", [

    function() {
        return {
            FormValidationDefinition: function(onSuccess, onFailure) {
                $('.ui.form')
                    .form({
                        asunto: {
                            description: 'description',
                            rules: [{
                                type: 'empty',
                                prompt: 'Desripcion requerida'
                            }]
                        }
                    }, {
                        onSuccess: onSuccess,
                        onFailure: onFailure
                    });
            }
        }
    }
]);

angular.module('TemaService', ['ngResource']).
factory('Tema', ['$resource', 'AppConfig',
    function($resource, AppConfig) {
        return $resource(AppConfig.apiClarity + 'tema/:action/:id', {}, {
            query: {
                method: "GET",
                isArray: false,
                params: {
                    action: "get"
                }
            },
            get: {
                method: "GET",
                isArray: false,
                params: {
                    action: "get"
                }
            },
            update: {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                params: {
                    action: "post"
                }
            },
            delete: {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                params: {
                    action: "DELETE"
                }
            },
            save: {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                params: {
                    action: "post"

                }
            }
        });
    }
]);<|endoftext|>


<commit_before>/**********************************************************************************************
 *
 * toggle
 * click to  show side panel navigation menu items in main content area and
 * hide previous elements
 * @author  dmauldin
 *
 *******************************************************************************************************/
function HideAllShowOne(d) {
	console.log(d);

	var menuItem = ["home-page", "profile-page", "message-page", "feed-page", "logout-page", "edit-profile-page"];

	for(i = 0; i < menuItem.length; i++) {
		document.getElementById(menuItem[i]).style.display = "none";
	}

	if(d === 'hp') {
		document.getElementById(menuItem[0]).style.display = "inline block";
		console.log("inside hp after display set")
	} else if(d === 'pp') {
		document.getElementById(menuItem[1]).style.display = "inline block";
	} else if(d === 'mp') {
		document.getElementById(menuItem[2]).style.display = "inline block";
	} else if(d === 'fp') {
		document.getElementById(menuItem[3]).style.display = "inline block";
	} else if(d === 'lp') {
		 document.getElementById(menuItem[4]).style.display = "inline block";
	} else if(d === 'ep') {
		document.getElementById(menuItem[4]).style.display = "inline block";

 }

}

/************************************************************************************************************
 * login/registration  form
 * @author jhung@cnm.edu
 ************************************************************************************************************/

$(function() {

	$('#login-form-link').click(function(e) {
		$("#login-form").delay(100).fadeIn(100);
		$("#register-form").fadeOut(100);
		$('#register-form-link').removeClass('active');
		$(this).addClass('active');
		e.preventDefault();
	});
	$('#register-form-link').click(function(e) {
		$("#register-form").delay(100).fadeIn(100);
		$("#login-form").fadeOut(100);
		$('#login-form-link').removeClass('active');
		$(this).addClass('active');
		e.preventDefault();
	});

});

/**************************************************************
 * edit profile/settings form
 * @author jhung@cnm.edu
 **************************************************************/
$(function() {

	$('#profile-form-link').click(function(e) {
		$("#profile-form").delay(100).fadeIn(100);
		$("#edit-settings").fadeOut(100);
		$('#edit-settings-link').removeClass('active');
		$(this).addClass('active');
		e.preventDefault();
	});
	$('#edit-settings-link').click(function(e) {
		$("#edit-settings").delay(100).fadeIn(100);
		$("#profile-form").fadeOut(100);
		$('#profile-form-link').removeClass('active');
		$(this).addClass('active');
		e.preventDefault();
	});
});

/************************************************************************************************************
 * mailbox
 * @author jhung@cnm.edu
 ************************************************************************************************************/
$(function() {

	$('#compose-wrapper-link').click(function(e) {
		$("#compose-wrapper").delay(100).fadeIn(100);
		$("#inbox-wrapper").fadeOut(100);
		$('#inbox-wrapper-link').removeClass('active');
		$(this).addClass('active');
		e.preventDefault();
	});
	$('#inbox-wrapper-link').click(function(e) {
		$("#inbox-wrapper").delay(100).fadeIn(100);
		$("#compose-wrapper").fadeOut(100);
		$("#sent-wrapper").fadeOut(100);
		$('#compose-wrapper-link').removeClass('active');

		$('#sent-wrapper-link').removeClass('active');
		$(this).addClass('active');
		e.preventDefault();
	});

	$('#sent-wrapper-link').click(function(e) {
		$("#sent-wrapper").delay(100).fadeIn(100);
		$("#compose-wrapper").fadeOut(100);
		$("#inbox-wrapper").fadeOut(100);
		$('#compose-wrapper-link').removeClass('active');
		$('#inbox-wrapper-link').removeClass('active');

		$(this).addClass('active');
		e.preventDefault();
	});

});

/******
 * interfering with validation?
 */
/********
 $(function () {
        //Enable iCheck plugin for checkboxes
        //iCheck for checkbox and radio inputs
        $('.mailbox-messages input[type="checkbox"]').iCheck({
          checkboxClass: 'icheckbox_flat-blue',
          radioClass: 'iradio_flat-blue'
        });

        //Enable check and uncheck all functionality
        $(".checkbox-toggle").click(function () {
          var clicks = $(this).data('clicks');
          if (clicks) {
            //Uncheck all checkboxes
            $(".mailbox-messages input[type='checkbox']").iCheck("uncheck");
            $(".fa", this).removeClass("fa-check-square-o").addClass('fa-square-o');
          } else {
            //Check all checkboxes
            $(".mailbox-messages input[type='checkbox']").iCheck("check");
            $(".fa", this).removeClass("fa-square-o").addClass('fa-check-square-o');
          }
          $(this).data("clicks", !clicks);
        });

        //Handle starring for glyphicon and font awesome
        $(".mailbox-star").click(function (e) {
          e.preventDefault();
          //detect type
          var $this = $(this).find("a > i");
          var glyph = $this.hasClass("glyphicon" );
          var fa = $this.hasClass("fa");

          //Switch states
          if (glyph) {
            $this.toggleClass("glyphicon-star");
            $this.toggleClass("glyphicon-star-empty");
          }

          if (fa) {
            $this.toggleClass("fa-star");
            $this.toggleClass("fa-star-o");
          }
        });
      });

/*******************************************************************************
 *
 *jscroll
 *
 ********************************************************************************/
	$(document).ready(function() {
		// Infinite Ajax Scroll configuration
		jQuery.ias({
			container : '#feed-page', // main container where data goes to append
			item: '.panel-default', // single items
			loader: '', // loading gif
			triggerPageThreshold: 10 // show load more if scroll more than this
		});
	});

$('.infinite-scroll').jscroll({
	loadingHtml:  '',

		padding: 20,
	nextSelector: 'a.jscroll-next:last',
	contentSelector: '#panel-wrapper'
});

/***********
 *close feed panel-wrapper
 * ***************************/

window.onload = function(){
	document.getElementById('close').onclick = function(){
		this.parentNode.parentNode.parentNode
				.removeChild(this.parentNode.parentNode);
		return false;
	};
};

/*************************************************
 *
 * side-menu toggle
 *
 *********************************************/

<commit_msg>edited site-scripts<commit_after>/**********************************************************************************************
 *
 * toggle
 * click to  show side panel navigation menu items in main content area and
 * hide previous elements
 * @author  dmauldin
 *
 *******************************************************************************************************/
function HideAllShowOne(d) {
	console.log(d);

	var menuItem = ["home-page", "profile-page", "message-page", "feed-page", "logout-page", "edit-profile-page"];

	for(i = 0; i < menuItem.length; i++) {
		document.getElementById(menuItem[i]).style.display = "none";
	}

	if(d === 'hp') {
		document.getElementById(menuItem[0]).style.display = "inline block";
		console.log("inside hp after display set")
	} else if(d === 'pp') {
		document.getElementById(menuItem[1]).style.display = "inline block";
	} else if(d === 'mp') {
		document.getElementById(menuItem[2]).style.display = "inline block";
	} else if(d === 'fp') {
		document.getElementById(menuItem[3]).style.display = "inline block";
	} else if(d === 'lp') {
		 document.getElementById(menuItem[4]).style.display = "inline block";
	} else if(d === 'ep') {
		document.getElementById(menuItem[4]).style.display = "inline block";

 }

}

/************************************************************************************************************
 * login/registration  form
 * @author jhung@cnm.edu
 ************************************************************************************************************/

$(function() {

	$('#login-form-link').click(function(e) {
		$("#login-form").delay(100).fadeIn(100);
		$("#register-form").fadeOut(100);
		$('#register-form-link').removeClass('active');
		$(this).addClass('active');
		e.preventDefault();
	});
	$('#register-form-link').click(function(e) {
		$("#register-form").delay(100).fadeIn(100);
		$("#login-form").fadeOut(100);
		$('#login-form-link').removeClass('active');
		$(this).addClass('active');
		e.preventDefault();
	});

});

/**************************************************************
 * edit profile/settings form
 * @author jhung@cnm.edu
 **************************************************************/
$(function() {

	$('#profile-form-link').click(function(e) {
		$("#profile-form").delay(100).fadeIn(100);
		$("#edit-settings").fadeOut(100);
		$('#edit-settings-link').removeClass('active');
		$(this).addClass('active');
		e.preventDefault();
	});
	$('#edit-settings-link').click(function(e) {
		$("#edit-settings").delay(100).fadeIn(100);
		$("#profile-form").fadeOut(100);
		$('#profile-form-link').removeClass('active');
		$(this).addClass('active');
		e.preventDefault();
	});
});

/************************************************************************************************************
 * mailbox
 * @author jhung@cnm.edu
 ************************************************************************************************************/
$(function() {

	$('#compose-wrapper-link').click(function(e) {
		$("#compose-wrapper").delay(100).fadeIn(100);
		$("#inbox-wrapper").fadeOut(100);
		$('#inbox-wrapper-link').removeClass('active');
		$(this).addClass('active');
		e.preventDefault();
	});
	$('#inbox-wrapper-link').click(function(e) {
		$("#inbox-wrapper").delay(100).fadeIn(100);
		$("#compose-wrapper").fadeOut(100);
		$("#sent-wrapper").fadeOut(100);
		$('#compose-wrapper-link').removeClass('active');

		$('#sent-wrapper-link').removeClass('active');
		$(this).addClass('active');
		e.preventDefault();
	});

	$('#sent-wrapper-link').click(function(e) {
		$("#sent-wrapper").delay(100).fadeIn(100);
		$("#compose-wrapper").fadeOut(100);
		$("#inbox-wrapper").fadeOut(100);
		$('#compose-wrapper-link').removeClass('active');
		$('#inbox-wrapper-link').removeClass('active');

		$(this).addClass('active');
		e.preventDefault();
	});

});

/******
 * interfering with validation?
 */
/********
 $(function () {
        //Enable iCheck plugin for checkboxes
        //iCheck for checkbox and radio inputs
        $('.mailbox-messages input[type="checkbox"]').iCheck({
          checkboxClass: 'icheckbox_flat-blue',
          radioClass: 'iradio_flat-blue'
        });

        //Enable check and uncheck all functionality
        $(".checkbox-toggle").click(function () {
          var clicks = $(this).data('clicks');
          if (clicks) {
            //Uncheck all checkboxes
            $(".mailbox-messages input[type='checkbox']").iCheck("uncheck");
            $(".fa", this).removeClass("fa-check-square-o").addClass('fa-square-o');
          } else {
            //Check all checkboxes
            $(".mailbox-messages input[type='checkbox']").iCheck("check");
            $(".fa", this).removeClass("fa-square-o").addClass('fa-check-square-o');
          }
          $(this).data("clicks", !clicks);
        });

        //Handle starring for glyphicon and font awesome
        $(".mailbox-star").click(function (e) {
          e.preventDefault();
          //detect type
          var $this = $(this).find("a > i");
          var glyph = $this.hasClass("glyphicon" );
          var fa = $this.hasClass("fa");

          //Switch states
          if (glyph) {
            $this.toggleClass("glyphicon-star");
            $this.toggleClass("glyphicon-star-empty");
          }

          if (fa) {
            $this.toggleClass("fa-star");
            $this.toggleClass("fa-star-o");
          }
        });
      });

/*******************************************************************************
 *
 *jscroll
 *
 ********************************************************************************/
	$(document).ready(function() {
		// Infinite Ajax Scroll configuration
		jQuery.ias({
			container : '#feed-page', // main container where data goes to append
			item: '.panel-default', // single items
			loader: '', // loading gif
			triggerPageThreshold: 10 // show load more if scroll more than this
		});
	});

$('.infinite-scroll').jscroll({
	loadingHtml:  '',

		padding: 20,
	nextSelector: 'a.jscroll-next:last',
	contentSelector: '#panel-wrapper'
});

<|endoftext|>