<commit_before>/* global app, Backbone, _, jQuery */
/**
 * Talkilla Backbone views.
 */
/* jshint unused: vars */
(function(app, Backbone, _, $) {
  "use strict";

  /**
   * Chat View (overall)
   */
  app.views.ChatView = Backbone.View.extend({
    initialize: function(options) {
      options = options || {};
      if (!options.call)
        throw new Error("missing parameter: call");

      this.call = options.call;

      this.call.on('change:otherUser', function(to) {
        document.title = to.get("otherUser");
      });

      this.call.on('offer-timeout', function() {
        // outgoing call didn't go through, close the window
        window.close();
      });
    }
  });

  /**
   * Call offer view
   */
  app.views.CallOfferView = Backbone.View.extend({
    el: "#offer",

    events: {
      'click .btn-accept': 'accept',
      'click .btn-ignore': 'ignore'
    },

    initialize: function(options) {
      options = options || {};
      if (!options.call)
        throw new Error("missing parameter: call");

      this.call = options.call;

      options.call.on('change:state', function(to, from) {
        if (to === "incoming")
          this.$el.show();
        else if (from === "incoming")
          this.$el.hide();

        this.render();
      }.bind(this));
    },

    accept: function(event) {
      if (event)
        event.preventDefault();

      this.call.accept();
    },

    ignore: function(event) {
      if (event)
        event.preventDefault();

      this.call.ignore();

      window.close();
    },

    render: function() {
      // XXX: update caller's avatar, though we'd need to access otherUser
      //      as a User model instance
      return this;
    }
  });

  /**
   * Call establish view
   */
  app.views.CallEstablishView = Backbone.View.extend({
    el: "#establish",

    events: {
      'click .btn-abort': '_abort'
    },

    initialize: function(options) {
      options = options || {};
      if (!options.call)
        throw new Error("missing parameter: call");

      this.call = options.call;

      this.call.on("change:state", this._handleStateChanges.bind(this));
    },

    _handleStateChanges: function(to, from) {
      if (to === "pending" && from === "ready") {
        this.$el.show();
      } else if (to !== "pending" && from === "pending") {
        this.$el.hide();
      }

      this.render();
    },

    _abort: function(event) {
      if (event) {
        event.preventDefault();
      }

      window.close();
    },

    render: function() {
      // XXX: update caller's avatar, though we'd need to access otherUser
      //      as a User model instance
      return this;
    }
  });

  /**
   * Video/Audio Call View
   */
  app.views.CallView = Backbone.View.extend({

    events: {
      'click .btn-hangup a': 'hangup'
    },

    initialize: function(options) {
      options = options || {};
      if (!options.call)
        throw new Error("missing parameter: call");
      if (!options.el)
        throw new Error("missing parameter: el");

      this.call = options.call;
      this.call.media.on('change:localStream', this._displayLocalVideo, this);
      this.call.media.on('change:remoteStream', this._displayRemoteVideo, this);

      options.call.on('change:state', function(to) {
        if (to === "ongoing")
          this.ongoing();
        else if (to === "terminated")
          this.terminated();
      }, this);
    },

    hangup: function(event) {
      if (event)
        event.preventDefault();

      window.close(); // XXX: actually terminate the call and leave the
                      // conversation window open (eg. for text chat)
    },

    ongoing: function() {
      this.$el.show();
      this.$('.btn-video').hide();
      this.$('.btn-audio').hide();
      this.$('.btn-hangup').show();
    },

    terminated: function() {
      this.$el.hide();
      this.$('.btn-video').show();
      this.$('.btn-audio').show();
      this.$('.btn-hangup').hide();
    },

    _displayLocalVideo: function() {
      var localVideo = this.$('#local-video')[0];
      if (!localVideo)
        return this;
      var localStream = this.call.media.get("localStream");
      localVideo.mozSrcObject = localStream;
      localVideo.play();
      return this;
    },

    _displayRemoteVideo: function() {
      var remoteVideo = this.$('#remote-video')[0];
      var remoteStream = this.call.media.get("remoteStream");

      remoteVideo.mozSrcObject = remoteStream;
      remoteVideo.play();
      return this;
    }
  });

  /**
   * Text chat entry view.
   */
  app.views.TextChatEntryView = Backbone.View.extend({
    tagName: 'li',

    template: _.template('<%= nick %>: <%= message %>'),

    render: function() {
      this.$el.html(this.template(this.model.toJSON()));
      return this;
    }
  });

  /**
   * Text chat conversation view.
   */
  app.views.TextChatView = Backbone.View.extend({
    el: '#textchat', // XXX: uncouple the selector from this view

    events: {
      'submit form': 'send'
    },

    initialize: function(options) {
      if (!options.call)
        throw new Error("missing parameter: call");
      if (!options.collection)
        throw new Error("missing parameter: collection");

      this.collection = options.collection;
      this.call = options.call;
      this.media = options.call.media;

      this.collection.on('add', this.render, this);

      this.media.on('dc.in.ready', function() {
        this.$('input').removeAttr('disabled');
      }, this);

      this.call.on('change:state', function(to) {
        if (to === "ongoing")
          this.$el.show();
        else if (to !== "ongoing")
          this.$el.hide();
      }.bind(this));
    },

    send: function(event) {
      event.preventDefault();
      var $input = this.$('form input[name="message"]');
      var message = $input.val().trim();
      $input.val('');
      this.collection.newEntry({
        nick: app.data.user.get("nick"),
        message: message
      });
    },

    render: function() {
      var $ul = this.$('ul').empty();
      this.collection.each(function(entry) {
        var view = new app.views.TextChatEntryView({model: entry});
        $ul.append(view.render().$el);
      });
      var ul = $ul.get(0);
      ul.scrollTop = ul.scrollTopMax;
      return this;
    }
  });
})(app, Backbone, _, jQuery);
<commit_msg>Remove unnecessary curly braces to fit with style guide; fixes previous review comment<commit_after>/* global app, Backbone, _, jQuery */
/**
 * Talkilla Backbone views.
 */
/* jshint unused: vars */
(function(app, Backbone, _, $) {
  "use strict";

  /**
   * Chat View (overall)
   */
  app.views.ChatView = Backbone.View.extend({
    initialize: function(options) {
      options = options || {};
      if (!options.call)
        throw new Error("missing parameter: call");

      this.call = options.call;

      this.call.on('change:otherUser', function(to) {
        document.title = to.get("otherUser");
      });

      this.call.on('offer-timeout', function() {
        // outgoing call didn't go through, close the window
        window.close();
      });
    }
  });

  /**
   * Call offer view
   */
  app.views.CallOfferView = Backbone.View.extend({
    el: "#offer",

    events: {
      'click .btn-accept': 'accept',
      'click .btn-ignore': 'ignore'
    },

    initialize: function(options) {
      options = options || {};
      if (!options.call)
        throw new Error("missing parameter: call");

      this.call = options.call;

      options.call.on('change:state', function(to, from) {
        if (to === "incoming")
          this.$el.show();
        else if (from === "incoming")
          this.$el.hide();

        this.render();
      }.bind(this));
    },

    accept: function(event) {
      if (event)
        event.preventDefault();

      this.call.accept();
    },

    ignore: function(event) {
      if (event)
        event.preventDefault();

      this.call.ignore();

      window.close();
    },

    render: function() {
      // XXX: update caller's avatar, though we'd need to access otherUser
      //      as a User model instance
      return this;
    }
  });

  /**
   * Call establish view
   */
  app.views.CallEstablishView = Backbone.View.extend({
    el: "#establish",

    events: {
      'click .btn-abort': '_abort'
    },

    initialize: function(options) {
      options = options || {};
      if (!options.call)
        throw new Error("missing parameter: call");

      this.call = options.call;

      this.call.on("change:state", this._handleStateChanges.bind(this));
    },

    _handleStateChanges: function(to, from) {
      if (to === "pending" && from === "ready") {
        this.$el.show();
      } else if (to !== "pending" && from === "pending") {
        this.$el.hide();
      }

      this.render();
    },

    _abort: function(event) {
      if (event)
        event.preventDefault();

      window.close();
    },

    render: function() {
      // XXX: update caller's avatar, though we'd need to access otherUser
      //      as a User model instance
      return this;
    }
  });

  /**
   * Video/Audio Call View
   */
  app.views.CallView = Backbone.View.extend({

    events: {
      'click .btn-hangup a': 'hangup'
    },

    initialize: function(options) {
      options = options || {};
      if (!options.call)
        throw new Error("missing parameter: call");
      if (!options.el)
        throw new Error("missing parameter: el");

      this.call = options.call;
      this.call.media.on('change:localStream', this._displayLocalVideo, this);
      this.call.media.on('change:remoteStream', this._displayRemoteVideo, this);

      options.call.on('change:state', function(to) {
        if (to === "ongoing")
          this.ongoing();
        else if (to === "terminated")
          this.terminated();
      }, this);
    },

    hangup: function(event) {
      if (event)
        event.preventDefault();

      window.close(); // XXX: actually terminate the call and leave the
                      // conversation window open (eg. for text chat)
    },

    ongoing: function() {
      this.$el.show();
      this.$('.btn-video').hide();
      this.$('.btn-audio').hide();
      this.$('.btn-hangup').show();
    },

    terminated: function() {
      this.$el.hide();
      this.$('.btn-video').show();
      this.$('.btn-audio').show();
      this.$('.btn-hangup').hide();
    },

    _displayLocalVideo: function() {
      var localVideo = this.$('#local-video')[0];
      if (!localVideo)
        return this;
      var localStream = this.call.media.get("localStream");
      localVideo.mozSrcObject = localStream;
      localVideo.play();
      return this;
    },

    _displayRemoteVideo: function() {
      var remoteVideo = this.$('#remote-video')[0];
      var remoteStream = this.call.media.get("remoteStream");

      remoteVideo.mozSrcObject = remoteStream;
      remoteVideo.play();
      return this;
    }
  });

  /**
   * Text chat entry view.
   */
  app.views.TextChatEntryView = Backbone.View.extend({
    tagName: 'li',

    template: _.template('<%= nick %>: <%= message %>'),

    render: function() {
      this.$el.html(this.template(this.model.toJSON()));
      return this;
    }
  });

  /**
   * Text chat conversation view.
   */
  app.views.TextChatView = Backbone.View.extend({
    el: '#textchat', // XXX: uncouple the selector from this view

    events: {
      'submit form': 'send'
    },

    initialize: function(options) {
      if (!options.call)
        throw new Error("missing parameter: call");
      if (!options.collection)
        throw new Error("missing parameter: collection");

      this.collection = options.collection;
      this.call = options.call;
      this.media = options.call.media;

      this.collection.on('add', this.render, this);

      this.media.on('dc.in.ready', function() {
        this.$('input').removeAttr('disabled');
      }, this);

      this.call.on('change:state', function(to) {
        if (to === "ongoing")
          this.$el.show();
        else if (to !== "ongoing")
          this.$el.hide();
      }.bind(this));
    },

    send: function(event) {
      event.preventDefault();
      var $input = this.$('form input[name="message"]');
      var message = $input.val().trim();
      $input.val('');
      this.collection.newEntry({
        nick: app.data.user.get("nick"),
        message: message
      });
    },

    render: function() {
      var $ul = this.$('ul').empty();
      this.collection.each(function(entry) {
        var view = new app.views.TextChatEntryView({model: entry});
        $ul.append(view.render().$el);
      });
      var ul = $ul.get(0);
      ul.scrollTop = ul.scrollTopMax;
      return this;
    }
  });
})(app, Backbone, _, jQuery);
<|endoftext|>


