<commit_before>/**
 * Created by candradwaskito on 11/22/15.
 */

//$(window).load(function(){
//    $("#navbar-main").sticky({ topSpacing: 0 });
//});

$("#navbar-main").sticky({ topSpacing: 0 });

$('.btn-delete').on('click', function () {
	return confirm('Anda yakin mau menghapus?');
})

$('.btn-reply').on('click', function () {
    var parent = $(this).data('parent')
    var inputp = $('input[name=parent]')

    inputp.val(parent)
})<commit_msg>Edit app.js untuk nav tab<commit_after>/**
 * Created by candradwaskito on 11/22/15.
 */

//$(window).load(function(){
//    $("#navbar-main").sticky({ topSpacing: 0 });
//});

$("#navbar-main").sticky({ topSpacing: 0 });

$('.btn-delete').on('click', function () {
	return confirm('Anda yakin mau menghapus?');
})

$('.btn-reply').on('click', function () {
    var parent = $(this).data('parent')
    var inputp = $('input[name=parent]')

    inputp.val(parent)
})

// if the tabs are in a narrow column in a larger viewport
    $('.sidebar-tabs').tabCollapse({
        tabsClass: 'visible-tabs',
        accordionClass: 'hidden-tabs'
    });

    // if the tabs are in wide columns on larger viewports
    $('.content-tabs').tabCollapse();

    // initialize tab function
    $('.nav-tabs a').click(function(e) {
        e.preventDefault();
        $(this).tab('show');
    });

    // slide to top of panel-group accordion
    $('.panel-group').on('shown.bs.collapse', function() {
        var panel = $(this).find('.in');
        $('html, body').animate({
            scrollTop: panel.offset().top + (-60)
        }, 500);
    });<|endoftext|>


<commit_before>Vue.component('camp-details', {
    props: ['campId'],
    computed: {
        campDetails: function() {
            // Since we don't yet include vue.js with NPM and webpack, we cannot use npm modules such as vue-fetch, and
            // also cannot use advanced javascript features such as async / await (which are required for the
            // fetch API). Therefore, to prove our point, we use a good old-fashioned XMLHttpRequest here to query our
            // eCamp API.
            var request = new XMLHttpRequest();
            request.open("GET", "/api/camp/" + this.campId, false);
            request.send();

            if (request.status !== 200) {
                alert('can not get camp details');
                return {};
            }

            return JSON.parse(request.responseText);
        },
        ownerName: function() {
            return this.campDetails._embedded.owner.name;
        },
        periods: function() {
            return this.campDetails._embedded.periods;
        },
    },
    template:
        '
\n' +
        '
\n' +
        '                Vue.js Infos zu genau einem Lager, id {{ campId }}\n' +
        '
\n' +
        '
Name: {{ campDetails.name }}
\n' +
        '
Titel: {{ campDetails.title }}
\n' +
        '
Motto: {{ campDetails.motto }}
\n' +
        '
Besitzer Name: {{ ownerName }}
\n' +
        '
Lager-Perioden:' +
        '

{{ period.description }} ({{ period.start }} - {{ period.end }})

' +
        '
\n' +
        '
\n' +
        '
\n' +
        '
'
});

new Vue({ el: '#camp-details' });
<commit_msg>Add edit button<commit_after>Vue.component('camp-details', {
    props: ['campId'],
    data: function() {
        return {
            editing: false,
        }
    },
    computed: {
        campDetails: function() {
            // Since we don't yet include vue.js with NPM and webpack, we cannot use npm modules such as vue-fetch, and
            // also cannot use advanced javascript features such as async / await (which are required for the
            // fetch API). Therefore, to prove our point, we use a good old-fashioned XMLHttpRequest here to query our
            // eCamp API.
            var request = new XMLHttpRequest();
            request.open("GET", "/api/camp/" + this.campId, false);
            request.send();

            if (request.status !== 200) {
                alert('can not get camp details');
                return {};
            }

            return JSON.parse(request.responseText);
        },
        ownerName: function() {
            return this.campDetails._embedded.owner.name;
        },
        periods: function() {
            return this.campDetails._embedded.periods;
        },
        buttonText: function() {
            return this.editing ? 'Speichern' : 'Bearbeiten';
        },
    },
    template:
        '
\n' +
        '
\n' +
        '                <button style="float: right" class="btn btn-sm" v-bind:class="{ \'btn-primary\': editing, \'btn-outline-primary\': !editing }" v-on:click="editing=!editing">{{ buttonText }}</button>' +
        '                Vue.js Infos zu genau einem Lager, id {{ campId }}\n' +
        '
\n' +
        '
Name: {{ campDetails.name }}
\n' +
        '
Titel: {{ campDetails.title }}
\n' +
        '
Motto: {{ campDetails.motto }}
\n' +
        '
Besitzer Name: {{ ownerName }}
\n' +
        '
Lager-Perioden:' +
        '

{{ period.description }} ({{ period.start }} - {{ period.end }})

' +
        '
\n' +
        '
\n' +
        '
\n' +
        '
'
});

new Vue({ el: '#camp-details' });
<|endoftext|>


<commit_before>// A script to open new tab/window for external links
var links = document.links;

for (var i = 0, linksLength = links.length; i < linksLength; i++) {
   if (links[i].hostname != window.location.hostname) {
       links[i].target = '_blank';
   }
}

// TODO: make this have some semblance of functionality
<commit_msg>Test SSH<commit_after>// A script to open new browser tab/window for external links
var links = document.links;

for (var i = 0, linksLength = links.length; i < linksLength; i++) {
   if (links[i].hostname != window.location.hostname) {
       links[i].target = '_blank';
   }
}

// TODO: make this have some semblance of functionality
<|endoftext|>


<commit_before>angular.module('wordasaurus', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider
  .when('/', {
    templateUrl: 'partials/home/index.html',
  })

  .when('/my_pieces', {
    templateUrl: 'partials/pieces/index.html',
  })

  .otherwise({redirectTo: '/'});
}]);

angular.module('wordasaurus')
.controller('HomeController', ['$scope', '$http', 'User' , 'Piece', function ($scope, $http, User, Piece) {
  User.current().success(function(res) {
    $scope.user = res;
    Piece.all($scope.user.id).success(function(res) {$scope.pieces = res});
  });
  $scope.createPiece = function(title, content) {
    Piece.create({
      title: title,
      content: content,
    }).success(function(payload) {
      $scope.pieces.push(payload);
      $('#new-title').val('');
      $('#new-piece').val('');
    });
  };
  $scope.setActivePiece = function(piece) {
    $scope.activePiece = piece;
    $scope.syn_json = JSON.parse(piece.syn_json);
  };
  $scope.getSyns = function(word) {
    if (!$scope.syn_json[word]) {
      console.log('getting');
      $http.get('/synonyms/'+word).success(function(res) {
        $scope.syn_json[word] = res
        $scope.saveSyns();
      });
    }
  };
  $scope.setActiveWord = function(index, word) {
    $scope.activeWord = word.toLowerCase().match(/[a-z]+/g)[0];
    $scope.activeIndex = index;
    $scope.getSyns($scope.activeWord);
  };
  $scope.embedWord = function(word) {
    // var target = $('#show-piece span:nth-child(' + ($scope.activeIndex+1) + ')')
    // target.text(target.text().replace(/[a-z\s]+/i, word));
    var pieces = $scope.activePiece.content.split(' ');
    pieces[$scope.activeIndex] = pieces[$scope.activeIndex].replace(/[a-z]+/i, word);
    $scope.activePiece.content = pieces.join(' ');
  };
  $scope.saveSyns = function() {
    $http.post('/pieces/'+$scope.activePiece.id+'/syns', {syn_json: JSON.stringify($scope.syn_json)} )
  };
  $scope.savePiece = function() {
    $http.put('/pieces/'+$scope.activePiece.id, {content: $scope.stripSpan()} ).success(function() {
      alert('Saved!');
    });
  };
  $scope.stripSpan = function() {
    return ($('#show-piece').text().match(/\S+/gi) || []).join(' ')
  };
  $scope.refreshActiveFromSyn = function() {
    $scope.activePiece.content = $scope.stripSpan();
    $('#edit-piece').val($scope.activePiece.content);
  };
  $scope.refreshActiveFromEdit = function() {
    $scope.activePiece.content = $('#edit-piece').val();
  };
  $scope.deleteActive = function() {
    $http.delete('/pieces/'+$scope.activePiece.id).success(function(id) {
      $scope.syn_json = {};
      $scope.activePiece = {};
      $scope.activeWord = '';
      for (var i = 0; i < $scope.pieces.length; i++) {
        if ($scope.pieces[i].id == id) {
          $scope.pieces.splice(i,1);
        };
      };
    });
  };
  $scope.syn_json = {};
  $scope.activePiece = {};
  $scope.activeWord = '';
}])

.factory('Piece', ['$http', function NoteFactory($http) {
  return {
    all: function(user_id) {
      return $http.get('users/'+user_id+'/pieces');
    },
    create: function(data) {
      return $http.post('/pieces', data);
    }
  };
}])

.factory('User', ['$http', function UserFactory($http) {
  return {
    current: function() {
      return $http.get('users/current');
    },
    find: function(id) {
      return $http.get('users/'+id);
    }
  };
}])

.directive('addPiece', function() {
  return {
    restrict: 'E',
    templateUrl: 'partials/directives/add-piece.html',
    link: function(scope) {
      scope.tab = 'button';
    }
  };
});

$(document).ready(function() {
  if (window.location.href.match(/session/)) {
    $('#sign-in').trigger('click');
  };
  if (window.location.href.match(/users/)) {
    document.getElementById('reg-but').click();
  };

  $(document).on('click', '.fancy span', function(e) {
    $('.fancy span').removeClass('grow');
    $(e.target).addClass('grow');
  });

  //registration form validation
  $(document).on('change', '.modal-body input', function() {
    if ($('#reg-password').val() === $('#conf-password').val() && $('#conf-password').val()) {
      $('.passw').parents('.form-group')
      .addClass('has-success')
      .removeClass('has-error');
      $('.modal-footer').find('.btn-primary').removeAttr('disabled');
    } else {
      $('.passw').parents('.form-group')
      .removeClass('has-success')
      .addClass('has-error');
      $('.modal-footer').find('.btn-primary').attr('disabled', 'disabled');
    };
  });
});
<commit_msg>scope the directive and communicate with parent<commit_after>angular.module('wordasaurus', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider
  .when('/', {
    templateUrl: 'partials/home/index.html',
  })

  .when('/my_pieces', {
    templateUrl: 'partials/pieces/index.html',
  })

  .otherwise({redirectTo: '/'});
}]);

angular.module('wordasaurus')
.controller('HomeController', ['$scope', '$http', 'User' , 'Piece', function ($scope, $http, User, Piece) {
  User.current().success(function(res) {
    $scope.user = res;
    Piece.all($scope.user.id).success(function(res) {$scope.pieces = res});
  });
  $scope.createPiece = function(title, content) {
    Piece.create({
      title: title,
      content: content,
    }).success(function(payload) {
      $scope.pieces.push(payload);
      $('#new-title').val('');
      $('#new-piece').val('');
    });
  };
  $scope.setActivePiece = function(piece) {
    $scope.activePiece = piece;
    $scope.syn_json = JSON.parse(piece.syn_json);
  };
  $scope.getSyns = function(word) {
    if (!$scope.syn_json[word]) {
      console.log('getting');
      $http.get('/synonyms/'+word).success(function(res) {
        $scope.syn_json[word] = res
        $scope.saveSyns();
      });
    }
  };
  $scope.setActiveWord = function(index, word) {
    $scope.activeWord = word.toLowerCase().match(/[a-z]+/g)[0];
    $scope.activeIndex = index;
    $scope.getSyns($scope.activeWord);
  };
  $scope.embedWord = function(word) {
    // var target = $('#show-piece span:nth-child(' + ($scope.activeIndex+1) + ')')
    // target.text(target.text().replace(/[a-z\s]+/i, word));
    var pieces = $scope.activePiece.content.split(' ');
    pieces[$scope.activeIndex] = pieces[$scope.activeIndex].replace(/[a-z]+/i, word);
    $scope.activePiece.content = pieces.join(' ');
  };
  $scope.saveSyns = function() {
    $http.post('/pieces/'+$scope.activePiece.id+'/syns', {syn_json: JSON.stringify($scope.syn_json)} )
  };
  $scope.savePiece = function() {
    $http.put('/pieces/'+$scope.activePiece.id, {content: $scope.stripSpan()} ).success(function() {
      alert('Saved!');
    });
  };
  $scope.stripSpan = function() {
    return ($('#show-piece').text().match(/\S+/gi) || []).join(' ')
  };
  $scope.refreshActiveFromSyn = function() {
    $scope.activePiece.content = $scope.stripSpan();
    $('#edit-piece').val($scope.activePiece.content);
  };
  $scope.refreshActiveFromEdit = function() {
    $scope.activePiece.content = $('#edit-piece').val();
  };
  $scope.deleteActive = function() {
    $http.delete('/pieces/'+$scope.activePiece.id).success(function(id) {
      $scope.syn_json = {};
      $scope.activePiece = {};
      $scope.activeWord = '';
      for (var i = 0; i < $scope.pieces.length; i++) {
        if ($scope.pieces[i].id == id) {
          $scope.pieces.splice(i,1);
        };
      };
    });
  };
  $scope.syn_json = {};
  $scope.activePiece = {};
  $scope.activeWord = '';
}])

.factory('Piece', ['$http', function NoteFactory($http) {
  return {
    all: function(user_id) {
      return $http.get('users/'+user_id+'/pieces');
    },
    create: function(data) {
      return $http.post('/pieces', data);
    }
  };
}])

.factory('User', ['$http', function UserFactory($http) {
  return {
    current: function() {
      return $http.get('users/current');
    },
    find: function(id) {
      return $http.get('users/'+id);
    }
  };
}])

.directive('addPiece', function() {
  return {
    restrict: 'E',
    templateUrl: 'partials/directives/add-piece.html',
    scope: {},
    link: function(scope) {
      scope.tab = 'button';
      scope.createPiece = scope.$parent.createPiece;
    }
  };
});

$(document).ready(function() {
  if (window.location.href.match(/session/)) {
    $('#sign-in').trigger('click');
  };
  if (window.location.href.match(/users/)) {
    document.getElementById('reg-but').click();
  };

  $(document).on('click', '.fancy span', function(e) {
    $('.fancy span').removeClass('grow');
    $(e.target).addClass('grow');
  });

  //registration form validation
  $(document).on('change', '.modal-body input', function() {
    if ($('#reg-password').val() === $('#conf-password').val() && $('#conf-password').val()) {
      $('.passw').parents('.form-group')
      .addClass('has-success')
      .removeClass('has-error');
      $('.modal-footer').find('.btn-primary').removeAttr('disabled');
    } else {
      $('.passw').parents('.form-group')
      .removeClass('has-success')
      .addClass('has-error');
      $('.modal-footer').find('.btn-primary').attr('disabled', 'disabled');
    };
  });
});
<|endoftext|>


<commit_before>$(document).ready(function() {

  //AJAX call for initial search with search bar
  $('#search').on('submit', function(event) {
    event.preventDefault();
    searchSetup();
    var $target = $(event.target);
    $.ajax({
      url: $target.attr('action'),
      type: 'POST',
      data: $target.serialize(),
      dataType: "JSON"
    }).done(function(response) {
      searchFinish(response);
    })
  })

  //AJAX call for initial search with thumbnail images
  $('.thumbnailSearch').on('click', function(event) {
    event.preventDefault();
    searchSetup();
    var $target = $(event.target);
    $.ajax({
      url: '/search/' + $target.attr('categoryId'),
      type: 'GET',
      dataType: "JSON"
    }).done(function(response) {
      searchFinish(response);
    })
  })

  //AJAX call to update likeCount of content and create Like
  $("#like").on('click', function(event) {
    event.preventDefault();
    $.ajax({
      url: '/' + content[contentNum].type + '/' + content[contentNum].id,
      type: 'POST'
    }).done(function(response) {
      console.log(response)
      if (response === "exists") {
        var n = noty({
          text: 'Like Already Exists!',
          type: 'warning',
          layout: 'topCenter',
          theme: 'relax',
          timeout: 1000
        });
      } else {
        var n = noty({
          text: 'Like Successful!',
          type: 'success',
          layout: 'topCenter',
          theme: 'relax',
          timeout: 1000
        });
      }
    }).fail(function(response) {
      var n = noty({
        text: 'Like Failed!',
        type: 'error',
        layout: 'topCenter',
        theme: 'relax',
        timeout: 1000
      });
    });
  })

  // Javascript used to go to the next piece of content
  $("#next").on('click', function(event) {
    event.preventDefault();
    if (content[++contentNum].type === "video") {
      $("#content iframe").attr("src", youtubeId(content[contentNum].url))
    } else {
      $("#content iframe").attr("src", content[contentNum].url)
    }
    resetCounter(contentNum, content)
  })

  // Javascript used to go to go back to the previous piece of content
  $("#back").on('click', function(event) {
    event.preventDefault();
    if (content[--contentNum].type === "video") {
      $("#content iframe").attr("src", youtubeId(content[contentNum].url))
    } else {
      $("#content iframe").attr("src", content[contentNum].url)
    }
  })

  // JavaScript used to toggle between show and edit partials on profile page
  $("#editButton").on('click', function(event) {
    var $target = $(event.target);
    $target.text($target.text() === "Edit List" ? "Show List" : "Edit List");
    $("#showListDiv").toggle();
    $("#editListDiv").toggle();
  });

  //AJAX call to delete videos and articles from posts
  $("#editList").on('submit', function(event) {
    event.preventDefault();
    var $target = $(event.target);
    $.ajax({
      url: $target.attr('action'),
      type: 'DELETE',
      data: $target.serialize()
    }).done(function(response) {
      $(".fuzzy-search").val("");
      showList.fuzzySearch.search('');
      editList.fuzzySearch.search('');
      var n = noty({
        text: 'List Update Successful!',
        type: 'success',
        layout: 'topCenter',
        theme: 'relax',
        timeout: 1000
      });
      $("input:checked").each(function() {
        $("a[href='" + $(this).prev().attr('href') + "']").remove();
        $("#" + this.name + "").remove();
        $(this).remove();
      });
    }).fail(function(response) {
      var n = noty({
        text: 'List Update Failed!',
        type: 'error',
        layout: 'topCenter',
        theme: 'relax',
        timeout: 1000
      });
    });
  })

  var showList = new List('show-list', {
    valueNames: ['title'],
    plugins: [ListFuzzySearch()]
  });

  var editList = new List('edit-list', {
    valueNames: ['title'],
    plugins: [ListFuzzySearch()]
  });

  //The following code starts the animation
  new imageLoader(cImageSrc, 'startAnimation()');

});

function youtubeId(url) {
  var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
  var match = url.match(regExp);

  if (match && match[2].length == 11) {
    return "//www.youtube.com/embed/" + match[2];
  }
}

function httpConvert(url) {
  return url = url.replace(/^http:\/\//, 'https://')
}

// function twitterButton() {
//   $("#twitterDiv").empty();
//   var $clone = $(".twitter-share-button-template").clone();
//   $clone.show();
//   $clone.attr("data-url", httpConvert(content[contentNum].url));
//   $clone.attr("class", "twitter-share-button");
//   $("#twitterDiv").append($clone);
//   $.getScript("http://platform.twitter.com/widgets.js");
// }

function resetCounter(counter, array) {
  if (counter > array.length) {
    counter = -1
  }
}

function searchSetup() {
  $("#search").hide();
  $("#initial").show();
  $(".homepage").hide();
  $("#searchWrapper #loaderImage").show();
}

function searchFinish(response) {
  content = response
  $("#initial").remove();
  $("#searchWrapper #loaderImage").hide();
  $("#search").show();
  $("#likeButtons").show();
  $("#content").show();
  $content = $("#content iframe")
  contentNum = 0;
  if (content[contentNum].type === "video") {
    $content.attr("src", youtubeId(content[contentNum].url))
    $content.attr("contentId", content[contentNum].id)
  } else {
    $content.attr("src", content[contentNum].url)
    $content.attr("contentId", content[contentNum].id)
  }
}

//Facebook SDK function
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s);
  js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

var cSpeed = 9;
var cWidth = 256;
var cHeight = 88;
var cTotalFrames = 11;
var cFrameWidth = 256;
var cImageSrc = '../img/sprites.png';

var cImageTimeout = false;
var cIndex = 0;
var cXpos = 0;
var cPreloaderTimeout = false;
var SECONDS_BETWEEN_FRAMES = 0;

function startAnimation() {

  document.getElementById('loaderImage').style.backgroundImage = 'url(' + cImageSrc + ')';
  document.getElementById('loaderImage').style.width = cWidth + 'px';
  document.getElementById('loaderImage').style.height = cHeight + 'px';

  //FPS = Math.round(100/(maxSpeed+2-speed));
  FPS = Math.round(100 / cSpeed);
  SECONDS_BETWEEN_FRAMES = 1 / FPS;

  cPreloaderTimeout = setTimeout('continueAnimation()', SECONDS_BETWEEN_FRAMES / 1000);

}