<commit_before>function capture(video, canvas, image, captureButton, stopButton, snapshotButton) {
	var ctx = canvas.getContext('2d');
	var localMediaStream = null;
	var track = null;

	captureButton.disabled = true;
	stopButton.disabled = false;
	snapshotButton.disabled = false;

	stopButton.onclick = function () {
		stop(video);
	};

	window.URL = window.URL || window.webkitURL;
	navigator.getUserMedia  = navigator.getUserMedia || navigator.webkitGetUserMedia ||
						  navigator.mozGetUserMedia || navigator.msGetUserMedia;

	var constraints = {
		video: true
	}

	var successCallback = function(mediaStream) {
		video.src = (window.URL && window.URL.createObjectURL(mediaStream)) || mediaStream;
		video.addEventListener("loadedmetadata", function(e) {
			video.style.display = "block";
			localMediaStream = mediaStream;
			track = localMediaStream.getTracks()[0];
			snapshotButton.onclick = function(event) {
				takePhoto();
				var dataURL = canvas.toDataURL(image/jpeg);
console.log(dataURL);
				//Confirmation for photo
				notie.confirm('Do you want to use this as your Photo of the Day?', 'Yes', 'Cancel', function()
                {
                	notie.alert(1, 'Good choice!', 2);
                });
			}
		});
	};

	var errorCallback = function() {
		console.log("failure to get media");
	};

	var takePhoto = function () {
		ctx.drawImage(video, 0, 0, 320, 240);
		canvas.style.display = "block";
		showImage();
	};

	var showImage = function () {
		image.src = canvas.toDataURL('image/webp');
		image.style.display = "none";
	};

	var stop = function () {
		if (localMediaStream) {
			track.stop(); /* TODO: it doesn't work in Opera Mobile 12 */
		}

		captureButton.disabled = false;
		stopButton.disabled = true;
		snapshotButton.disabled = true;
	};

	if (navigator.getUserMedia) {
		navigator.getUserMedia(constraints, successCallback, errorCallback);
	} else {
		console.log("getUserMedia not supported");
	}
}

function getConfirmation(){
   var retVal = confirm("Do you want to use this photo for your Photo of the Day?");
   if( retVal == true ){
      //document.write ("User wants to use photo!");
      return true;
   }
   else{
      //document.write ("User does not want to use photo!");
      return false;
   }
}

function upload(file) {
  var form = new FormData(),
      xhr = new XMLHttpRequest();

  form.append('image', file);
  xhr.open('post', 'server.php', true);
  xhr.send(form);
}

function init() {
	var video = document.querySelector('video#getUserMedia');
	var canvas = document.querySelector('#canvas');
	var snapshot = document.querySelector('#snapshot');
	var captureButton = document.querySelector('#captureButton');
	var stopButton = document.querySelector('#stopButton');
	var snapshotButton = document.querySelector('#snapshotButton');

	captureButton.onclick = function () {
		capture(video, canvas, snapshot, captureButton, stopButton, snapshotButton);
	};
}<commit_msg>Same image as jpeg<commit_after>function capture(video, canvas, image, captureButton, stopButton, snapshotButton) {
	var ctx = canvas.getContext('2d');
	var localMediaStream = null;
	var track = null;

	captureButton.disabled = true;
	stopButton.disabled = false;
	snapshotButton.disabled = false;

	stopButton.onclick = function () {
		stop(video);
	};

	window.URL = window.URL || window.webkitURL;
	navigator.getUserMedia  = navigator.getUserMedia || navigator.webkitGetUserMedia ||
						  navigator.mozGetUserMedia || navigator.msGetUserMedia;

	var constraints = {
		video: true
	}

	var successCallback = function(mediaStream) {
		video.src = (window.URL && window.URL.createObjectURL(mediaStream)) || mediaStream;
		video.addEventListener("loadedmetadata", function(e) {
			video.style.display = "block";
			localMediaStream = mediaStream;
			track = localMediaStream.getTracks()[0];
			snapshotButton.onclick = function(event) {
				takePhoto();
				var dataURL = canvas.toDataURL("image/jpeg");
console.log(dataURL);
				//Confirmation for photo
				notie.confirm('Do you want to use this as your Photo of the Day?', 'Yes', 'Cancel', function()
                {
                	notie.alert(1, 'Good choice!', 2);
                });
			}
		});
	};

	var errorCallback = function() {
		console.log("failure to get media");
	};

	var takePhoto = function () {
		ctx.drawImage(video, 0, 0, 320, 240);
		canvas.style.display = "block";
		showImage();
	};

	var showImage = function () {
		image.src = canvas.toDataURL('image/webp');
		image.style.display = "none";
	};

	var stop = function () {
		if (localMediaStream) {
			track.stop(); /* TODO: it doesn't work in Opera Mobile 12 */
		}

		captureButton.disabled = false;
		stopButton.disabled = true;
		snapshotButton.disabled = true;
	};

	if (navigator.getUserMedia) {
		navigator.getUserMedia(constraints, successCallback, errorCallback);
	} else {
		console.log("getUserMedia not supported");
	}
}

function getConfirmation(){
   var retVal = confirm("Do you want to use this photo for your Photo of the Day?");
   if( retVal == true ){
      //document.write ("User wants to use photo!");
      return true;
   }
   else{
      //document.write ("User does not want to use photo!");
      return false;
   }
}

function upload(file) {
  var form = new FormData(),
      xhr = new XMLHttpRequest();

  form.append('image', file);
  xhr.open('post', 'server.php', true);
  xhr.send(form);
}

function init() {
	var video = document.querySelector('video#getUserMedia');
	var canvas = document.querySelector('#canvas');
	var snapshot = document.querySelector('#snapshot');
	var captureButton = document.querySelector('#captureButton');
	var stopButton = document.querySelector('#stopButton');
	var snapshotButton = document.querySelector('#snapshotButton');

	captureButton.onclick = function () {
		capture(video, canvas, snapshot, captureButton, stopButton, snapshotButton);
	};
}<|endoftext|>


<commit_before>function init(){
  var sections = ['home','about','services','references','contact'];
  var sectionPositions = [];
  var autoScroll = false;

  var parseHash = function() {
    if(window.location.hash)
      return window.location.hash.slice(window.location.hash.indexOf('!')+1);
    else
      return null;
  };

  var scroll = function(divId) {
    if(divId && $('#'+divId).length){
      autoScroll = true;
      $("html, body").animate({ scrollTop: $('#'+divId).offset().top }, 1000, function(){
        autoScroll = false;
      });
    }
    else
      console.error('Section ' + divId + ' not found!');
  };

  var activateNavLink = function(href) {
    var navLinks = $('.navbar-dbf .nav-menu li');
    navLinks.each(function(key,navLink){
      navLink = $(navLink);
      navLink.removeClass('active');
      if(navLink.find('a').attr('href') == href)
        navLink.addClass('active');
    });
  };

  var findCurrentScrollSection = function(i) {
    var pos = window.scrollY;
    if(i < sectionPositions.length) {
      if(pos >= sectionPositions[i].pos) {
        if(!sectionPositions[i+1] || pos < sectionPositions[i+1].pos)
          return sectionPositions[i].id;
        else
          return findCurrentScrollSection(i+1);
      }
    }
  };

  window.onhashchange = function() {
    scroll(parseHash());
    activateNavLink(window.location.hash);
  };

  window.onscroll = function(){
    if(!autoScroll){
      section = findCurrentScrollSection(0);
      if(section)
        activateNavLink('#!'+section);
    }
  };

  sections.forEach(function(val){
    sectionPositions.push({id: val, pos: $('#'+val).offset().top});
  });

  // first nav.
  scroll(parseHash());
}