function continueAnimation() {

  cXpos += cFrameWidth;
  //increase the index so we know which frame of our animation we are currently on
  cIndex += 1;

  //if our cIndex is higher than our total number of frames, we're at the end and should restart
  if (cIndex >= cTotalFrames) {
    cXpos = 0;
    cIndex = 0;
  }

  if (document.getElementById('loaderImage'))
    document.getElementById('loaderImage').style.backgroundPosition = (-cXpos) + 'px 0';

  cPreloaderTimeout = setTimeout('continueAnimation()', SECONDS_BETWEEN_FRAMES * 1000);
}

function stopAnimation() { //stops animation
  clearTimeout(cPreloaderTimeout);
  cPreloaderTimeout = false;
}

function imageLoader(s, fun) //Pre-loads the sprites image
{
  clearTimeout(cImageTimeout);
  cImageTimeout = 0;
  genImage = new Image();
  genImage.onload = function() {
    cImageTimeout = setTimeout(fun, 0)
  };
  genImage.onerror = new Function('alert(\'Could not load the image\')');
  genImage.src = s;
}<commit_msg>Remove console.log in application.js<commit_after>$(document).ready(function() {

  //AJAX call for initial search with search bar
  $('#search').on('submit', function(event) {
    event.preventDefault();
    searchSetup();
    var $target = $(event.target);
    $.ajax({
      url: $target.attr('action'),
      type: 'POST',
      data: $target.serialize(),
      dataType: "JSON"
    }).done(function(response) {
      searchFinish(response);
    })
  })

  //AJAX call for initial search with thumbnail images
  $('.thumbnailSearch').on('click', function(event) {
    event.preventDefault();
    searchSetup();
    var $target = $(event.target);
    $.ajax({
      url: '/search/' + $target.attr('categoryId'),
      type: 'GET',
      dataType: "JSON"
    }).done(function(response) {
      searchFinish(response);
    })
  })

  //AJAX call to update likeCount of content and create Like
  $("#like").on('click', function(event) {
    event.preventDefault();
    $.ajax({
      url: '/' + content[contentNum].type + '/' + content[contentNum].id,
      type: 'POST'
    }).done(function(response) {
      if (response === "exists") {
        var n = noty({
          text: 'Like Already Exists!',
          type: 'warning',
          layout: 'topCenter',
          theme: 'relax',
          timeout: 1000
        });
      } else {
        var n = noty({
          text: 'Like Successful!',
          type: 'success',
          layout: 'topCenter',
          theme: 'relax',
          timeout: 1000
        });
      }
    }).fail(function(response) {
      var n = noty({
        text: 'Like Failed!',
        type: 'error',
        layout: 'topCenter',
        theme: 'relax',
        timeout: 1000
      });
    });
  })

  // Javascript used to go to the next piece of content
  $("#next").on('click', function(event) {
    event.preventDefault();
    if (content[++contentNum].type === "video") {
      $("#content iframe").attr("src", youtubeId(content[contentNum].url))
    } else {
      $("#content iframe").attr("src", content[contentNum].url)
    }
    resetCounter(contentNum, content)
  })

  // Javascript used to go to go back to the previous piece of content
  $("#back").on('click', function(event) {
    event.preventDefault();
    if (content[--contentNum].type === "video") {
      $("#content iframe").attr("src", youtubeId(content[contentNum].url))
    } else {
      $("#content iframe").attr("src", content[contentNum].url)
    }
  })

  // JavaScript used to toggle between show and edit partials on profile page
  $("#editButton").on('click', function(event) {
    var $target = $(event.target);
    $target.text($target.text() === "Edit List" ? "Show List" : "Edit List");
    $("#showListDiv").toggle();
    $("#editListDiv").toggle();
  });

  //AJAX call to delete videos and articles from posts
  $("#editList").on('submit', function(event) {
    event.preventDefault();
    var $target = $(event.target);
    $.ajax({
      url: $target.attr('action'),
      type: 'DELETE',
      data: $target.serialize()
    }).done(function(response) {
      $(".fuzzy-search").val("");
      showList.fuzzySearch.search('');
      editList.fuzzySearch.search('');
      var n = noty({
        text: 'List Update Successful!',
        type: 'success',
        layout: 'topCenter',
        theme: 'relax',
        timeout: 1000
      });
      $("input:checked").each(function() {
        $("a[href='" + $(this).prev().attr('href') + "']").remove();
        $("#" + this.name + "").remove();
        $(this).remove();
      });
    }).fail(function(response) {
      var n = noty({
        text: 'List Update Failed!',
        type: 'error',
        layout: 'topCenter',
        theme: 'relax',
        timeout: 1000
      });
    });
  })

  var showList = new List('show-list', {
    valueNames: ['title'],
    plugins: [ListFuzzySearch()]
  });

  var editList = new List('edit-list', {
    valueNames: ['title'],
    plugins: [ListFuzzySearch()]
  });

  //The following code starts the animation
  new imageLoader(cImageSrc, 'startAnimation()');

});

function youtubeId(url) {
  var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
  var match = url.match(regExp);

  if (match && match[2].length == 11) {
    return "//www.youtube.com/embed/" + match[2];
  }
}

function httpConvert(url) {
  return url = url.replace(/^http:\/\//, 'https://')
}

// function twitterButton() {
//   $("#twitterDiv").empty();
//   var $clone = $(".twitter-share-button-template").clone();
//   $clone.show();
//   $clone.attr("data-url", httpConvert(content[contentNum].url));
//   $clone.attr("class", "twitter-share-button");
//   $("#twitterDiv").append($clone);
//   $.getScript("http://platform.twitter.com/widgets.js");
// }

function resetCounter(counter, array) {
  if (counter > array.length) {
    counter = -1
  }
}

function searchSetup() {
  $("#search").hide();
  $("#initial").show();
  $(".homepage").hide();
  $("#searchWrapper #loaderImage").show();
}

function searchFinish(response) {
  content = response
  $("#initial").remove();
  $("#searchWrapper #loaderImage").hide();
  $("#search").show();
  $("#likeButtons").show();
  $("#content").show();
  $content = $("#content iframe")
  contentNum = 0;
  if (content[contentNum].type === "video") {
    $content.attr("src", youtubeId(content[contentNum].url))
    $content.attr("contentId", content[contentNum].id)
  } else {
    $content.attr("src", content[contentNum].url)
    $content.attr("contentId", content[contentNum].id)
  }
}

//Facebook SDK function
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s);
  js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.0";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

var cSpeed = 9;
var cWidth = 256;
var cHeight = 88;
var cTotalFrames = 11;
var cFrameWidth = 256;
var cImageSrc = '../img/sprites.png';

var cImageTimeout = false;
var cIndex = 0;
var cXpos = 0;
var cPreloaderTimeout = false;
var SECONDS_BETWEEN_FRAMES = 0;

function startAnimation() {

  document.getElementById('loaderImage').style.backgroundImage = 'url(' + cImageSrc + ')';
  document.getElementById('loaderImage').style.width = cWidth + 'px';
  document.getElementById('loaderImage').style.height = cHeight + 'px';

  //FPS = Math.round(100/(maxSpeed+2-speed));
  FPS = Math.round(100 / cSpeed);
  SECONDS_BETWEEN_FRAMES = 1 / FPS;

  cPreloaderTimeout = setTimeout('continueAnimation()', SECONDS_BETWEEN_FRAMES / 1000);

}

function continueAnimation() {

  cXpos += cFrameWidth;
  //increase the index so we know which frame of our animation we are currently on
  cIndex += 1;

  //if our cIndex is higher than our total number of frames, we're at the end and should restart
  if (cIndex >= cTotalFrames) {
    cXpos = 0;
    cIndex = 0;
  }

  if (document.getElementById('loaderImage'))
    document.getElementById('loaderImage').style.backgroundPosition = (-cXpos) + 'px 0';

  cPreloaderTimeout = setTimeout('continueAnimation()', SECONDS_BETWEEN_FRAMES * 1000);
}

function stopAnimation() { //stops animation
  clearTimeout(cPreloaderTimeout);
  cPreloaderTimeout = false;
}

function imageLoader(s, fun) //Pre-loads the sprites image
{
  clearTimeout(cImageTimeout);
  cImageTimeout = 0;
  genImage = new Image();
  genImage.onload = function() {
    cImageTimeout = setTimeout(fun, 0)
  };
  genImage.onerror = new Function('alert(\'Could not load the image\')');
  genImage.src = s;
}<|endoftext|>


<commit_before><commit_msg>fix rest of event distribution<commit_after><|endoftext|>


<commit_before>angular.module('GMPDApp', [])
    .controller('SearchController', function($scope, $http) {
        $http({
            method: 'GET',
            url: '/search?q=carl+craig'
        }).then(function successCallback(res) {
            $scope.tracks = res.data.entries.filter((x) => x.type == 1).map((x) => x.track);
            $scope.artists = res.data.entries.filter((x) => x.type == 2).map((x) => x.artist);
            console.log($scope.tracks);
        }, function errorCallback(res) {
            console.log(res);
        });
    })

<commit_msg>Removed console log<commit_after>angular.module('GMPDApp', [])
    .controller('SearchController', function($scope, $http) {
        $http({
            method: 'GET',
            url: '/search?q=carl+craig'
        }).then(function successCallback(res) {
            $scope.tracks = res.data.entries.filter((x) => x.type == 1).map((x) => x.track);
            $scope.artists = res.data.entries.filter((x) => x.type == 2).map((x) => x.artist);
        }, function errorCallback(res) {
            console.log(res);
        });
    })

<|endoftext|>