init();
<commit_msg>scroll nav change optimization: offset added.<commit_after>function init(){
  var sections = ['home','about','services','references','contact'];
  var sectionPositions = [];
  var autoScroll = false;
  var sectionOffset = 100;

  var parseHash = function() {
    if(window.location.hash)
      return window.location.hash.slice(window.location.hash.indexOf('!')+1);
    else
      return null;
  };

  var scroll = function(divId) {
    if(divId && $('#'+divId).length){
      autoScroll = true;
      $("html, body").animate({ scrollTop: $('#'+divId).offset().top }, 1000, function(){
        autoScroll = false;
      });
    }
    else
      console.error('Section ' + divId + ' not found!');
  };

  var activateNavLink = function(href) {
    var navLinks = $('.navbar-dbf .nav-menu li');
    navLinks.each(function(key,navLink){
      navLink = $(navLink);
      navLink.removeClass('active');
      if(navLink.find('a').attr('href') == href)
        navLink.addClass('active');
    });
  };

  var findCurrentScrollSection = function(i) {
    var pos = window.scrollY;
    if(i < sectionPositions.length) {
      if(pos >= sectionPositions[i].pos - sectionOffset) {
        if(!sectionPositions[i+1] || pos < sectionPositions[i+1].pos - sectionOffset)
          return sectionPositions[i].id;
        else
          return findCurrentScrollSection(i+1);
      }
    }
  };

  window.onhashchange = function() {
    scroll(parseHash());
    activateNavLink(window.location.hash);
  };

  window.onscroll = function(){
    if(!autoScroll){
      section = findCurrentScrollSection(0);
      if(section)
        activateNavLink('#!'+section);
    }
  };

  sections.forEach(function(val){
    sectionPositions.push({id: val, pos: $('#'+val).offset().top});
  });

  // first nav.
  scroll(parseHash());
}

init();
<|endoftext|>


<commit_before>$(function () {
    map();
});

/* map */

function map() {
  if ($("#map") != undefined) {
    var lat = $("#gmap-lat").val();
    var lng = $("#gmap-lng").val();
    var image = '/img/marker.png';

    var styles = [{"featureType": "landscape", "stylers": [{"saturation": -100}, {"lightness": 65}, {"visibility": "on"}]}, {"featureType": "poi", "stylers": [{"saturation": -100}, {"lightness": 51}, {"visibility": "simplified"}]}, {"featureType": "road.highway", "stylers": [{"saturation": -100}, {"visibility": "simplified"}]}, {"featureType": "road.arterial", "stylers": [{"saturation": -100}, {"lightness": 30}, {"visibility": "on"}]}, {"featureType": "road.local", "stylers": [{"saturation": -100}, {"lightness": 40}, {"visibility": "on"}]}, {"featureType": "transit", "stylers": [{"saturation": -100}, {"visibility": "simplified"}]}, {"featureType": "administrative.province", "stylers": [{"visibility": "off"}]}, {"featureType": "water", "elementType": "labels", "stylers": [{"visibility": "on"}, {"lightness": -25}, {"saturation": -100}]}, {"featureType": "water", "elementType": "geometry", "stylers": [{"hue": "#ffff00"}, {"lightness": -25}, {"saturation": -97}]}];
    map = new GMaps({
    	el: '#map',
    	lat: lat,
    	lng: lng,
    	zoomControl: true,
    	zoomControlOpt: {
  	    style: 'SMALL',
  	    position: 'TOP_LEFT'
    	},
    	panControl: false,
    	streetViewControl: false,
    	mapTypeControl: false,
    	overviewMapControl: false,
    	scrollwheel: false,
    	draggable: false,
    	styles: styles
    });

    map.addMarker({
    	lat: lat,
    	lng: lng,
    	icon: image/* ,
    	 title: '',
    	 infoWindow: {
    	 content: '
HTML Content
'
    	 }*/
    });
  }
}
<commit_msg>Fixes bug carousel not displaying (closes #19)<commit_after>$( document ).ready(function() {
    map();
});

function map() {
  if( $('#map').length ) {
    var lat = $("#gmap-lat").val();
    var lng = $("#gmap-lng").val();
    var image = '/img/marker.png';

    var styles = [{"featureType": "landscape", "stylers": [{"saturation": -100}, {"lightness": 65}, {"visibility": "on"}]}, {"featureType": "poi", "stylers": [{"saturation": -100}, {"lightness": 51}, {"visibility": "simplified"}]}, {"featureType": "road.highway", "stylers": [{"saturation": -100}, {"visibility": "simplified"}]}, {"featureType": "road.arterial", "stylers": [{"saturation": -100}, {"lightness": 30}, {"visibility": "on"}]}, {"featureType": "road.local", "stylers": [{"saturation": -100}, {"lightness": 40}, {"visibility": "on"}]}, {"featureType": "transit", "stylers": [{"saturation": -100}, {"visibility": "simplified"}]}, {"featureType": "administrative.province", "stylers": [{"visibility": "off"}]}, {"featureType": "water", "elementType": "labels", "stylers": [{"visibility": "on"}, {"lightness": -25}, {"saturation": -100}]}, {"featureType": "water", "elementType": "geometry", "stylers": [{"hue": "#ffff00"}, {"lightness": -25}, {"saturation": -97}]}];
    map = new GMaps({
      el: '#map',
      lat: lat,
      lng: lng,
      zoomControl: true,
      zoomControlOpt: {
        style: 'SMALL',
        position: 'TOP_LEFT'
      },
      panControl: false,
      streetViewControl: false,
      mapTypeControl: false,
      overviewMapControl: false,
      scrollwheel: false,
      draggable: false,
      styles: styles
    });

    map.addMarker({
      lat: lat,
      lng: lng,
      icon: image/* ,
       title: '',
       infoWindow: {
       content: '
HTML Content
'
       }*/
    });
  }
}
<|endoftext|>


<commit_before>/**
 * Support file for Libravatar
 * @source: https://code.launchpad.net/libravatar
 *
 * @licstart
 * Copyright (C) 2011 Francois Marier <francois@libravatar.org>
 *
 * The JavaScript code in this page is free software: you can
 * redistribute it and/or modify it under the terms of the GNU Affero
 * General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. The code is distributed WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU Affero General Public License
 * for more details.
 *
 * As an additional permission under GNU AGPL version 3 section 7, you
 * may distribute non-source (e.g., minimized or compacted) forms of
 * that code without the copy of the GNU AGPL normally required by
 * section 4, provided you include this license notice and a URL
 * through which recipients can access the Corresponding Source.
 * @licend
 */

"use strict";

// Autofocus the right field on forms
if (document.forms.login) {
    if (document.forms.login.username) {
        document.forms.login.username.focus();
    } else if (document.forms.login.openid_identifier) {
        document.forms.login.openid_identifier.focus();
    }
} else if (document.forms.addemail) {
    document.forms.addemail.email.focus();
} else if (document.forms.addopenid) {
    document.forms.addopenid.openid.focus();
} else if (document.forms.changepassword) {
    document.forms.changepassword.old_password.focus();
} else if (document.forms.deleteaccount) {
    if (document.forms.deleteaccount.password) {
        document.forms.deleteaccount.password.focus();
    }
} else if (document.forms.lookup) {
    if (document.forms.lookup.email) {
        document.forms.lookup.email.focus();
    } else if (document.forms.lookup.domain) {
        document.forms.lookup.domain.focus();
    }
} else if (document.forms.newaccount) {
    document.forms.newaccount.username.focus();
} else if (document.forms.reset) {
    document.forms.reset.email.focus();
}

if (navigator.id) {
    // For the BrowserID addon (session API)
    var username = document.getElementById('session-username').textContent;
    if (username) {
        navigator.id.sessions = [{
            email: username,
            bound_to: {
                type: "cookie",
                cookie_name: "sessionid"
            }
        }];
    } else {
        navigator.id.sessions = [];
    }
    document.addEventListener("login", function (event) {
        document.location.href = "/account/login/";
    }, false);
    document.addEventListener("logout", function (event) {
        document.location.href = "/account/logout/";
    }, false);

    // Show BrowserID option and make link clickable
    var option = document.getElementById('browserid-option');
    var link = document.getElementById('browserid-link');
    if (option && link) {
        option.style.display = 'inline';
        link.onclick = try_browserid;
        link.addEventListener('click', try_browserid, false);
    }
}