<commit_before>define(['FFF','zepto'],function(FFF,$){
	var F=FFF.FFF;
	var Widget=F.Widget;
	function FontSelect(){
		Widget.apply(this,arguments);
	}

	FontSelect.ATTRS={
		boundingBox:{
			value:$('

')
		},
		title:{
			value:'选择字体',
			changeFn:function(obj){
				var that =this;
				that.$btn.text(obj.value);
			}
		},
		selectIndex:{
			value:0
		}
	}
	F.extend(FontSelect,Widget,{
		initialize:function(){

		},
		renderUI:function(){
			var that=this;
			var html ='';
			var btnhtml='<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1">'+that.getTitle()+'</button>';
			$.ajax({
	            type: "get",
	            url: '/loadFontlist',
	            success: function(data){
	            	 for (var i = 0; i < data.length; i++) {
	            	 	var ff =data[i].replace(/\.\w*/g,"");
	            	 	if(ff!=""){
	            	 	 html+='
'+ff+'
';
	            	 	}
	            	 };

	                var ulhtml ='
'+html+'
' ;

	               that.getBoundingBox().append(btnhtml+ulhtml);

	            },
	            error: function(xhr, type){
	                alert('Ajax error!')
	            }
           });

		},
		bindUI:function(){
			var that=this;

			setTimeout(function(){
				var $dom =  that.getBoundingBox();

			  that.$btn =$dom.find('#dropdownMenu1');

			 that.$ul =$dom.find('.J_select');

            var $lic =$dom.find('.W_li_click');

            that.$btn.on('click',function(){
            	that.$ul.show();
            })
            $lic.on('click',function(){
            	 that.setTitle($(this).children('a').text());
            	 that.setSelectIndex($(this).children('a').attr('index'));
            	 that.$ul.hide();
            })

			},1000)

		},
		destructor:function(){

		},
		getFonts:function(){
			var that=this;
			var html='';
			$.ajax({
	            type: "get",
	            url: '/loadFontlist',
	            success: function(data){
	            	 for (var i = 0; i < data.length; i++) {
	            	 	var ff =data[i].replace(/\.\w*/g,"");
	            	 	var isadd =false;
	            	 	if(ff=="") continue;
	            	 	var $ul = that.$ul.children('li')
	            	    $ul.each(function(inde,item){
	            	  	var fontname = $(item).attr('fontname');
			          	     if(fontname==ff){
			          	     	isadd=false
			          	     	return false;
			          	     }else{
			          	     	isadd=true;
			          	     }

			          })
	            	  if(isadd){
	            	  	var l =parseInt($ul.length)+1;
	            	  	html+='
'+ff+'
';
	            	  }
	            	 };
	                that.$ul.append(html);

	            },
	            error: function(xhr, type){
	                alert('Ajax error!')
	            }
           });

		}
	});
	return{
		FontSelect:FontSelect
	}
});<commit_msg>修改上传后不能选中<commit_after>define(['FFF','zepto'],function(FFF,$){
	var F=FFF.FFF;
	var Widget=F.Widget;
	function FontSelect(){
		Widget.apply(this,arguments);
	}

	FontSelect.ATTRS={
		boundingBox:{
			value:$('

')
		},
		title:{
			value:'选择字体',
			changeFn:function(obj){
				var that =this;
				that.$btn.text(obj.value);
			}
		},
		selectIndex:{
			value:0
		}
	}
	F.extend(FontSelect,Widget,{
		initialize:function(){

		},
		renderUI:function(){
			var that=this;
			var html ='';
			var btnhtml='<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1">'+that.getTitle()+'</button>';
			$.ajax({
	            type: "get",
	            url: '/loadFontlist',
	            success: function(data){
	            	 for (var i = 0; i < data.length; i++) {
	            	 	var ff =data[i].replace(/\.\w*/g,"");
	            	 	if(ff!=""){
	            	 	 html+='
'+ff+'
';
	            	 	}
	            	 };

	                var ulhtml ='
'+html+'
' ;

	               that.getBoundingBox().append(btnhtml+ulhtml);

	            },
	            error: function(xhr, type){
	                alert('Ajax error!')
	            }
           });

		},
		bindUI:function(){
			var that=this;

			setTimeout(function(){
				var $dom =  that.getBoundingBox();

			  that.$btn =$dom.find('#dropdownMenu1');

			 that.$ul =$dom.find('.J_select');

            var $lic =$dom.find('.W_li_click');

            that.$btn.on('click',function(){
              	that.$ul.show();
            })
            that.$ul.on('click',function(e){
            	   var target = e.target.tagName.toUpperCase();
            	     if(target=="A" || target=="LI"){
            	     	var txt = $(e.target).text() || $(e.target).children('a').text();
            	     	var index = $(e.target).attr('index') || $(e.target).children('a').attr('index');
            	     	that.setTitle(txt);
		            	 that.setSelectIndex(parseInt(index));
		            	 $(this).hide();
            	     }

            })

			},1000)

		},
		destructor:function(){

		},
		getFonts:function(){
			var that=this;
			var html='';
			$.ajax({
	            type: "get",
	            url: '/loadFontlist',
	            success: function(data){
	            	 for (var i = 0; i < data.length; i++) {
	            	 	var ff =data[i].replace(/\.\w*/g,"");
	            	 	var isadd =false;
	            	 	if(ff=="") continue;
	            	 	var $ul = that.$ul.children('li')
	            	    $ul.each(function(inde,item){
	            	  	var fontname = $(item).attr('fontname');
			          	     if(fontname==ff){
			          	     	isadd=false
			          	     	return false;
			          	     }else{
			          	     	isadd=true;
			          	     }

			          })
	            	  if(isadd){
	            	  	var l =parseInt($ul.length)+1;
	            	  	html+='
'+ff+'
';
	            	  }
	            	 };
	                that.$ul.append(html);

	            },
	            error: function(xhr, type){
	                alert('Ajax error!')
	            }
           });

		}
	});
	return{
		FontSelect:FontSelect
	}
});<|endoftext|>


<commit_before>import { moduleForModel, test } from 'ember-qunit';
import modelList from '../../helpers/model-list';
import Ember from 'ember';

const { run } = Ember;

moduleForModel('course', 'Unit | Model | Course', {
  needs: modelList
});

test('it exists', function(assert) {
  let model = this.subject();
  assert.ok(!!model);
});

test('check required publication items', function(assert) {
  let model = this.subject();
  let store = this.store();
  assert.equal(model.get('requiredPublicationIssues').length, 3);
  var cohort = store.createRecord('cohort');
  model.get('cohorts').addObject(cohort);
  assert.equal(model.get('requiredPublicationIssues').length, 2);
  model.set('startDate', 'nothing');
  assert.equal(model.get('requiredPublicationIssues').length, 1);
  model.set('endDate', 'nothing');
  assert.equal(model.get('requiredPublicationIssues').length, 0);
});

test('check optional publication items', function(assert) {
  let model = this.subject();
  let store = this.store();
  assert.equal(model.get('optionalPublicationIssues').length, 3);
  model.get('terms').addObject(store.createRecord('term'));
  assert.equal(model.get('optionalPublicationIssues').length, 2);
  model.get('objectives').addObject(store.createRecord('objective'));
  assert.equal(model.get('optionalPublicationIssues').length, 1);
  model.get('meshDescriptors').addObject(store.createRecord('meshDescriptor'));
  assert.equal(model.get('optionalPublicationIssues').length, 0);
});

test('check empty competencies', async function(assert) {
  assert.expect(1);
  let course = this.subject();

  const competencies = await course.get('competencies');
  assert.equal(competencies.length, 0);
});

test('check competencies', async function(assert) {
  assert.expect(4);
  let course = this.subject();
  let store = this.store();

  await run( async () => {
    let competency1 = store.createRecord('competency');
    let competency2 = store.createRecord('competency');
    let competency3 = store.createRecord('competency');

    let objective1 = store.createRecord('objective', {competency: competency1});
    let objective2 = store.createRecord('objective', {competency: competency2});
    let objective3 = store.createRecord('objective', {competency: competency3, courses: [course], parents: [objective1]});
    let objective4 = store.createRecord('objective', {courses: [course], parents: [objective2]});
    objective1.get('children').pushObject(objective3);
    objective2.get('children').pushObject(objective4);
    course.get('objectives').pushObjects([objective3, objective4]);

    const competencies = await course.get('competencies');

    assert.equal(competencies.length, 3);
    assert.ok(competencies.includes(competency1));
    assert.ok(competencies.includes(competency2));
    assert.ok(competencies.includes(competency3));
  });
});

test('check publishedSessionOfferingCounts count', function(assert) {
  assert.expect(2);
  let course = this.subject();
  let store = this.store();

  run(() => {
    let offering1 = store.createRecord('offering');
    let offering2 = store.createRecord('offering');
    let offering3 = store.createRecord('offering');
    let offering4 = store.createRecord('offering');

    let session1 = store.createRecord('session', {offerings: [offering1, offering2], published: true});
    let session2 = store.createRecord('session', {offerings: [offering3], published: true});
    let session3 = store.createRecord('session', {offerings: [offering4], published: false});

    course.get('sessions').pushObjects([session1, session2, session3]);

    assert.equal(course.get('publishedOfferingCount'), 3);
    let offering5 = store.createRecord('offering');
    session1.get('offerings').pushObject(offering5);
    session3.set('published', true);

    assert.equal(course.get('publishedOfferingCount'), 5);
  });
});

test("domains", async function(assert) {
  assert.expect(10);
  let course = this.subject();
  let store = this.store();
  await run( async () => {
    const domain1 = store.createRecord('competency', { id: 1, title: 'Zylinder' });
    const domain2 = store.createRecord('competency', { id: 2, title: 'Anton' });
    const domain3 = store.createRecord('competency', { id: 3, title: 'Lexicon' });
    const competency1 = store.createRecord('competency', { id: 4, title: 'Zeppelin', parent: domain1 });
    const competency2 = store.createRecord('competency', { id: 5, title: 'Aardvark', parent: domain1 });
    const competency3 = store.createRecord('competency', { id: 6, title: 'Geflarknik', parent: domain2 });
    // competencies that are linked to these domains, but not to this course.
    // they should not appear in the output.
    store.createRecord('competency', { id: 7, parent: domain1 });
    store.createRecord('competency', { id: 8, parent: domain2 });
    store.createRecord('competency', { id: 9, parent: domain3 });

    let objective1 = store.createRecord('objective', { competency: competency1 });
    let objective2 = store.createRecord('objective', { competency: competency2 });
    let objective3 = store.createRecord('objective', { competency: competency3 });
    let objective4 = store.createRecord('objective', { competency: domain3 });

    course.get('objectives').pushObjects([ objective1, objective2, objective3, objective4 ]);

    const domainProxies = await course.get('domains');
    assert.equal(domainProxies.length, 3);

    const domainProxy1 = domainProxies[0];
    assert.equal(domainProxy1.get('content'), domain2);
    assert.equal(domainProxy1.get('subCompetencies').length, 1);
    assert.ok(domainProxy1.get('subCompetencies').includes(competency3));

    const domainProxy2 = domainProxies[1];
    assert.equal(domainProxy2.get('content'), domain3);
    assert.equal(domainProxy2.get('subCompetencies').length, 0);

    const domainProxy3 = domainProxies[2];
    assert.equal(domainProxy3.get('content'), domain1);
    assert.equal(domainProxy3.get('subCompetencies').length, 2);
    assert.equal(domainProxy3.get('subCompetencies')[0], competency2);
    assert.equal(domainProxy3.get('subCompetencies')[1], competency1);
  });
});

test('schools', async function(assert) {
  assert.expect(4);
  let course = this.subject();
  let store = this.store();
  await run( async () => {
    const school1 = store.createRecord('school');
    const school2 = store.createRecord('school');
    const school3 = store.createRecord('school');
    const program1 = store.createRecord('program', { school: school2 });
    const program2 = store.createRecord('program', { school: school2 });
    const program3 = store.createRecord('program', { school: school3 });
    const programYear1 = store.createRecord('programYear', { program: program1 });
    const programYear2 = store.createRecord('programYear', { program: program2 });
    const programYear3 = store.createRecord('programYear', { program: program3 });
    const cohort1 = store.createRecord('cohort', { programYear: programYear1 });
    const cohort2 = store.createRecord('cohort', { programYear: programYear2 });
    const cohort3 = store.createRecord('cohort', { programYear: programYear3 });

    course.get('cohorts').pushObjects([ cohort1, cohort2, cohort3 ]);
    course.set('school', school1);

    const schools = await course.get('schools');

    assert.equal(schools.length, 3);
    assert.ok(schools.includes(school1));
    assert.ok(schools.includes(school2));
    assert.ok(schools.includes(school3));
  });
});
<commit_msg>test coverage for assignableVocabularies CP.<commit_after>import { moduleForModel, test } from 'ember-qunit';
import modelList from '../../helpers/model-list';
import Ember from 'ember';

const { run } = Ember;

moduleForModel('course', 'Unit | Model | Course', {
  needs: modelList
});

test('it exists', function(assert) {
  let model = this.subject();
  assert.ok(!!model);
});

test('check required publication items', function(assert) {
  let model = this.subject();
  let store = this.store();
  assert.equal(model.get('requiredPublicationIssues').length, 3);
  var cohort = store.createRecord('cohort');
  model.get('cohorts').addObject(cohort);
  assert.equal(model.get('requiredPublicationIssues').length, 2);
  model.set('startDate', 'nothing');
  assert.equal(model.get('requiredPublicationIssues').length, 1);
  model.set('endDate', 'nothing');
  assert.equal(model.get('requiredPublicationIssues').length, 0);
});

test('check optional publication items', function(assert) {
  let model = this.subject();
  let store = this.store();
  assert.equal(model.get('optionalPublicationIssues').length, 3);
  model.get('terms').addObject(store.createRecord('term'));
  assert.equal(model.get('optionalPublicationIssues').length, 2);
  model.get('objectives').addObject(store.createRecord('objective'));
  assert.equal(model.get('optionalPublicationIssues').length, 1);
  model.get('meshDescriptors').addObject(store.createRecord('meshDescriptor'));
  assert.equal(model.get('optionalPublicationIssues').length, 0);
});

test('check empty competencies', async function(assert) {
  assert.expect(1);
  let course = this.subject();

  const competencies = await course.get('competencies');
  assert.equal(competencies.length, 0);
});

test('check competencies', async function(assert) {
  assert.expect(4);
  let course = this.subject();
  let store = this.store();

  await run( async () => {
    let competency1 = store.createRecord('competency');
    let competency2 = store.createRecord('competency');
    let competency3 = store.createRecord('competency');

    let objective1 = store.createRecord('objective', {competency: competency1});
    let objective2 = store.createRecord('objective', {competency: competency2});
    let objective3 = store.createRecord('objective', {competency: competency3, courses: [course], parents: [objective1]});
    let objective4 = store.createRecord('objective', {courses: [course], parents: [objective2]});
    objective1.get('children').pushObject(objective3);
    objective2.get('children').pushObject(objective4);
    course.get('objectives').pushObjects([objective3, objective4]);

    const competencies = await course.get('competencies');

    assert.equal(competencies.length, 3);
    assert.ok(competencies.includes(competency1));
    assert.ok(competencies.includes(competency2));
    assert.ok(competencies.includes(competency3));
  });
});

test('check publishedSessionOfferingCounts count', function(assert) {
  assert.expect(2);
  let course = this.subject();
  let store = this.store();

  run(() => {
    let offering1 = store.createRecord('offering');
    let offering2 = store.createRecord('offering');
    let offering3 = store.createRecord('offering');
    let offering4 = store.createRecord('offering');

    let session1 = store.createRecord('session', {offerings: [offering1, offering2], published: true});
    let session2 = store.createRecord('session', {offerings: [offering3], published: true});
    let session3 = store.createRecord('session', {offerings: [offering4], published: false});

    course.get('sessions').pushObjects([session1, session2, session3]);

    assert.equal(course.get('publishedOfferingCount'), 3);
    let offering5 = store.createRecord('offering');
    session1.get('offerings').pushObject(offering5);
    session3.set('published', true);

    assert.equal(course.get('publishedOfferingCount'), 5);
  });
});

test("domains", async function(assert) {
  assert.expect(10);
  let course = this.subject();
  let store = this.store();
  await run( async () => {
    const domain1 = store.createRecord('competency', { id: 1, title: 'Zylinder' });
    const domain2 = store.createRecord('competency', { id: 2, title: 'Anton' });
    const domain3 = store.createRecord('competency', { id: 3, title: 'Lexicon' });
    const competency1 = store.createRecord('competency', { id: 4, title: 'Zeppelin', parent: domain1 });
    const competency2 = store.createRecord('competency', { id: 5, title: 'Aardvark', parent: domain1 });
    const competency3 = store.createRecord('competency', { id: 6, title: 'Geflarknik', parent: domain2 });
    // competencies that are linked to these domains, but not to this course.
    // they should not appear in the output.
    store.createRecord('competency', { id: 7, parent: domain1 });
    store.createRecord('competency', { id: 8, parent: domain2 });
    store.createRecord('competency', { id: 9, parent: domain3 });

    let objective1 = store.createRecord('objective', { competency: competency1 });
    let objective2 = store.createRecord('objective', { competency: competency2 });
    let objective3 = store.createRecord('objective', { competency: competency3 });
    let objective4 = store.createRecord('objective', { competency: domain3 });

    course.get('objectives').pushObjects([ objective1, objective2, objective3, objective4 ]);

    const domainProxies = await course.get('domains');
    assert.equal(domainProxies.length, 3);

    const domainProxy1 = domainProxies[0];
    assert.equal(domainProxy1.get('content'), domain2);
    assert.equal(domainProxy1.get('subCompetencies').length, 1);
    assert.ok(domainProxy1.get('subCompetencies').includes(competency3));

    const domainProxy2 = domainProxies[1];
    assert.equal(domainProxy2.get('content'), domain3);
    assert.equal(domainProxy2.get('subCompetencies').length, 0);

    const domainProxy3 = domainProxies[2];
    assert.equal(domainProxy3.get('content'), domain1);
    assert.equal(domainProxy3.get('subCompetencies').length, 2);
    assert.equal(domainProxy3.get('subCompetencies')[0], competency2);
    assert.equal(domainProxy3.get('subCompetencies')[1], competency1);
  });
});

test('schools', async function(assert) {
  assert.expect(4);
  let course = this.subject();
  let store = this.store();
  await run( async () => {
    const school1 = store.createRecord('school');
    const school2 = store.createRecord('school');
    const school3 = store.createRecord('school');
    const program1 = store.createRecord('program', { school: school2 });
    const program2 = store.createRecord('program', { school: school2 });
    const program3 = store.createRecord('program', { school: school3 });
    const programYear1 = store.createRecord('programYear', { program: program1 });
    const programYear2 = store.createRecord('programYear', { program: program2 });
    const programYear3 = store.createRecord('programYear', { program: program3 });
    const cohort1 = store.createRecord('cohort', { programYear: programYear1 });
    const cohort2 = store.createRecord('cohort', { programYear: programYear2 });
    const cohort3 = store.createRecord('cohort', { programYear: programYear3 });

    course.get('cohorts').pushObjects([ cohort1, cohort2, cohort3 ]);
    course.set('school', school1);

    const schools = await course.get('schools');

    assert.equal(schools.length, 3);
    assert.ok(schools.includes(school1));
    assert.ok(schools.includes(school2));
    assert.ok(schools.includes(school3));
  });
});

test('assignableVocabularies', async function(assert){
  assert.expect(5);
  let course = this.subject();
  let store = this.store();
  await run( async () => {
    const school1 = store.createRecord('school', { title: 'Zylinder' });
    const school2 = store.createRecord('school', { title: 'Anton' });
    const vocabulary1 = store.createRecord('vocabulary', { title: 'Sowjetunion',  school: school1 });
    const vocabulary2 = store.createRecord('vocabulary', { title: 'DDR', school: school1 });
    const vocabulary3 = store.createRecord('vocabulary', { title: 'Walter Ulbricht', school: school2 });
    const vocabulary4 = store.createRecord('vocabulary', { title: 'Antifaschistischer Schutzwall', school: school2 });
    const program = store.createRecord('program', { school: school1 });
    const programYear = store.createRecord('programYear', { program });
    const cohort = store.createRecord('cohort', { programYear });
    course.get('cohorts').pushObject(cohort);
    course.set('school', school2);

    const vocabularies = await course.get('assignableVocabularies');
    assert.equal(vocabularies.length, 4);
    assert.equal(vocabularies[0], vocabulary4);
    assert.equal(vocabularies[1], vocabulary3);
    assert.equal(vocabularies[2], vocabulary2);
    assert.equal(vocabularies[3], vocabulary1);
  });
});
<|endoftext|>


<commit_before>/**
 * Notifications. Thingy innit.
 */
var notificationsDropdown = document.getElementById("notificationsDropdown");
var notificationsList = document.getElementById("user-notifications");
var notificationsBadge = document.getElementById("notificationsBadge");
var updatedReadStatus = false;
if (!notificationsList) {
	console.error("No notification dropdown found. Aborting notificationsThingy.");
}

function onNotificationsGetSuccess(data) {
	//console.log("notificationsThingy onNotificationsGetSuccess", data);
	if (data.headers && data.headers["X-Notification-Count"] && (data.headers["X-Notification-Count"] > 0)) {
		var HTML = [];
		var notificationIds = [];
		HTML.push(
			'
Notifications
 ' +
			'

'
		)
		for (var i = 0; i < 10; i++) {
			if (data.body[i]) {
				var notification = data.body[i];
				var url = "#";
				switch (notification.type) {
					case "user_got_a_notification":
						break;
					case "user_approved_access_to_year":
					case "user_rejected_access_to_year":
						url = '/dashboard.php';
						break;
					case "user_wants_to_access_a_year":
					case "group_wants_to_undertake_a_project":
					case "user_wants_to_join_a_group":
						url = '/intents.php?action=view&id=' + notification.intent.id;
						break;
					case "user_approved_another_to_join_a_group":
					case "user_rejected_another_to_join_a_group":
					case "user_joined_a_group":
					case "user_left_a_group":
						url = '/profile.php?type=group&id=' + notification.group.id;
						break;
					case "group_undertaken_project_approved":
					case "group_undertaken_project_rejected":
					case "group_released_project":
						url = '/profile.php?type=project&id=' + notification.project.id;
						break;
				}

				HTML.push('
' + notification.text + '
');
				if (!data.body[i].read) {
					notificationIds.push(data.body[i].id);
				}
			}
		}
		HTML.push(
			'

' +
			'
See All
'
		)
		notificationsList.innerHTML = HTML.join("");
		if (notificationIds > 0) {
			notificationsBadge.innerText = notificationIds.length.toString();
			notificationsBadge.style.display = "block";
			notificationsDropdown.setAttribute('onclick', 'setReadStatus([' + notificationIds + '])');
			updatedReadStatus = false;
		}
		else {
			notificationsBadge.style.display = "none";
		}
	}
	else {
		notificationsList.innerHTML = '
You have no notifications
'
	}
}

function onNotificationsGetError(data) {
	console.error("notificationsThingy onNotificationsGetError", data);
}

function GetNotifications() {
	API.GET("/me/notifications", {}, onNotificationsGetSuccess, onNotificationsGetError);
}

function onCheckNotificationsSuccess(data) {
	//console.log("notificationsThingy onCheckNotificationsSuccess", data);
	if (data.headers && data.headers["X-Notification-Count"] && (data.headers["X-Notification-Count"] > 0)) {
		GetNotifications();
	}
}

function onCheckNotificationsError(data) {
	// Meh. Who cares.
	// console.error("notificationsThingy onCheckNotificationsError", data);
}

function setReadStatus(ids) {
	if(!updatedReadStatus) {
		API.PUT("/me/notifications", {
				ids: ids
			},
			function onNotificationReadStatusUpdateSuccess(data) {
				//console.log(data.body);
				updatedReadStatus = true;
			},
			function onNotificationReadStatusUpdateError() {
				console.error("Failed to update the read status for notifications");
			}
		)
	}
	GetNotifications();
}

function CheckUnreadNotificationInterval() {
	API.HEAD("/me/notifications", {"unread": 1}, onCheckNotificationsSuccess, onCheckNotificationsError);
}

setInterval(CheckUnreadNotificationInterval, 10000);
GetNotifications();<commit_msg>Support for group join invites<commit_after>/**
 * Notifications. Thingy innit.
 */
var notificationsDropdown = document.getElementById("notificationsDropdown");
var notificationsList = document.getElementById("user-notifications");
var notificationsBadge = document.getElementById("notificationsBadge");
var updatedReadStatus = false;
if (!notificationsList) {
	console.error("No notification dropdown found. Aborting notificationsThingy.");
}

function onNotificationsGetSuccess(data) {
	//console.log("notificationsThingy onNotificationsGetSuccess", data);
	if (data.headers && data.headers["X-Notification-Count"] && (data.headers["X-Notification-Count"] > 0)) {
		var HTML = [];
		var notificationIds = [];
		HTML.push(
			'
Notifications
 ' +
			'

'
		)
		for (var i = 0; i < 10; i++) {
			if (data.body[i]) {
				var notification = data.body[i];
				var url = "#";
				switch (notification.type) {
					case "user_got_a_notification":
						break;
					case "user_approved_access_to_year":
					case "user_rejected_access_to_year":
						url = '/dashboard.php';
						break;
					case "user_wants_to_access_a_year":
					case "group_wants_to_undertake_a_project":
					case "user_wants_another_to_join_a_group":
					case "user_wants_to_join_a_group":
						url = '/intents.php?action=view&id=' + notification.intent.id;
						break;
					case "user_approved_another_to_join_a_group":
					case "user_rejected_another_to_join_a_group":
					case "user_joined_a_group":
					case "user_left_a_group":
						url = '/profile.php?type=group&id=' + notification.group.id;
						break;
					case "group_undertaken_project_approved":
					case "group_undertaken_project_rejected":
					case "group_released_project":
						url = '/profile.php?type=project&id=' + notification.project.id;
						break;
				}

				HTML.push('
' + notification.text + '
');
				if (!data.body[i].read) {
					notificationIds.push(data.body[i].id);
				}
			}
		}
		HTML.push(
			'

' +
			'
See All
'
		)
		notificationsList.innerHTML = HTML.join("");
		if (notificationIds > 0) {
			notificationsBadge.innerText = notificationIds.length.toString();
			notificationsBadge.style.display = "block";
			notificationsDropdown.setAttribute('onclick', 'setReadStatus([' + notificationIds + '])');
			updatedReadStatus = false;
		}
		else {
			notificationsBadge.style.display = "none";
		}
	}
	else {
		notificationsList.innerHTML = '
You have no notifications
'
	}
}

function onNotificationsGetError(data) {
	console.error("notificationsThingy onNotificationsGetError", data);
}

function GetNotifications() {
	API.GET("/me/notifications", {}, onNotificationsGetSuccess, onNotificationsGetError);
}

function onCheckNotificationsSuccess(data) {
	//console.log("notificationsThingy onCheckNotificationsSuccess", data);
	if (data.headers && data.headers["X-Notification-Count"] && (data.headers["X-Notification-Count"] > 0)) {
		GetNotifications();
	}
}

function onCheckNotificationsError(data) {
	// Meh. Who cares.
	// console.error("notificationsThingy onCheckNotificationsError", data);
}

function setReadStatus(ids) {
	if(!updatedReadStatus) {
		API.PUT("/me/notifications", {
				ids: ids
			},
			function onNotificationReadStatusUpdateSuccess(data) {
				//console.log(data.body);
				updatedReadStatus = true;
			},
			function onNotificationReadStatusUpdateError() {
				console.error("Failed to update the read status for notifications");
			}
		)
	}
	GetNotifications();
}

function CheckUnreadNotificationInterval() {
	API.HEAD("/me/notifications", {"unread": 1}, onCheckNotificationsSuccess, onCheckNotificationsError);
}

setInterval(CheckUnreadNotificationInterval, 10000);
GetNotifications();<|endoftext|>


<commit_before>import Ember from 'ember';
import { moduleFor, test } from 'ember-qunit';

var steps = [
  {
    id: 'intro',
    options: {
      attachTo: '.test-element bottom',
      builtInButtons: [
        {
          classes: 'shepherd-button-secondary',
          text: 'Exit',
          type: 'cancel'
        },
        {
          classes: 'shepherd-button-primary',
          text: 'Next',
          type: 'next'
        }
      ],
      classes: 'shepherd shepherd-open shepherd-theme-arrows shepherd-transparent-text',
      copyStyles: false,
      title: 'Welcome to Ember-Shepherd!',
      text: ['Test text']
    }
  }
];

var mockTourObject = Ember.Object.createWithMixins(Ember.Evented, {
  start() {
    this.trigger('start');
  }
});

moduleFor('service:tour', {
  afterEach() {
    // Remove start actions
    mockTourObject.off('start');
  }
});

// Replace this with your real tests.
test('it starts the tour when all required properties are available', function(assert) {
  assert.expect(1);

  mockTourObject.on('start', function() {
    assert.ok(true, 'This tour was started');
  });

  var service = this.subject({
    steps: steps,
    _tourObject: mockTourObject
  });

  Ember.run(function() {
    service.trigger('start');
  });

});
<commit_msg>Change test name<commit_after>import Ember from 'ember';
import { moduleFor, test } from 'ember-qunit';

var steps = [
  {
    id: 'intro',
    options: {
      attachTo: '.test-element bottom',
      builtInButtons: [
        {
          classes: 'shepherd-button-secondary',
          text: 'Exit',
          type: 'cancel'
        },
        {
          classes: 'shepherd-button-primary',
          text: 'Next',
          type: 'next'
        }
      ],
      classes: 'shepherd shepherd-open shepherd-theme-arrows shepherd-transparent-text',
      copyStyles: false,
      title: 'Welcome to Ember-Shepherd!',
      text: ['Test text']
    }
  }
];

var mockTourObject = Ember.Object.createWithMixins(Ember.Evented, {
  start() {
    this.trigger('start');
  }
});

moduleFor('service:tour', {
  afterEach() {
    // Remove start actions
    mockTourObject.off('start');
  }
});

// Replace this with your real tests.
test('it starts the tour when the `start` event is triggered', function(assert) {
  assert.expect(1);

  mockTourObject.on('start', function() {
    assert.ok(true, 'This tour was started');
  });

  var service = this.subject({
    steps: steps,
    _tourObject: mockTourObject
  });

  Ember.run(function() {
    service.trigger('start');
  });

});
<|endoftext|>


<commit_before>/*
 * jQuery simple-color plugin
 * @requires jQuery v1.4.2 or later
 *
 * See http://recursive-design.com/projects/jquery-simple-color/
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Version: 1.0.1 (201108151520)
 */
 (function($) {
/**
 * simpleColor() provides a mechanism for displaying simple color-pickers.
 *
 * If an options Object is provided, the following attributes are supported:
 *
 *  defaultColor:       Default (initially selected) color.
 *                       default value: '#FFF'
 *
 *  border:             CSS border properties.
 *                       default value: '1px solid #000'
 *
 *  cellWidth:          Width of each individual color cell.
 *                       default value: 10
 *
 *  cellHeight:         Height of each individual color cell.
 *                       default value: 10
 *
 *  cellMargin:         Margin of each individual color cell.
 *                       default value: 1
 *
 *  boxWidth:           Width of the color display box.
 *                       default value: 115px
 *
 *  boxHeight:          Height of the color display box.
 *                       default value: 20px
 *
 *  columns:            Number of columns to display. Color order may look strange if this is altered.
 *                       default value: 16
 *
 *  insert:             The position to insert the color picker. 'before' or 'after'.
 *                       default value: 'after'
 *
 *  buttonClass:        A custom CSS class to add to the button, if you want to add some custom styling.
 *                       default value: ''
 *
 *  colors:             An array of colors to display, if you want to customize the default color set.
 *                       default value: default color set - see 'default_colors' below.
 *
 *  displayColorCode:   Display the color code (eg #333333) as text inside the button. true or false.
 *                       default value: false
 *
 *  colorCodeAlign:     Text alignment used to display the color code inside the button. Only used if 'displayColorCode' is true. 'left', 'center' or 'right'
 *                       default value: 'center'
 *
 *  colorCodeColor:     Text color of the color code inside the button. Only used if 'displayColorCode' is true.
 *                       default value: '#FFF'
 */
    $.fn.simpleColor = function(options) {

        var default_colors =
        ['ffffff', 'ffffcc', 'ffff99', 'ffff66', 'ffff33', 'ffff00',
         'ccffff', 'ccffcc', 'ccff99', 'ccff66', 'ccff33', 'ccff00',
         '99ffff', '99ffcc', '99ff99', '99ff66', '99ff33', '99ff00',
         '66ffff', '66ffcc', '66ff99', '66ff66', '66ff33', '66ff00',
         '33ffff', '33ffcc', '33ff99', '33ff66', '33ff33', '33ff00',
         '00ffff', '00ffcc', '00ff99', '00ff66', '00ff33', '00ff00',
         'ffccff', 'ffcccc', 'ffcc99', 'ffcc66', 'ffcc33', 'ffcc00',
         'ccccff', 'cccccc', 'cccc99', 'cccc66', 'cccc33', 'cccc00',
         '99ccff', '99cccc', '99cc99', '99cc66', '99cc33', '99cc00',
         '66ccff', '66cccc', '66cc99', '66cc66', '66cc33', '66cc00',
         '33ccff', '33cccc', '33cc99', '33cc66', '33cc33', '33cc00',
         '00ccff', '00cccc', '00cc99', '00cc66', '00cc33', '00cc00',
         'ff99ff', 'ff99cc', 'ff9999', 'ff9966', 'ff9933', 'ff9900',
         'cc99ff', 'cc99cc', 'cc9999', 'cc9966', 'cc9933', 'cc9900',
         '9999ff', '9999cc', '999999', '999966', '999933', '999900',
         '6699ff', '6699cc', '669999', '669966', '669933', '669900',
         '3399ff', '3399cc', '339999', '339966', '339933', '339900',
         '0099ff', '0099cc', '009999', '009966', '009933', '009900',
         'ff66ff', 'ff66cc', 'ff6699', 'ff6666', 'ff6633', 'ff6600',
         'cc66ff', 'cc66cc', 'cc6699', 'cc6666', 'cc6633', 'cc6600',
         '9966ff', '9966cc', '996699', '996666', '996633', '996600',
         '6666ff', '6666cc', '666699', '666666', '666633', '666600',
         '3366ff', '3366cc', '336699', '336666', '336633', '336600',
         '0066ff', '0066cc', '006699', '006666', '006633', '006600',
         'ff33ff', 'ff33cc', 'ff3399', 'ff3366', 'ff3333', 'ff3300',
         'cc33ff', 'cc33cc', 'cc3399', 'cc3366', 'cc3333', 'cc3300',
         '9933ff', '9933cc', '993399', '993366', '993333', '993300',
         '6633ff', '6633cc', '663399', '663366', '663333', '663300',
         '3333ff', '3333cc', '333399', '333366', '333333', '333300',
         '0033ff', '0033cc', '003399', '003366', '003333', '003300',
         'ff00ff', 'ff00cc', 'ff0099', 'ff0066', 'ff0033', 'ff0000',
         'cc00ff', 'cc00cc', 'cc0099', 'cc0066', 'cc0033', 'cc0000',
         '9900ff', '9900cc', '990099', '990066', '990033', '990000',
         '6600ff', '6600cc', '660099', '660066', '660033', '660000',
         '3300ff', '3300cc', '330099', '330066', '330033', '330000',
         '0000ff', '0000cc', '000099', '000066', '000033', '000000'];

        // Option defaults
        options = $.extend({
            defaultColor:     this.attr('defaultColor') || '#FFF',
            border:           this.attr('border') || '1px solid #000',
            cellWidth:        this.attr('cellWidth') || 10,
            cellHeight:       this.attr('cellHeight') || 10,
            cellMargin:       this.attr('cellMargin') || 1,
            boxWidth:         this.attr('boxWidth') || '115px',
            boxHeight:        this.attr('boxHeight') || '20px',
            columns:          this.attr('columns') || 18,
            insert:           this.attr('insert') || 'after',
            buttonClass:      this.attr('buttonClass') || '',
            colors:           this.attr('colors') || default_colors,
            displayColorCode: this.attr('displayColorCode') || false,
            colorCodeAlign:   this.attr('colorCodeAlign') || 'center',
            colorCodeColor:   this.attr('colorCodeColor') || '#FFF'

        }, options || {});

        // Hide the input
        this.hide();

        // Figure out the cell dimensions
        options.totalWidth = options.columns * (options.cellWidth + (2 * options.cellMargin));
        if ($.browser.msie) {
            options.totalWidth += 2;
        }

        options.totalHeight = Math.ceil(options.colors.length / options.columns) * (options.cellHeight + (2 * options.cellMargin));

        // Store these options so they'll be available to the other functions
        // TODO - must be a better way to do this, not sure what the 'official'
        // jQuery method is. Ideally i want to pass these as a parameter to the
        // each() function but i'm not sure how
        $.simpleColorOptions = options;

        function buildSelector(index) {

            var options = $.simpleColorOptions;

            // Create a container to hold everything
            var container = $("
");

            // Create the color display box
            var default_color = (this.value && this.value != '') ? this.value : options.defaultColor;

            var display_box = $("
");
            display_box.css('backgroundColor', default_color);
            display_box.css('border',          options.border);
            display_box.css('width',           options.boxWidth);
            display_box.css('height',          options.boxHeight);
            display_box.css('cursor',          'pointer');
            container.append(display_box);

            // If 'displayColorCode' is turned on, display the currently selected color code as text inside the button.
            if (options.displayColorCode) {
                display_box.text(this.value);
                display_box.css('color',     options.colorCodeColor);
                display_box.css('textAlign', options.colorCodeAlign);
            }

            var select_callback = function (event) {

               // Use an existing chooser if there is one
               if (event.data.container.chooser) {
                   event.data.container.chooser.show();

               // Build the chooser
               } else {

                   // Make a chooser div to hold the cells
                   var chooser = $("
");
                   chooser.css('border',  options.border);
                   chooser.css('margin',  '0px');
                   chooser.css('margin-top',  '3px');
                   chooser.css('width',   options.totalWidth + 'px');
                   chooser.css('height',  options.totalHeight + 'px');

                   event.data.container.chooser = chooser;
                   event.data.container.append(chooser);

                   // Create the cells
                   for (var i=0; i<options.colors.length; i++) {
                       var cell = $("
");
                       cell.css('width',           options.cellWidth + 'px');
                       cell.css('height',          options.cellHeight + 'px');
                       cell.css('margin',          options.cellMargin + 'px');
                       cell.css('cursor',          'pointer');
                       cell.css('lineHeight',      options.cellHeight + 'px');
                       cell.css('fontSize',        '1px');
                       cell.css('float',           'left');
                       cell.css('backgroundColor', '#'+options.colors[i]);
                       chooser.append(cell);

                       cell.bind('click', {
                               input: event.data.input,
                               chooser: chooser,
                               display_box: display_box},
                           function(event) {
                               event.data.input.value = '#' + this.id;
                               $(event.data.input).change();
                               event.data.display_box.css('backgroundColor', '#' + this.id);
                               event.data.chooser.hide();
                               event.data.display_box.show();

                               // If 'displayColorCode' is turned on, display the currently selected color code as text inside the button.
                               if (options.displayColorCode) {
                                   event.data.display_box.text('#' + this.id);
                               }
                           }
                       );
                   }
               }
           };

           var callback_params = {
               container: container,
               input: this,
               display_box: display_box,
           };

           // Bind the display box button to display the chooser.
           display_box.bind('click', callback_params, select_callback);

            $(this).after(container);

        };

        this.each(buildSelector);

        return this;
    };

    /*
     * Close the given color selectors
     */
    $.fn.closeSelector = function() {
        this.each( function(index) {
            var container = $(this).parent().find('div.simpleColorContainer');
            container.find('.simpleColorChooser').hide();
            container.find('.simpleColorDisplay').show();
        });

        return this;
    };

})(jQuery);
<commit_msg>add a line of greys to make it easy to find one - fixes S4665<commit_after>/*
 * jQuery simple-color plugin
 * @requires jQuery v1.4.2 or later
 *
 * See http://recursive-design.com/projects/jquery-simple-color/
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Version: 1.0.1 (201108151520)
 */
 (function($) {
/**
 * simpleColor() provides a mechanism for displaying simple color-pickers.
 *
 * If an options Object is provided, the following attributes are supported:
 *
 *  defaultColor:       Default (initially selected) color.
 *                       default value: '#FFF'
 *
 *  border:             CSS border properties.
 *                       default value: '1px solid #000'
 *
 *  cellWidth:          Width of each individual color cell.
 *                       default value: 10
 *
 *  cellHeight:         Height of each individual color cell.
 *                       default value: 10
 *
 *  cellMargin:         Margin of each individual color cell.
 *                       default value: 1
 *
 *  boxWidth:           Width of the color display box.
 *                       default value: 115px
 *
 *  boxHeight:          Height of the color display box.
 *                       default value: 20px
 *
 *  columns:            Number of columns to display. Color order may look strange if this is altered.
 *                       default value: 16
 *
 *  insert:             The position to insert the color picker. 'before' or 'after'.
 *                       default value: 'after'
 *
 *  buttonClass:        A custom CSS class to add to the button, if you want to add some custom styling.
 *                       default value: ''
 *
 *  colors:             An array of colors to display, if you want to customize the default color set.
 *                       default value: default color set - see 'default_colors' below.
 *
 *  displayColorCode:   Display the color code (eg #333333) as text inside the button. true or false.
 *                       default value: false
 *
 *  colorCodeAlign:     Text alignment used to display the color code inside the button. Only used if 'displayColorCode' is true. 'left', 'center' or 'right'
 *                       default value: 'center'
 *
 *  colorCodeColor:     Text color of the color code inside the button. Only used if 'displayColorCode' is true.
 *                       default value: '#FFF'
 */
    $.fn.simpleColor = function(options) {

        var default_colors =
        ['ffffff', 'ffffcc', 'ffff99', 'ffff66', 'ffff33', 'ffff00',
         'ccffff', 'ccffcc', 'ccff99', 'ccff66', 'ccff33', 'ccff00',
         '99ffff', '99ffcc', '99ff99', '99ff66', '99ff33', '99ff00',
         '66ffff', '66ffcc', '66ff99', '66ff66', '66ff33', '66ff00',
         '33ffff', '33ffcc', '33ff99', '33ff66', '33ff33', '33ff00',
         '00ffff', '00ffcc', '00ff99', '00ff66', '00ff33', '00ff00',
         'ffccff', 'ffcccc', 'ffcc99', 'ffcc66', 'ffcc33', 'ffcc00',
         'ccccff', 'cccccc', 'cccc99', 'cccc66', 'cccc33', 'cccc00',
         '99ccff', '99cccc', '99cc99', '99cc66', '99cc33', '99cc00',
         '66ccff', '66cccc', '66cc99', '66cc66', '66cc33', '66cc00',
         '33ccff', '33cccc', '33cc99', '33cc66', '33cc33', '33cc00',
         '00ccff', '00cccc', '00cc99', '00cc66', '00cc33', '00cc00',
         'ff99ff', 'ff99cc', 'ff9999', 'ff9966', 'ff9933', 'ff9900',
         'cc99ff', 'cc99cc', 'cc9999', 'cc9966', 'cc9933', 'cc9900',
         '9999ff', '9999cc', '999999', '999966', '999933', '999900',
         '6699ff', '6699cc', '669999', '669966', '669933', '669900',
         '3399ff', '3399cc', '339999', '339966', '339933', '339900',
         '0099ff', '0099cc', '009999', '009966', '009933', '009900',
         'ff66ff', 'ff66cc', 'ff6699', 'ff6666', 'ff6633', 'ff6600',
         'cc66ff', 'cc66cc', 'cc6699', 'cc6666', 'cc6633', 'cc6600',
         '9966ff', '9966cc', '996699', '996666', '996633', '996600',
         '6666ff', '6666cc', '666699', '666666', '666633', '666600',
         '3366ff', '3366cc', '336699', '336666', '336633', '336600',
         '0066ff', '0066cc', '006699', '006666', '006633', '006600',
         'ff33ff', 'ff33cc', 'ff3399', 'ff3366', 'ff3333', 'ff3300',
         'cc33ff', 'cc33cc', 'cc3399', 'cc3366', 'cc3333', 'cc3300',
         '9933ff', '9933cc', '993399', '993366', '993333', '993300',
         '6633ff', '6633cc', '663399', '663366', '663333', '663300',
         '3333ff', '3333cc', '333399', '333366', '333333', '333300',
         '0033ff', '0033cc', '003399', '003366', '003333', '003300',
         'ff00ff', 'ff00cc', 'ff0099', 'ff0066', 'ff0033', 'ff0000',
         'cc00ff', 'cc00cc', 'cc0099', 'cc0066', 'cc0033', 'cc0000',
         '9900ff', '9900cc', '990099', '990066', '990033', '990000',
         '6600ff', '6600cc', '660099', '660066', '660033', '660000',
         '3300ff', '3300cc', '330099', '330066', '330033', '330000',
         '0000ff', '0000cc', '000099', '000066', '000033', '000000',
         'ffffff', 'eeeeee', 'dddddd', 'cccccc', 'bbbbbb', 'aaaaaa',
         '999999', '888888', '777777', '666666', '555555', '444444',
         '333333', '222222', '111111', '000000', '000000', '000000'];

        // Option defaults
        options = $.extend({
            defaultColor:     this.attr('defaultColor') || '#FFF',
            border:           this.attr('border') || '1px solid #000',
            cellWidth:        this.attr('cellWidth') || 10,
            cellHeight:       this.attr('cellHeight') || 10,
            cellMargin:       this.attr('cellMargin') || 1,
            boxWidth:         this.attr('boxWidth') || '115px',
            boxHeight:        this.attr('boxHeight') || '20px',
            columns:          this.attr('columns') || 18,
            insert:           this.attr('insert') || 'after',
            buttonClass:      this.attr('buttonClass') || '',
            colors:           this.attr('colors') || default_colors,
            displayColorCode: this.attr('displayColorCode') || false,
            colorCodeAlign:   this.attr('colorCodeAlign') || 'center',
            colorCodeColor:   this.attr('colorCodeColor') || '#FFF'

        }, options || {});

        // Hide the input
        this.hide();

        // Figure out the cell dimensions
        options.totalWidth = options.columns * (options.cellWidth + (2 * options.cellMargin));
        if ($.browser.msie) {
            options.totalWidth += 2;
        }

        options.totalHeight = Math.ceil(options.colors.length / options.columns) * (options.cellHeight + (2 * options.cellMargin));

        // Store these options so they'll be available to the other functions
        // TODO - must be a better way to do this, not sure what the 'official'
        // jQuery method is. Ideally i want to pass these as a parameter to the
        // each() function but i'm not sure how
        $.simpleColorOptions = options;

        function buildSelector(index) {

            var options = $.simpleColorOptions;

            // Create a container to hold everything
            var container = $("
");

            // Create the color display box
            var default_color = (this.value && this.value != '') ? this.value : options.defaultColor;

            var display_box = $("
");
            display_box.css('backgroundColor', default_color);
            display_box.css('border',          options.border);
            display_box.css('width',           options.boxWidth);
            display_box.css('height',          options.boxHeight);
            display_box.css('cursor',          'pointer');
            container.append(display_box);

            // If 'displayColorCode' is turned on, display the currently selected color code as text inside the button.
            if (options.displayColorCode) {
                display_box.text(this.value);
                display_box.css('color',     options.colorCodeColor);
                display_box.css('textAlign', options.colorCodeAlign);
            }

            var select_callback = function (event) {

               // Use an existing chooser if there is one
               if (event.data.container.chooser) {
                   event.data.container.chooser.show();

               // Build the chooser
               } else {

                   // Make a chooser div to hold the cells
                   var chooser = $("
");
                   chooser.css('border',  options.border);
                   chooser.css('margin',  '0px');
                   chooser.css('margin-top',  '3px');
                   chooser.css('width',   options.totalWidth + 'px');
                   chooser.css('height',  options.totalHeight + 'px');

                   event.data.container.chooser = chooser;
                   event.data.container.append(chooser);

                   // Create the cells
                   for (var i=0; i<options.colors.length; i++) {
                       var cell = $("
");
                       cell.css('width',           options.cellWidth + 'px');
                       cell.css('height',          options.cellHeight + 'px');
                       cell.css('margin',          options.cellMargin + 'px');
                       cell.css('cursor',          'pointer');
                       cell.css('lineHeight',      options.cellHeight + 'px');
                       cell.css('fontSize',        '1px');
                       cell.css('float',           'left');
                       cell.css('backgroundColor', '#'+options.colors[i]);
                       chooser.append(cell);

                       cell.bind('click', {
                               input: event.data.input,
                               chooser: chooser,
                               display_box: display_box},
                           function(event) {
                               event.data.input.value = '#' + this.id;
                               $(event.data.input).change();
                               event.data.display_box.css('backgroundColor', '#' + this.id);
                               event.data.chooser.hide();
                               event.data.display_box.show();

                               // If 'displayColorCode' is turned on, display the currently selected color code as text inside the button.
                               if (options.displayColorCode) {
                                   event.data.display_box.text('#' + this.id);
                               }
                           }
                       );
                   }
               }
           };

           var callback_params = {
               container: container,
               input: this,
               display_box: display_box,
           };

           // Bind the display box button to display the chooser.
           display_box.bind('click', callback_params, select_callback);

            $(this).after(container);

        };

        this.each(buildSelector);

        return this;
    };

    /*
     * Close the given color selectors
     */
    $.fn.closeSelector = function() {
        this.each( function(index) {
            var container = $(this).parent().find('div.simpleColorContainer');
            container.find('.simpleColorChooser').hide();
            container.find('.simpleColorDisplay').show();
        });

        return this;
    };

})(jQuery);
<|endoftext|>


<commit_before>mapApp.factory("MapService",
    function () {
        var map = null;

        var platform = new H.service.Platform({
            app_id: "wLWuweij9RTP8EtgUKYc",
            app_code: "s4gqVLTvBeEDQMiSECS8WQ",
            useCIT: true,
            useHTTPS: false
        });

        var defaultLayers = platform.createDefaultLayers();

        return {
            initializeMap: function() {
                var mapDiv = document.getElementById("map");
                mapDiv.innerHTML = ""; // HACK: How can I update the map with HERE properties?

                map = new H.Map(mapDiv,
                    defaultLayers.normal.map, {
                    center: {
                        lat: 52,
                        lng: 5
                        },
                    zoom: 5
                });

                var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
                var ui = H.ui.UI.createDefault(map, defaultLayers);
            },

            drawRouteInMap: function(data) {
                var route,
                    routeShape,
                    strip,
                    markers;

                if(data.response.route) {
                    route = data.response.route[0];
                    routeShape = route.shape;
                    strip = new H.geo.Strip();

                    routeShape.forEach(function(point) {
                        var parts = point.split(',');
                        strip.pushLatLngAlt(parts[0], parts[1]);
                    });

                    markers = [];
                    for (var i=0; i<route.waypoint.length; i++) {
                        markers[i] = route.waypoint[i].mappedPosition;
                    }

                    var routeLine = new H.map.Polyline(strip, {
                        style: {
                            strokeColor: 'blue',
                            lineWidth: 4
                            }
                    });

                    this.initializeMap();
                    map.addObject(routeLine);

                    for (var i=0; i<markers.length; i++) {
                        map.addObject(new H.map.Marker({
                            lat: markers[i].latitude,
                            lng: markers[i].longitude
                        }));
                    }
                    map.setViewBounds(routeLine.getBounds());
                } else {
                    throw new Error("An unexpected error happened. Please try again!");
                }
            }
        }
    }
);<commit_msg>remove the previous route with the proper HERE function instead of emptying the map. The change should also affect performance for the better<commit_after>mapApp.factory("MapService",
    function () {
        var map = null;

        var platform = new H.service.Platform({
            app_id: "wLWuweij9RTP8EtgUKYc",
            app_code: "s4gqVLTvBeEDQMiSECS8WQ",
            useCIT: true,
            useHTTPS: false
        });

        var defaultLayers = platform.createDefaultLayers();
        var previousRouteLine = null;

        return {
            initializeMap: function() {
                var mapDiv = document.getElementById("map");

                map = new H.Map(mapDiv,
                    defaultLayers.normal.map, {
                    center: {
                        lat: 52,
                        lng: 5
                        },
                    zoom: 5
                });

                var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
                var ui = H.ui.UI.createDefault(map, defaultLayers);
            },

            drawRouteInMap: function(data) {
                var route,
                    routeShape,
                    strip,
                    markers;

                if(data.response.route) {
                    route = data.response.route[0];
                    routeShape = route.shape;
                    strip = new H.geo.Strip();

                    routeShape.forEach(function(point) {
                        var parts = point.split(',');
                        strip.pushLatLngAlt(parts[0], parts[1]);
                    });

                    markers = [];
                    for (var i=0; i<route.waypoint.length; i++) {
                        markers[i] = route.waypoint[i].mappedPosition;
                    }

                    var routeLine = new H.map.Polyline(strip, {
                        style: {
                            strokeColor: 'blue',
                            lineWidth: 4
                            }
                    });

                    if (previousRouteLine) {
                        map.removeObject(previousRouteLine);
                    }

                    map.addObject(routeLine);
                    previousRouteLine = routeLine;

                    for (var i=0; i<markers.length; i++) {
                        map.addObject(new H.map.Marker({
                            lat: markers[i].latitude,
                            lng: markers[i].longitude
                        }));
                    }
                    map.setViewBounds(routeLine.getBounds());
                } else {
                    throw new Error("An unexpected error happened. Please try again!");
                }
            }
        }
    }
);<|endoftext|>