// For main BrowserID functionality on the add_email and login pages
function try_browserid() {
    navigator.id.getVerifiedEmail(function (assertion) {
        if (assertion) {
            document.getElementById('browserid-assertion').setAttribute('value', assertion);
            document.getElementById('browserid-form').submit();
        }
    });
}
<commit_msg>Replace navigator.id.getVerifiedEmail() with .get() (closes: #911482)<commit_after>/**
 * Support file for Libravatar
 * @source: https://code.launchpad.net/libravatar
 *
 * @licstart
 * Copyright (C) 2011 Francois Marier <francois@libravatar.org>
 *
 * The JavaScript code in this page is free software: you can
 * redistribute it and/or modify it under the terms of the GNU Affero
 * General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. The code is distributed WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU Affero General Public License
 * for more details.
 *
 * As an additional permission under GNU AGPL version 3 section 7, you
 * may distribute non-source (e.g., minimized or compacted) forms of
 * that code without the copy of the GNU AGPL normally required by
 * section 4, provided you include this license notice and a URL
 * through which recipients can access the Corresponding Source.
 * @licend
 */

"use strict";

// Autofocus the right field on forms
if (document.forms.login) {
    if (document.forms.login.username) {
        document.forms.login.username.focus();
    } else if (document.forms.login.openid_identifier) {
        document.forms.login.openid_identifier.focus();
    }
} else if (document.forms.addemail) {
    document.forms.addemail.email.focus();
} else if (document.forms.addopenid) {
    document.forms.addopenid.openid.focus();
} else if (document.forms.changepassword) {
    document.forms.changepassword.old_password.focus();
} else if (document.forms.deleteaccount) {
    if (document.forms.deleteaccount.password) {
        document.forms.deleteaccount.password.focus();
    }
} else if (document.forms.lookup) {
    if (document.forms.lookup.email) {
        document.forms.lookup.email.focus();
    } else if (document.forms.lookup.domain) {
        document.forms.lookup.domain.focus();
    }
} else if (document.forms.newaccount) {
    document.forms.newaccount.username.focus();
} else if (document.forms.reset) {
    document.forms.reset.email.focus();
}

if (navigator.id) {
    // For the BrowserID addon (session API)
    var username = document.getElementById('session-username').textContent;
    if (username) {
        navigator.id.sessions = [{
            email: username,
            bound_to: {
                type: "cookie",
                cookie_name: "sessionid"
            }
        }];
    } else {
        navigator.id.sessions = [];
    }
    document.addEventListener("login", function (event) {
        document.location.href = "/account/login/";
    }, false);
    document.addEventListener("logout", function (event) {
        document.location.href = "/account/logout/";
    }, false);

    // Show BrowserID option and make link clickable
    var option = document.getElementById('browserid-option');
    var link = document.getElementById('browserid-link');
    if (option && link) {
        option.style.display = 'inline';
        link.onclick = try_browserid;
        link.addEventListener('click', try_browserid, false);
    }
}

// For main BrowserID functionality on the add_email and login pages
function try_browserid() {
    navigator.id.get(function (assertion) {
        if (assertion) {
            document.getElementById('browserid-assertion').setAttribute('value', assertion);
            document.getElementById('browserid-form').submit();
        }
    });
}
<|endoftext|>


<commit_before>// For the scroll effects.
stroll.bind('.stroll-list ul', {live: true});

// Click 'more' then append days.
$('.load').on('click', function(){
  var last = $('.three-column-day li a').eq(-1).html();
  $.ajax('/three-columns/append-date/' + last, {
    type: 'GET',
    dataType: 'json',
    success: function(resp){
      resp.append_list.map(function(date) {
        $('.load').before("
" + date + "
");
      });
    }
  });
});

// Click the date and show the news titles.
// Event binding on dynamically elements：
// http://stackoverflow.com/a/6658774 and http://stackoverflow.com/a/1207393
$('.three-column-day').on('click', 'a.days', function(event) {
  event.preventDefault();
  $.getJSON($(this).attr('href'), function(resp) {
    $('.three-column-title li').remove();
    // http://goo.gl/fRKpMD
    var news = resp.news;
    var textToInsert = [];
    var length = news.length;
    var i = 0;
    for (var a = 0; a < length; a += 1) {
//      textToInsert[i++] = '
<a href="http://news-at.zhihu.com/api/4/news/';
      textToInsert[i++] = '
';
      textToInsert[i++] = news[a]['title'];
      textToInsert[i++] = '
';
    }
    $('.three-column-title').append(textToInsert.join(''));
  });
  $('.three-column-title').animate({scrollTop: 0}, 1000);
});

// Mark clicked days in the first column.
$('.stroll-list').on('click', 'a.days', function() {
  $(this).css( "color", "#acacc6");
});

// Click the title and show the content.
$('.three-column-title').on('click', 'a.titles', function(event) {
  event.preventDefault();
    $.ajax($(this).attr('href'), {
      type: 'GET',
      dataType: 'json',
      success: function(resp){
          $('.three-column-content div').replaceWith(resp['body']);
      }
    });
  $('.three-column-content').animate({scrollTop: 0}, 1000);
});
<commit_msg>Also mark those clicked titles<commit_after>// For the scroll effects.
stroll.bind('.stroll-list ul', {live: true});

// Click 'more' then append days.
$('.load').on('click', function(){
  var last = $('.three-column-day li a').eq(-1).html();
  $.ajax('/three-columns/append-date/' + last, {
    type: 'GET',
    dataType: 'json',
    success: function(resp){
      resp.append_list.map(function(date) {
        $('.load').before("
" + date + "
");
      });
    }
  });
});

// Click the date and show the news titles.
// Event binding on dynamically elements：
// http://stackoverflow.com/a/6658774 and http://stackoverflow.com/a/1207393
$('.three-column-day').on('click', 'a.days', function(event) {
  event.preventDefault();
  $.getJSON($(this).attr('href'), function(resp) {
    $('.three-column-title li').remove();
    // http://goo.gl/fRKpMD
    var news = resp.news;
    var textToInsert = [];
    var length = news.length;
    var i = 0;
    for (var a = 0; a < length; a += 1) {
//      textToInsert[i++] = '
<a href="http://news-at.zhihu.com/api/4/news/';
      textToInsert[i++] = '
';
      textToInsert[i++] = news[a]['title'];
      textToInsert[i++] = '
';
    }
    $('.three-column-title').append(textToInsert.join(''));
  });
  $('.three-column-title').animate({scrollTop: 0}, 1000);
});

// Mark clicked days in the first column.
$('.stroll-list').on('click', 'a', function() {
  $(this).css( "color", "#acacc6");
});

// Click the title and show the content.
$('.three-column-title').on('click', 'a.titles', function(event) {
  event.preventDefault();
    $.ajax($(this).attr('href'), {
      type: 'GET',
      dataType: 'json',
      success: function(resp){
          $('.three-column-content div').replaceWith(resp['body']);
      }
    });
  $('.three-column-content').animate({scrollTop: 0}, 1000);
});
<|endoftext|>


<commit_before>var popupWin = null;
function openPopup(url) {
	if ( !popupWin || popupWin.closed ) {
		popupWin = window.open( url, "popupWin", "width=640,height=480" );
	} else popupWin.focus();
}
$(document).ready(function() {
    $('.error').hide().slideDown('slow')
    $('.error').click(function() { $(this).fadeOut('slow'); return false; });
    $('.warning').hide().slideDown('slow')
    $('.warning').click(function() { $(this).fadeOut('slow'); return false; });
    $('.information').hide().slideDown('slow')
    $('.information').click(function() { $(this).fadeOut('slow'); return false; });
    $('.confirmation').hide().slideDown('slow')
    $('.confirmation').click(function() { $(this).fadeOut('slow'); return false; });
    $("input.date").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', isRTL: false });
    $('a.thickbox').click(function(){
        $(this).attr('href', function() {
	    // Add the caller to the URL vars so that the popup knows which field to refresh/set
	    var url_in = $(this).attr('href');
	    var caller = $(this).parents('tr').attr('id').replace(/__row/, '');
	    // This has to be the last var: &TB_iframe=true
	    if (set_parent_id)
	        url_in = set_parent_id(url_in,caller);

	    if (url_in.match(/caller=/)) {
	        return url_in.replace(/caller=.*?&/, 'caller=' + caller + '&');
		} else {
		return url_in.replace(/&TB_iframe=true/, '&caller=' + caller + '&TB_iframe=true');
	    }
        });
        return false;
    });
    // IE6 non anchor hover hack
    $('.hoverable').hover(
        function() { $(this).addClass('hovered'); },
        function() { $(this).removeClass('hovered'); }
    );
    // Menu popups (works in IE6)
    $('#modulenav li').hover(
        function() {
                var popup_width = $(this).width()-2;
                $('ul', this).css({
                    'display': 'block',
                    'width': popup_width.toString() + 'px'
                });
            },
        function() { $('ul', this).css('display', 'none');  }
    );
    $('#subnav li').hover(
        function() {
                var popup_width = $(this).width()-2;
                $('ul', this).css({
                    'display': 'block',
                    'width': popup_width.toString() + 'px'
                });
            },
        function() { $('ul', this).css('display', 'none');  }
    );
});
/*
  ajaxS3 ------------------------------------------------------------
  added by sunneach 2010-feb-14
*/

/*
  these set in the ajaxS3messages.js :
_ajaxS3_wht_ = {{=T('We have tried')}};
_ajaxS3_gvn_ = {{=T('times and it is still not working. We give in. Sorry.')}};
_ajaxS3_500_ = {{=T('Sorry - the server has a problem, please try again later.')}};
_ajaxS3_dwn_ = {{=T('There was a problem, sorry, please try again later.')}};
_ajaxS3_get_ = {{=T('getting')}};
_ajaxS3_fmd_ = {{=T('form data')}};
_ajaxS3_rtr_ = {{=T('retry')}};
*/
(function($) {
    jQuery.ajaxS3 = function(s) {
        var options = jQuery.extend({}, jQuery.ajaxS3Settings, s);
	options.tryCount = 0;
	showStatus(_ajaxS3_get_ + ' ' + (s.message ? s.message : _ajaxS3_fmd_) + '...', this.ajaxS3Settings.msgTimeout);
	options.success = function(data, status) {
	    hideStatus();
	    if(s.success)
		s.success(data, status);
	}
	options.error = function(xhr, textStatus, errorThrown ) {
	    if (textStatus == 'timeout') {
		this.tryCount++;
		if (this.tryCount <= this.retryLimit) {
		    //try again
    		    showStatus(_ajaxS3_get_ + ' ' + (s.message ? s.message : _ajaxS3_fmd_) + '... ' + _ajaxS3_rtr_+ ' ' + this.tryCount,
				$.ajaxS3Settings.msgTimeout);
		    $.ajax(this);
		    return;
		}
		showStatus(_ajaxS3_wht_ + ' ' + (this.retryLimit + 1) + ' ' + _ajaxS3_gvn_,
			   $.ajaxS3Settings.msgTimeout, false, true);
		return;
	    }
	    if (xhr.status == 500) {
		showStatus(_ajaxS3_500_, $.ajaxS3Settings.msgTimeout, false, true);
	    } else {
		showStatus(_ajaxS3_dwn_, $.ajaxS3Settings.msgTimeout, false, true);
	    }
	};
        jQuery.ajax(options);
    };

    jQuery.postS3 = function(url, data, callback, type) {
        return jQuery.ajaxS3({
            type: "POST",
            url: url,
            data: data,
            success: callback,
            dataType: type
        });
    };

    jQuery.getS3 = function(url, data, callback, type, message) {
	// shift arguments if data argument was ommited
	if ( jQuery.isFunction( data ) ) {
		callback = data;
		data = null;
	}
        return jQuery.ajaxS3({
            type: 'GET',
            url: url,
	    data: data,
            success: callback,
            dataType: type,
	    message: message,
        });
    };

    jQuery.getJSONS3 = function(url, data, callback, message) {
	// shift arguments if data argument was ommited
	if ( jQuery.isFunction( data ) ) {
		message = callback;
		callback = data;
		data = null;
	}
        return jQuery.getS3(url, data, callback, 'json', message);
    };

    jQuery.ajaxS3Settings = {
	timeout : 10000,
	msgTimeout: 2000,
	retryLimit : 10,
	dataType: 'json',
	type: 'GET'
    };

    jQuery.ajaxS3Setup = function(settings) {
        jQuery.extend(jQuery.ajaxS3Settings, settings);
    };

})(jQuery);

// status bar for ajaxS3 operation
// taken from http://www.west-wind.com/WebLog/posts/388213.aspx
// added and fixed by sunneach on Feb 16, 2010
//
//  to use make a call:
//  showStatus(message, timeout, additive, isError)
//     1. message  - string - message to display
//     2. timeout  - integer - milliseconds to change the statusbar style - flash effect (1000 works OK)
//     3. additive - boolean - default false - to accumulate messages in the bar
//     4. isError  - boolean - default false - show in the statusbarerror class
//
//  to remove bar, use
//  hideStatus()
//
function StatusBar(sel,options)
{
    var _I = this;
    var _sb = null;
    // options
    this.elementId = "_showstatus";
    this.prependMultiline = true;
    this.showCloseButton = false;
    this.afterTimeoutText = null;

    this.cssClass = "statusbar";
    this.highlightClass = "statusbarhighlight";
    this.errorClass = "statusbarerror";
    this.closeButtonClass = "statusbarclose";
    this.additive = false;
    $.extend(this, options);
    if (sel)
      _sb = $(sel);
    // create statusbar object manually
    if (!_sb)
    {
        _sb = $("
" +
                "
" +
                (_I.showCloseButton ? " X

" : "") )
                .appendTo(document.body)
                .show();
    }
    //if (_I.showCloseButton)
        $("." + _I.cssClass).click(function(e) { $(_sb).hide(); });
    this.show = function(message, timeout, additive, isError)
    {
        if (additive || ((additive == undefined) && _I.additive))
        {
            var html = "
" + message + "
";
            if (_I.prependMultiline)
                _sb.prepend(html);
            else
                _sb.append(html);
        }
        else
        {
            if (!_I.showCloseButton)
                _sb.text(message);
            else
            {
                var t = _sb.find("div.statusbarclose");
                _sb.text(message).prepend(t);
            }
        }
        _sb.show();
        if (timeout)
        {
            if (isError)
                _sb.addClass(_I.errorClass);
            else
                _sb.addClass(_I.highlightClass);
            setTimeout(
                function() {
                    _sb.removeClass(_I.highlightClass);
                    if (_I.afterTimeoutText)
                       _I.show(_I.afterTimeoutText);
                },
                timeout);
        }
    }
    this.release = function()
    {
        if(_statusbar){
            $('#_statusbar').remove();
	    _statusbar = undefined;
	}
    }
}
// use this as a global instance to customize constructor
// or do nothing and get a default status bar
var _statusbar = null;
function showStatus(message, timeout, additive, isError)
{
    if (!_statusbar)
        _statusbar = new StatusBar();
    _statusbar.show(message, timeout, additive, isError);
}
function hideStatus()
{
    if(_statusbar)
	_statusbar.release();
}
<commit_msg>S3 IE bug fixed - the app did not work in IE without  this<commit_after>var popupWin = null;
function openPopup(url) {
	if ( !popupWin || popupWin.closed ) {
		popupWin = window.open( url, "popupWin", "width=640,height=480" );
	} else popupWin.focus();
}
$(document).ready(function() {
    $('.error').hide().slideDown('slow')
    $('.error').click(function() { $(this).fadeOut('slow'); return false; });
    $('.warning').hide().slideDown('slow')
    $('.warning').click(function() { $(this).fadeOut('slow'); return false; });
    $('.information').hide().slideDown('slow')
    $('.information').click(function() { $(this).fadeOut('slow'); return false; });
    $('.confirmation').hide().slideDown('slow')
    $('.confirmation').click(function() { $(this).fadeOut('slow'); return false; });
    $("input.date").datepicker({ changeMonth: true, changeYear: true, dateFormat: 'yy-mm-dd', isRTL: false });
    $('a.thickbox').click(function(){
        $(this).attr('href', function() {
	    // Add the caller to the URL vars so that the popup knows which field to refresh/set
	    var url_in = $(this).attr('href');
	    var caller = $(this).parents('tr').attr('id').replace(/__row/, '');
	    // This has to be the last var: &TB_iframe=true
	    if (set_parent_id)
	        url_in = set_parent_id(url_in,caller);

	    if (url_in.match(/caller=/)) {
	        return url_in.replace(/caller=.*?&/, 'caller=' + caller + '&');
		} else {
		return url_in.replace(/&TB_iframe=true/, '&caller=' + caller + '&TB_iframe=true');
	    }
        });
        return false;
    });
    // IE6 non anchor hover hack
    $('.hoverable').hover(
        function() { $(this).addClass('hovered'); },
        function() { $(this).removeClass('hovered'); }
    );
    // Menu popups (works in IE6)
    $('#modulenav li').hover(
        function() {
                var popup_width = $(this).width()-2;
                $('ul', this).css({
                    'display': 'block',
                    'width': popup_width.toString() + 'px'
                });
            },
        function() { $('ul', this).css('display', 'none');  }
    );
    $('#subnav li').hover(
        function() {
                var popup_width = $(this).width()-2;
                $('ul', this).css({
                    'display': 'block',
                    'width': popup_width.toString() + 'px'
                });
            },
        function() { $('ul', this).css('display', 'none');  }
    );
});
/*
  ajaxS3 ------------------------------------------------------------
  added by sunneach 2010-feb-14
*/

/*
  these set in the ajaxS3messages.js :
_ajaxS3_wht_ = {{=T('We have tried')}};
_ajaxS3_gvn_ = {{=T('times and it is still not working. We give in. Sorry.')}};
_ajaxS3_500_ = {{=T('Sorry - the server has a problem, please try again later.')}};
_ajaxS3_dwn_ = {{=T('There was a problem, sorry, please try again later.')}};
_ajaxS3_get_ = {{=T('getting')}};
_ajaxS3_fmd_ = {{=T('form data')}};
_ajaxS3_rtr_ = {{=T('retry')}};
*/
(function($) {
    jQuery.ajaxS3 = function(s) {
        var options = jQuery.extend({}, jQuery.ajaxS3Settings, s);
	options.tryCount = 0;
	showStatus(_ajaxS3_get_ + ' ' + (s.message ? s.message : _ajaxS3_fmd_) + '...', this.ajaxS3Settings.msgTimeout);
	options.success = function(data, status) {
	    hideStatus();
	    if(s.success)
		s.success(data, status);
	}
	options.error = function(xhr, textStatus, errorThrown ) {
	    if (textStatus == 'timeout') {
		this.tryCount++;
		if (this.tryCount <= this.retryLimit) {
		    //try again
    		    showStatus(_ajaxS3_get_ + ' ' + (s.message ? s.message : _ajaxS3_fmd_) + '... ' + _ajaxS3_rtr_+ ' ' + this.tryCount,
				$.ajaxS3Settings.msgTimeout);
		    $.ajax(this);
		    return;
		}
		showStatus(_ajaxS3_wht_ + ' ' + (this.retryLimit + 1) + ' ' + _ajaxS3_gvn_,
			   $.ajaxS3Settings.msgTimeout, false, true);
		return;
	    }
	    if (xhr.status == 500) {
		showStatus(_ajaxS3_500_, $.ajaxS3Settings.msgTimeout, false, true);
	    } else {
		showStatus(_ajaxS3_dwn_, $.ajaxS3Settings.msgTimeout, false, true);
	    }
	};
        jQuery.ajax(options);
    };

    jQuery.postS3 = function(url, data, callback, type) {
        return jQuery.ajaxS3({
            type: "POST",
            url: url,
            data: data,
            success: callback,
            dataType: type
        });
    };

    jQuery.getS3 = function(url, data, callback, type, message) {
	// shift arguments if data argument was ommited
	if ( jQuery.isFunction( data ) ) {
		callback = data;
		data = null;
	}
        return jQuery.ajaxS3({
            type: 'GET',
            url: url,
	    data: data,
            success: callback,
            dataType: type,
	    message: message
        });
    };

    jQuery.getJSONS3 = function(url, data, callback, message) {
	// shift arguments if data argument was ommited
	if ( jQuery.isFunction( data ) ) {
		message = callback;
		callback = data;
		data = null;
	}
        return jQuery.getS3(url, data, callback, 'json', message);
    };

    jQuery.ajaxS3Settings = {
	timeout : 10000,
	msgTimeout: 2000,
	retryLimit : 10,
	dataType: 'json',
	type: 'GET'
    };

    jQuery.ajaxS3Setup = function(settings) {
        jQuery.extend(jQuery.ajaxS3Settings, settings);
    };

})(jQuery);

// status bar for ajaxS3 operation
// taken from http://www.west-wind.com/WebLog/posts/388213.aspx
// added and fixed by sunneach on Feb 16, 2010
//
//  to use make a call:
//  showStatus(message, timeout, additive, isError)
//     1. message  - string - message to display
//     2. timeout  - integer - milliseconds to change the statusbar style - flash effect (1000 works OK)
//     3. additive - boolean - default false - to accumulate messages in the bar
//     4. isError  - boolean - default false - show in the statusbarerror class
//
//  to remove bar, use
//  hideStatus()
//
function StatusBar(sel,options)
{
    var _I = this;
    var _sb = null;
    // options
    this.elementId = "_showstatus";
    this.prependMultiline = true;
    this.showCloseButton = false;
    this.afterTimeoutText = null;

    this.cssClass = "statusbar";
    this.highlightClass = "statusbarhighlight";
    this.errorClass = "statusbarerror";
    this.closeButtonClass = "statusbarclose";
    this.additive = false;
    $.extend(this, options);
    if (sel)
      _sb = $(sel);
    // create statusbar object manually
    if (!_sb)
    {
        _sb = $("
" +
                "
" +
                (_I.showCloseButton ? " X

" : "") )
                .appendTo(document.body)
                .show();
    }
    //if (_I.showCloseButton)
        $("." + _I.cssClass).click(function(e) { $(_sb).hide(); });
    this.show = function(message, timeout, additive, isError)
    {
        if (additive || ((additive == undefined) && _I.additive))
        {
            var html = "
" + message + "
";
            if (_I.prependMultiline)
                _sb.prepend(html);
            else
                _sb.append(html);
        }
        else
        {
            if (!_I.showCloseButton)
                _sb.text(message);
            else
            {
                var t = _sb.find("div.statusbarclose");
                _sb.text(message).prepend(t);
            }
        }
        _sb.show();
        if (timeout)
        {
            if (isError)
                _sb.addClass(_I.errorClass);
            else
                _sb.addClass(_I.highlightClass);
            setTimeout(
                function() {
                    _sb.removeClass(_I.highlightClass);
                    if (_I.afterTimeoutText)
                       _I.show(_I.afterTimeoutText);
                },
                timeout);
        }
    }
    this.release = function()
    {
        if(_statusbar){
            $('#_statusbar').remove();
	    _statusbar = undefined;
	}
    }
}
// use this as a global instance to customize constructor
// or do nothing and get a default status bar
var _statusbar = null;
function showStatus(message, timeout, additive, isError)
{
    if (!_statusbar)
        _statusbar = new StatusBar();
    _statusbar.show(message, timeout, additive, isError);
}
function hideStatus()
{
    if(_statusbar)
	_statusbar.release();
}
<|endoftext|>


<commit_before>// View event binding
_.init = function() {

  _.persistent = new LocalStoragePersistent();

  // Load data
  var current = _.persistent.get('current');
  if (!current) {
    _.user = User.create('anonymous', '', true);
    _.project = Project.get(_.user.defaultProject);

    var current = {id: 'current', key: _.user.id};
    _.persistent.save(current);
  } else {
    _.user = User.get(current.key);
    _.project = Project.get(_.user.defaultProject);
  }

  var iteration = Iteration.get(_.project.currentIteration());
  for (var taskID in iteration.tasks) {

    if (iteration.tasks[taskID]) {
      var task = Task.get(taskID);
      if (task) {
        $('#' + task.status).append(_.tmpl('task', task));
        $('#' + task.id).attr('draggable', true);
      }

    }

  }

  $('#project-name').text(_.project.name);
  $('#iteration-name').text(iteration.name);

  // List projects
  var projects = _.user.projects;
  for (var index = 0; index < projects.length; index++) {
    var project = Project.get(projects[index]);
    if (project) {
      var list = _.tmpl('project_list', project);
      $('#projects-list-menu').append(list);
    }
  }

  // List iterations
  var iterations = _.project.iterations.slice(0).reverse()
  for (var index = 0; index < iterations.length; index++) {
    var iteration = Iteration.get(iterations[index]);
    var list = _.tmpl('iteration_list', iteration);
    $('#iterations-list-menu').append(list);
  }

  // Bind drag & drop on wall
  $('.wall').bind({
    dragenter: function (ev) {
      $(this).addClass('over');
    },
    dragover: function (ev) {
      if (ev.preventDefault) {
        ev.preventDefault();
      }

      return false;
    },
    dragleave: function (ev) {
      $(this).removeClass('over');
    },
    drop: function (ev) {
      $(this).removeClass('over');

      var dt = ev.originalEvent.dataTransfer;
      var target = dt.getData('Text');

      $('#' + target).remove();
      var task = Task.get(target);
      $(this).append(_.tmpl('task', task));
      $('#' + task.id).attr('draggable', true);

      var status = $(this)[0].id;
      task.status = status;
      Task.save(task, true);

      console.log ('client(update): ' + task.status + ', ' + task.detail);

      return false;
    }
  });

  // Bind drag & drop on task
  $('.task').live({
    dragstart: function (ev) {
      var dt = ev.originalEvent.dataTransfer;
      dt.setData('Text', $(this).attr('id'));
    },
    dblclick: function (ev) {
      window.location.hash = 'task/edit/' + $(this).attr('id');
    }
  });

  $('#new-task-button').click(function(event) {
    window.location.hash = 'task/new';
  });

  $('#clear-task-button').click(function(event) {
    window.location.hash = 'task/clear';
  });

  $('#end-iteration-button').click(function(event) {
    window.location.hash = 'iteration/end';
  });

  $('.dropdown').click(function(event) {
    var open = false;
    if (!$(this).hasClass('open')) {
      open = true;
    }
    $('.dropdown').removeClass('open');

    if (open) {
      $(this).addClass('open');
    }
  });

  // Update event
  $(applicationCache).bind('updateready', function (e) {
    if (applicationCache.status == applicationCache.UPDATEREADY) {
      window.location.hash = 'update/ready';
    }
  });

  // Sync data to server if online
  if (navigator.onLine) {
    now.ready(function() {

      _.client = now.core.clientId;

      $('#logging-in-menu').hide();

      if (_.user.anonymous) {
        $('#logged-out-menu').css('display', 'block');

        if (_.oldHash) {
          // Parse login
          if (/^#user\/login/i.test(_.oldHash)) {
            window.location.hash = _.oldHash;
          }
        }
      } else {

        var joinList = [];

        // If user already login it should sync user.
        now.syncUser(_.user, function(object) {

          console.log ('Sync user success: ' + object.error);
          // How to handler error ?
          if (!object.error) {

            joinList.push(_.user.id);

            $('#logged-in-user').text(_.user.username);
            $('#logged-in-image').attr('src', _.user.image);

            $('#logged-in-menu').css('display', 'block');
            $('#logged-in-status').css('display', 'block');

            if (object.status == 'update') {
              var data = object.data;
              User.save(data);
            }

            // Prepare project need to sync
            var projects = _.user.projects;
            var prepare = [];
            for (var key in projects) {
              var project = Project.get(projects[key]);
              if (project && project.sync) {
                prepare.push(project);
              }
            }

            now.syncProjects(_.client, _.user.id, prepare, function (object) {

              if (object.status == 'update') {
                var projects = object.data;

                for (var key in projects) {
                  var project = projects[key];
                  Project.save(project);

                  joinList.push(project.id);
                }

                now.joinGroups(_.client, joinList, function () {
                  console.log ('Join projects success');
                });
              }

            });

          } else {

            _.persistent.clear();
            location.reload();

          }

        });
      }

      $('#sync-status').text('Online');

      // User real-time synchronization
      now.clientUpdateUser = function (user) {

        console.log ('server-debug(create): user - ' +
                     user.id + ', ' +
                     user.updated);

        if (user.updated > _.user.updated) {
          User.save(user);
        }

      }

      // Project real-time synchronization
      now.clientCreateProject = function (client, serverProject) {

        console.log ('server-debug(create): project - ' +
                     serverProject.id + ', ' +
                     serverProject.updated + ', ' +
                     serverProject.modified);

        if (client != _.client) {
          Project.save(serverProject);
          now.joinGroups(_.client, [serverProject.id]);

          var list = _.tmpl('project_list', serverProject);
          $('#projects-list-menu').append(list);
        }

      }

      now.clientUpdateProject = function (client, serverProject) {

        console.log ('server-debug(update): project - ' +
                     serverProject.id + ', ' +
                     serverProject.updated + ', ' +
                     serverProject.modified);

        var clientProject = Project.get(serverProject.id);
        if (serverProject.updated > clientProject.updated ||
            serverProject.modified != clientProject.modified) {
          Project.save(serverProject);
        }

        clientProject = Project.get(serverProject.id);
        $('#project-menu-' + clientProject.id).text(clientProject.name);

        if (_.project.id == clientProject.id) {
          $('#project-name').text(clientProject.name);
          _.project = clientProject;
        }

      }

      // Task real-time synchronization
      now.clientCreateTask = function (from, task) {
        console.log ('server-debug(create): (' + from + ',' + task.id + ') ' + task.detail);
        if (from == _.client) { return; }

        if (!Task.get(task.id)) {
          Task.save(task);

          var iteration = Iteration.get(_.project.currentIteration());
          iteration.addTask(task);
          Iteration.save(iteration);

          var _task = Task.get(task.id);
          $('#' + _task.status).append(_.tmpl('task', _task));
          $('#' + _task.id).attr('draggable', true);
          console.log ('server(create): ' + _task.status + ', ' + _task.detail);
        }

      };

      now.clientUpdateTask = function (from, task) {
        console.log ('server-debug(update): (' + from + ',' + task.id + ') '  + task.detail);
        if (from == _.client) { return; }

        var _task = Task.get(task.id);
        _task.setDetail(task.detail);
        _task.updated = task.updated;
        _task.status = task.status;
        Task.save(_task);

        console.log ('server(update): ' + _task.status + ', ' + _task.detail);

        $('#' + _task.id).remove();
        $('#' + _task.status).append(_.tmpl('task', _task));
        $('#' + _task.id).attr('draggable', true);
      }

      now.clientRemoveTask = function (from, id) {
        console.log ('server-debug(remove): (' + from + ',' + id + ')');
        if (from == _.client) { return; }

        console.log ('server(remove): ' + id);

        if ($('#' + id).length > 0) {
          $('#' + id).remove();
          Task.remove(id);

          var iteration = Iteration.get(_.project.currentIteration());
          iteration.removeTask(id);
          Iteration.save(iteration);
        }

      }

      var iteration = Iteration.get(_.project.currentIteration());
      var prepareSync = [];
      var tasks = iteration.tasks;

      for (var taskID in tasks) {
        var task = Task.get(taskID);
        if (task) {
          prepareSync.push(task);
        }
      }

      var prepareRemove = [];
      var removed = _.persistent.get('removed');

      if (removed) {
        prepareRemove = removed.list;
        _.persistent.remove('removed');
      }

      now.joinGroups(_.client, [iteration.id], function() {

        $('#sync-status').text('Syncing');
        now.syncAllTask(iteration.id , prepareSync, prepareRemove, function() {
          $('#sync-status').text('Online');
        });

      });

    });
  } else {

    $('#logging-in-menu').hide();
    if (_.user.anonymous) {
      $('#logged-out-menu').hide();
    } else {
      $('#logged-in-status').css('display', 'block');
      $('#logged-in-user').text(_.user.username);

      $('#logged-in-menu').css('display', 'block');
      $('#log-out-menu').remove();

      if (_.project.sync) {
        $('#end-iteration-button').attr('disabled', true);
      }
    }

  }

  // Online/Offline event
  $(window).bind('online', function (e) {
    console.log ('Online');
    window.location.reload()
  });

  $(window).bind('offline', function(e) {
    console.log ('Offline');
    $('#sync-status').text('Offline');

    if (_.project.sync) {
      $('#end-iteration-button').attr('disabled', true);
    }
  });

}<commit_msg>Render project menu after sync projects.<commit_after>// View event binding
_.init = function() {

  _.persistent = new LocalStoragePersistent();

  // Load data
  var current = _.persistent.get('current');
  if (!current) {
    _.user = User.create('anonymous', '', true);
    _.project = Project.get(_.user.defaultProject);

    var current = {id: 'current', key: _.user.id};
    _.persistent.save(current);
  } else {
    _.user = User.get(current.key);
    _.project = Project.get(_.user.defaultProject);
  }

  var iteration = Iteration.get(_.project.currentIteration());
  for (var taskID in iteration.tasks) {

    if (iteration.tasks[taskID]) {
      var task = Task.get(taskID);
      if (task) {
        $('#' + task.status).append(_.tmpl('task', task));
        $('#' + task.id).attr('draggable', true);
      }

    }

  }

  $('#project-name').text(_.project.name);
  $('#iteration-name').text(iteration.name);

  // List iterations
  var iterations = _.project.iterations.slice(0).reverse()
  for (var index = 0; index < iterations.length; index++) {
    var iteration = Iteration.get(iterations[index]);
    var list = _.tmpl('iteration_list', iteration);
    $('#iterations-list-menu').append(list);
  }

  // Bind drag & drop on wall
  $('.wall').bind({
    dragenter: function (ev) {
      $(this).addClass('over');
    },
    dragover: function (ev) {
      if (ev.preventDefault) {
        ev.preventDefault();
      }

      return false;
    },
    dragleave: function (ev) {
      $(this).removeClass('over');
    },
    drop: function (ev) {
      $(this).removeClass('over');

      var dt = ev.originalEvent.dataTransfer;
      var target = dt.getData('Text');

      $('#' + target).remove();
      var task = Task.get(target);
      $(this).append(_.tmpl('task', task));
      $('#' + task.id).attr('draggable', true);

      var status = $(this)[0].id;
      task.status = status;
      Task.save(task, true);

      console.log ('client(update): ' + task.status + ', ' + task.detail);

      return false;
    }
  });

  // Bind drag & drop on task
  $('.task').live({
    dragstart: function (ev) {
      var dt = ev.originalEvent.dataTransfer;
      dt.setData('Text', $(this).attr('id'));
    },
    dblclick: function (ev) {
      window.location.hash = 'task/edit/' + $(this).attr('id');
    }
  });

  $('#new-task-button').click(function(event) {
    window.location.hash = 'task/new';
  });

  $('#clear-task-button').click(function(event) {
    window.location.hash = 'task/clear';
  });

  $('#end-iteration-button').click(function(event) {
    window.location.hash = 'iteration/end';
  });

  $('.dropdown').click(function(event) {
    var open = false;
    if (!$(this).hasClass('open')) {
      open = true;
    }
    $('.dropdown').removeClass('open');

    if (open) {
      $(this).addClass('open');
    }
  });

  // Update event
  $(applicationCache).bind('updateready', function (e) {
    if (applicationCache.status == applicationCache.UPDATEREADY) {
      window.location.hash = 'update/ready';
    }
  });

  // Sync data to server if online
  if (navigator.onLine) {
    now.ready(function() {

      _.client = now.core.clientId;

      $('#logging-in-menu').hide();

      if (_.user.anonymous) {
        $('#logged-out-menu').css('display', 'block');

        // List projects
        var projects = _.user.projects;
        for (var index = 0; index < projects.length; index++) {
          var project = Project.get(projects[index]);
          if (project) {
            var list = _.tmpl('project_list', project);
            $('#projects-list-menu').append(list);
          }
        }

        if (_.oldHash) {
          // Parse login
          if (/^#user\/login/i.test(_.oldHash)) {
            window.location.hash = _.oldHash;
          }
        }
      } else {

        var joinList = [];

        // If user already login it should sync user.
        now.syncUser(_.user, function(object) {

          console.log ('Sync user success: ' + object.error);
          // How to handler error ?
          if (!object.error) {

            joinList.push(_.user.id);

            $('#logged-in-user').text(_.user.username);
            $('#logged-in-image').attr('src', _.user.image);

            $('#logged-in-menu').css('display', 'block');
            $('#logged-in-status').css('display', 'block');

            if (object.status == 'update') {
              var data = object.data;
              User.save(data);

              _.user = User.get(data.id);
            }

            // Prepare project need to sync
            var projects = _.user.projects;
            var prepare = [];
            for (var key in projects) {
              var project = Project.get(projects[key]);
              if (project && project.sync) {
                prepare.push(project);
              }
            }

            now.syncProjects(_.client, _.user.id, prepare, function (object) {

              if (object.status == 'update') {
                var projects = object.data;

                for (var key in projects) {
                  var project = projects[key];
                  Project.save(project);

                  joinList.push(project.id);
                }

                now.joinGroups(_.client, joinList, function () {
                  console.log ('Join projects success');
                });

              }

              // List projects
              var projects = _.user.projects;
              for (var index = 0; index < projects.length; index++) {
                var project = Project.get(projects[index]);
                if (project) {
                  var list = _.tmpl('project_list', project);
                  $('#projects-list-menu').append(list);
                }
              }

            });

          } else {

            _.persistent.clear();
            location.reload();

          }

        });
      }

      $('#sync-status').text('Online');

      // User real-time synchronization
      now.clientUpdateUser = function (user) {

        console.log ('server-debug(create): user - ' +
                     user.id + ', ' +
                     user.updated);

        if (user.updated > _.user.updated) {
          User.save(user);
        }

      }

      // Project real-time synchronization
      now.clientCreateProject = function (client, serverProject) {

        console.log ('server-debug(create): project - ' +
                     serverProject.id + ', ' +
                     serverProject.updated + ', ' +
                     serverProject.modified);

        if (client != _.client) {
          Project.save(serverProject);
          now.joinGroups(_.client, [serverProject.id]);

          var list = _.tmpl('project_list', serverProject);
          $('#projects-list-menu').append(list);
        }

      }

      now.clientUpdateProject = function (client, serverProject) {

        console.log ('server-debug(update): project - ' +
                     serverProject.id + ', ' +
                     serverProject.updated + ', ' +
                     serverProject.modified);

        var clientProject = Project.get(serverProject.id);
        if (serverProject.updated > clientProject.updated ||
            serverProject.modified != clientProject.modified) {
          Project.save(serverProject);
        }

        clientProject = Project.get(serverProject.id);
        $('#project-menu-' + clientProject.id).text(clientProject.name);

        if (_.project.id == clientProject.id) {
          $('#project-name').text(clientProject.name);
          _.project = clientProject;
        }

      }

      // Task real-time synchronization
      now.clientCreateTask = function (from, task) {
        console.log ('server-debug(create): (' + from + ',' + task.id + ') ' + task.detail);
        if (from == _.client) { return; }

        if (!Task.get(task.id)) {
          Task.save(task);

          var iteration = Iteration.get(_.project.currentIteration());
          iteration.addTask(task);
          Iteration.save(iteration);

          var _task = Task.get(task.id);
          $('#' + _task.status).append(_.tmpl('task', _task));
          $('#' + _task.id).attr('draggable', true);
          console.log ('server(create): ' + _task.status + ', ' + _task.detail);
        }

      };

      now.clientUpdateTask = function (from, task) {
        console.log ('server-debug(update): (' + from + ',' + task.id + ') '  + task.detail);
        if (from == _.client) { return; }

        var _task = Task.get(task.id);
        _task.setDetail(task.detail);
        _task.updated = task.updated;
        _task.status = task.status;
        Task.save(_task);

        console.log ('server(update): ' + _task.status + ', ' + _task.detail);

        $('#' + _task.id).remove();
        $('#' + _task.status).append(_.tmpl('task', _task));
        $('#' + _task.id).attr('draggable', true);
      }

      now.clientRemoveTask = function (from, id) {
        console.log ('server-debug(remove): (' + from + ',' + id + ')');
        if (from == _.client) { return; }

        console.log ('server(remove): ' + id);

        if ($('#' + id).length > 0) {
          $('#' + id).remove();
          Task.remove(id);

          var iteration = Iteration.get(_.project.currentIteration());
          iteration.removeTask(id);
          Iteration.save(iteration);
        }

      }

      var iteration = Iteration.get(_.project.currentIteration());
      var prepareSync = [];
      var tasks = iteration.tasks;

      for (var taskID in tasks) {
        var task = Task.get(taskID);
        if (task) {
          prepareSync.push(task);
        }
      }

      var prepareRemove = [];
      var removed = _.persistent.get('removed');

      if (removed) {
        prepareRemove = removed.list;
        _.persistent.remove('removed');
      }

      now.joinGroups(_.client, [iteration.id], function() {

        $('#sync-status').text('Syncing');
        now.syncAllTask(iteration.id , prepareSync, prepareRemove, function() {
          $('#sync-status').text('Online');
        });

      });

    });
  } else {

    // List projects
    var projects = _.user.projects;
    for (var index = 0; index < projects.length; index++) {
      var project = Project.get(projects[index]);
      if (project) {
        var list = _.tmpl('project_list', project);
        $('#projects-list-menu').append(list);
      }
    }

    // Update login menu
    $('#logging-in-menu').hide();
    if (_.user.anonymous) {
      $('#logged-out-menu').hide();
    } else {
      $('#logged-in-status').css('display', 'block');
      $('#logged-in-user').text(_.user.username);

      $('#logged-in-menu').css('display', 'block');
      $('#log-out-menu').remove();

      if (_.project.sync) {
        $('#end-iteration-button').attr('disabled', true);
      }
    }

  }

  // Online/Offline event
  $(window).bind('online', function (e) {
    console.log ('Online');
    window.location.reload()
  });

  $(window).bind('offline', function(e) {
    console.log ('Offline');
    $('#sync-status').text('Offline');

    if (_.project.sync) {
      $('#end-iteration-button').attr('disabled', true);
    }
  });

}<|endoftext|>


<commit_before>LANGUAGES.javascript = {
  defaultMode: {
    lexems: [UNDERSCORE_IDENT_RE],
    contains: ['string', 'comment', 'number', 'regexp', 'function'],
    keywords: {
      'keyword': {'in': 1, 'if': 1, 'for': 1, 'while': 1, 'finally': 1, 'var': 1, 'new': 1, 'function': 1, 'do': 1, 'return': 1, 'void': 1, 'else': 1, 'break': 1, 'catch': 1, 'instanceof': 1, 'with': 1, 'throw': 1, 'case': 1, 'default': 1, 'try': 1, 'this': 1, 'switch': 1, 'continue': 1, 'typeof': 1, 'delete': 1},
      'literal': {'true': 1, 'false': 1, 'null': 1}
    }
  },
  modes: [
    C_LINE_COMMENT_MODE,
    C_BLOCK_COMMENT_MODE,
    C_NUMBER_MODE,
    APOS_STRING_MODE,
    QUOTE_STRING_MODE,
    BACKSLASH_ESCAPE,
    {
      className: 'regexp',
      begin: '/.*?[^\\\\/]/[gim]*', end: '^'
    },
    {
      className: 'function',
      begin: 'function ', end: '{',
      lexems: [UNDERSCORE_IDENT_RE],
      keywords: {'function': 1},
      contains: ['title', 'params']
    },
    {
      className: 'title',
      begin: UNDERSCORE_IDENT_RE, end: '^'
    },
    {
      className: 'params',
      begin: '\\(', end: '\\)',
      contains: ['string', 'comment']
    }
  ]
};//javascript<commit_msg>function в javascript не обязана отделяться пробелом справа<commit_after>LANGUAGES.javascript = {
  defaultMode: {
    lexems: [UNDERSCORE_IDENT_RE],
    contains: ['string', 'comment', 'number', 'regexp', 'function'],
    keywords: {
      'keyword': {'in': 1, 'if': 1, 'for': 1, 'while': 1, 'finally': 1, 'var': 1, 'new': 1, 'function': 1, 'do': 1, 'return': 1, 'void': 1, 'else': 1, 'break': 1, 'catch': 1, 'instanceof': 1, 'with': 1, 'throw': 1, 'case': 1, 'default': 1, 'try': 1, 'this': 1, 'switch': 1, 'continue': 1, 'typeof': 1, 'delete': 1},
      'literal': {'true': 1, 'false': 1, 'null': 1}
    }
  },
  modes: [
    C_LINE_COMMENT_MODE,
    C_BLOCK_COMMENT_MODE,
    C_NUMBER_MODE,
    APOS_STRING_MODE,
    QUOTE_STRING_MODE,
    BACKSLASH_ESCAPE,
    {
      className: 'regexp',
      begin: '/.*?[^\\\\/]/[gim]*', end: '^'
    },
    {
      className: 'function',
      begin: 'function\\b', end: '{',
      lexems: [UNDERSCORE_IDENT_RE],
      keywords: {'function': 1},
      contains: ['title', 'params']
    },
    {
      className: 'title',
      begin: UNDERSCORE_IDENT_RE, end: '^'
    },
    {
      className: 'params',
      begin: '\\(', end: '\\)',
      contains: ['string', 'comment']
    }
  ]
};//javascript<|endoftext|>