<commit_before>var sys = require('sys');
var nerve = require('./../deps/nerve/nerve');
var pls = require('./genpls');
var redis = require('./../deps/redis-node/redis');
var view = require('./view');
var utils = require('./../utils');
var _ = require('./../deps/underscore/underscore')._;

// a little different
process.mixin( require('./../utils') )

var dbError = function(res) {
    return function() {
        view.output( res, 'error', {
            message : "Error connecting to database"
            , status_code : 500
        });
    }
}

var redirectToReferer = function(req, res, message) {
    res.sendHeader( 303, { "Location" : req.headers['referer'] } );
    res.respond( message );
}

var playlist = exports.playlist = function( req, res, action, arg ) {

    var pls_id = req.session['session_id'];
    var actions = {
        'add': function() {
            playlist.add( pls_id, function(success) {
                if( success )
                    req.session['message'] = 'Song Added';
                else( success )
                    req.session['message'] = 'error';
                redirectToReferer( req, res );
            })
        }
      , 'remove': function() {}
      , 'download': function() {}
    };

    if( _.isFunction( actions[action] ) )
        actions[action]( arg );

    if( req.session['test'] )
        view.output( res, 'playlist', { 'greeting' : req.session['test'] } )

}

var listPlaylist = exports.listPlaylist = function( res ) {
    util.newRedis(
        function() {
        },
        dbError(res)
    );
}

exports.listArtists = function(req, res, page) {
    page = page || 0;
    utils.newRedis(
        function() {
            this.redis.lrange($artistnames(), page*10 || 0, (page*10 || 0)+10).addCallback(
            function(list) {
                view.output( res, 'artistlist', {
                    'artists':_.map(list || [], function(m) {
                                return JSON.parse(m);
                              })
                    , 'title': 'Artists'
                    , 'message' : req.session['message']
                });
            });
        },

        dbError(res)
    );
}

exports.artist = function(req, res, hash) {
    var output = {
        'songs':[]
      , 'message' : req.session['message']
    }
    utils.newRedis( function() {
        var r = this.redis;
        r.smembers( $artistsongs(hash) ).addCallback(
        function(songs) {
            _.each( songs, function(song, index) {
                r.get( $song(song) ).addCallback( function(s) {
                    output['songs'].push(JSON.parse(s));
                    if( index == songs.length - 1 ) {
                        // getting the artist from the song is cheating, but it works
                        // and is faster and cleaner than another redis query
                        output['title'] = "Artist - " + JSON.parse(s).artist;
                        view.output(res, 'artistsongs', output);
                    }
                });
            });
        });
    },

    dbError(res)
    );
}

exports.album = function(req, res, hash) {
    var output = {
        'songs':[]
      , 'message' : req.session['message']
    }
    utils.newRedis( function() {
        var r = this.redis;
        r.smembers( $albumsongs(hash) ).addCallback(
        function(songs) {
            _.each( songs, function(song, index) {
                r.get( $song(song) ).addCallback( function(s) {
                    output['songs'].push(JSON.parse(s));
                    if( index == songs.length - 1 ) {
                        // getting the artist from the song is cheating, but it works
                        // and is faster and cleaner than another redis query
                        output['songs'] = _.sortBy( output['songs'], function( song ) {
                            return song.track;
                        });
                        output['title'] = "Album - " + JSON.parse(s).album;
                        view.output(res, 'albumsongs', output);
                    }
                });
            });
        });
    },
    dbError(res)
    );
}

exports.listSongs = function(req, res) {
    var resp = "";
    utils.newRedis(function() {
        var r = this.redis;
        r.keys($song('*')).addCallback( function(songlist) {
            _.each(songlist, function( songkey, i ) {
                r.get(songkey).addCallback( function( songdata ) {
                    view.render('info', JSON.parse(songdata), function(out) {
                        resp += out;

                        if( i == songlist.length-1 ) {
                            res.respond( resp );
                            r.close();
                        }
                    });
                })
            });
            r.close();
        });
    },
    dbError(res)
    );
}

exports.songInfo = function( req, res, songhash ) {
    utils.newRedis( function() {
        this.redis.get($song(songhash)).addCallback( function(meta) {
                view.output(res, 'info', JSON.parse(meta));
        });
    },
    dbError(res)
    );
};
<commit_msg>Require playlist module which will implement playlist add/remove/download using redis<commit_after>var sys = require('sys');
var nerve = require('./../deps/nerve/nerve');
var pls = require('./genpls');
var redis = require('./../deps/redis-node/redis');
var view = require('./view');
var utils = require('./../utils');
var playlist = require('./playlist');
var _ = require('./../deps/underscore/underscore')._;

// a little different
process.mixin( require('./../utils') )

var dbError = function(res) {
    return function() {
        view.output( res, 'error', {
            message : "Error connecting to database"
            , status_code : 500
        });
    }
}

var redirectToReferer = function(req, res, message) {
    res.sendHeader( 303, { "Location" : req.headers['referer'] } );
    res.respond( message );
}

var playlist = exports.playlist = function( req, res, action, arg ) {

    var pls_id = req.session['session_id'];
    var actions = {
        'add': function() {
            playlist.add( pls_id, function(success) {
                if( success )
                    req.session['message'] = 'Song Added';
                else( success )
                    req.session['message'] = 'error';
                redirectToReferer( req, res );
            })
        }
      , 'remove': function() {}
      , 'download': function() {}
    };

    if( _.isFunction( actions[action] ) )
        actions[action]( arg );

    if( req.session['test'] )
        view.output( res, 'playlist', { 'greeting' : req.session['test'] } )

}

var listPlaylist = exports.listPlaylist = function( res ) {
    util.newRedis(
        function() {
        },
        dbError(res)
    );
}

exports.listArtists = function(req, res, page) {
    page = page || 0;
    utils.newRedis(
        function() {
            this.redis.lrange($artistnames(), page*10 || 0, (page*10 || 0)+10).addCallback(
            function(list) {
                view.output( res, 'artistlist', {
                    'artists':_.map(list || [], function(m) {
                                return JSON.parse(m);
                              })
                    , 'title': 'Artists'
                    , 'message' : req.session['message']
                });
            });
        },

        dbError(res)
    );
}

exports.artist = function(req, res, hash) {
    var output = {
        'songs':[]
      , 'message' : req.session['message']
    }
    utils.newRedis( function() {
        var r = this.redis;
        r.smembers( $artistsongs(hash) ).addCallback(
        function(songs) {
            _.each( songs, function(song, index) {
                r.get( $song(song) ).addCallback( function(s) {
                    output['songs'].push(JSON.parse(s));
                    if( index == songs.length - 1 ) {
                        // getting the artist from the song is cheating, but it works
                        // and is faster and cleaner than another redis query
                        output['title'] = "Artist - " + JSON.parse(s).artist;
                        view.output(res, 'artistsongs', output);
                    }
                });
            });
        });
    },

    dbError(res)
    );
}

exports.album = function(req, res, hash) {
    var output = {
        'songs':[]
      , 'message' : req.session['message']
    }
    utils.newRedis( function() {
        var r = this.redis;
        r.smembers( $albumsongs(hash) ).addCallback(
        function(songs) {
            _.each( songs, function(song, index) {
                r.get( $song(song) ).addCallback( function(s) {
                    output['songs'].push(JSON.parse(s));
                    if( index == songs.length - 1 ) {
                        // getting the artist from the song is cheating, but it works
                        // and is faster and cleaner than another redis query
                        output['songs'] = _.sortBy( output['songs'], function( song ) {
                            return song.track;
                        });
                        output['title'] = "Album - " + JSON.parse(s).album;
                        view.output(res, 'albumsongs', output);
                    }
                });
            });
        });
    },
    dbError(res)
    );
}

exports.listSongs = function(req, res) {
    var resp = "";
    utils.newRedis(function() {
        var r = this.redis;
        r.keys($song('*')).addCallback( function(songlist) {
            _.each(songlist, function( songkey, i ) {
                r.get(songkey).addCallback( function( songdata ) {
                    view.render('info', JSON.parse(songdata), function(out) {
                        resp += out;

                        if( i == songlist.length-1 ) {
                            res.respond( resp );
                            r.close();
                        }
                    });
                })
            });
            r.close();
        });
    },
    dbError(res)
    );
}

exports.songInfo = function( req, res, songhash ) {
    utils.newRedis( function() {
        this.redis.get($song(songhash)).addCallback( function(meta) {
                view.output(res, 'info', JSON.parse(meta));
        });
    },
    dbError(res)
    );
};
<|endoftext|>


<commit_before>/* Copyright 2013 Rob Wu <gwnRob@gmail.com>
 * https://github.com/Rob--W/grab-to-pan.js
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define('pdfjs-web/grab_to_pan', ['exports'], factory);
  } else if (typeof exports !== 'undefined') {
    factory(exports);
  } else {
    factory((root.pdfjsWebGrabToPan = {}));
  }
}(this, function (exports) {
  /**
   * Construct a GrabToPan instance for a given HTML element.
   * @param options.element {Element}
   * @param options.ignoreTarget {function} optional. See `ignoreTarget(node)`
   * @param options.onActiveChanged {function(boolean)} optional. Called
   *  when grab-to-pan is (de)activated. The first argument is a boolean that
   *  shows whether grab-to-pan is activated.
   */
  function GrabToPan(options) {
    this.element = options.element;
    this.document = options.element.ownerDocument;
    if (typeof options.ignoreTarget === 'function') {
      this.ignoreTarget = options.ignoreTarget;
    }
    this.onActiveChanged = options.onActiveChanged;

    // Bind the contexts to ensure that `this` always points to
    // the GrabToPan instance.
    this.activate = this.activate.bind(this);
    this.deactivate = this.deactivate.bind(this);
    this.toggle = this.toggle.bind(this);
    this._onmousedown = this._onmousedown.bind(this);
    this._onmousemove = this._onmousemove.bind(this);
    this._endPan = this._endPan.bind(this);

    // This overlay will be inserted in the document when the mouse moves during
    // a grab operation, to ensure that the cursor has the desired appearance.
    var overlay = this.overlay = document.createElement('div');
    overlay.className = 'grab-to-pan-grabbing';
  }
  GrabToPan.prototype = {
    /**
     * Class name of element which can be grabbed
     */
    CSS_CLASS_GRAB: 'grab-to-pan-grab',

    /**
     * Bind a mousedown event to the element to enable grab-detection.
     */
    activate: function GrabToPan_activate() {
      if (!this.active) {
        this.active = true;
        this.element.addEventListener('mousedown', this._onmousedown, true);
        this.element.classList.add(this.CSS_CLASS_GRAB);
        if (this.onActiveChanged) {
          this.onActiveChanged(true);
        }
      }
    },

    /**
     * Removes all events. Any pending pan session is immediately stopped.
     */
    deactivate: function GrabToPan_deactivate() {
      if (this.active) {
        this.active = false;
        this.element.removeEventListener('mousedown', this._onmousedown, true);
        this._endPan();
        this.element.classList.remove(this.CSS_CLASS_GRAB);
        if (this.onActiveChanged) {
          this.onActiveChanged(false);
        }
      }
    },

    toggle: function GrabToPan_toggle() {
      if (this.active) {
        this.deactivate();
      } else {
        this.activate();
      }
    },

    /**
     * Whether to not pan if the target element is clicked.
     * Override this method to change the default behaviour.
     *
     * @param node {Element} The target of the event
     * @return {boolean} Whether to not react to the click event.
     */
    ignoreTarget: function GrabToPan_ignoreTarget(node) {
      // Use matchesSelector to check whether the clicked element
      // is (a child of) an input element / link
      return node[matchesSelector](
        'a[href], a[href] *, input, textarea, button, button *, select, option'
      );
    },

    /**
     * @private
     */
    _onmousedown: function GrabToPan__onmousedown(event) {
      if (event.button !== 0 || this.ignoreTarget(event.target)) {
        return;
      }
      if (event.originalTarget) {
        try {
          /* jshint expr:true */
          event.originalTarget.tagName;
        } catch (e) {
          // Mozilla-specific: element is a scrollbar (XUL element)
          return;
        }
      }

      this.scrollLeftStart = this.element.scrollLeft;
      this.scrollTopStart = this.element.scrollTop;
      this.clientXStart = event.clientX;
      this.clientYStart = event.clientY;
      this.document.addEventListener('mousemove', this._onmousemove, true);
      this.document.addEventListener('mouseup', this._endPan, true);
      // When a scroll event occurs before a mousemove, assume that the user
      // dragged a scrollbar (necessary for Opera Presto, Safari and IE)
      // (not needed for Chrome/Firefox)
      this.element.addEventListener('scroll', this._endPan, true);
      event.preventDefault();
      event.stopPropagation();
      this.document.documentElement.classList.add(this.CSS_CLASS_GRABBING);

      var focusedElement = document.activeElement;
      if (focusedElement && !focusedElement.contains(event.target)) {
        focusedElement.blur();
      }
    },

    /**
     * @private
     */
    _onmousemove: function GrabToPan__onmousemove(event) {
      this.element.removeEventListener('scroll', this._endPan, true);
      if (isLeftMouseReleased(event)) {
        this._endPan();
        return;
      }
      var xDiff = event.clientX - this.clientXStart;
      var yDiff = event.clientY - this.clientYStart;
      this.element.scrollTop = this.scrollTopStart - yDiff;
      this.element.scrollLeft = this.scrollLeftStart - xDiff;
      if (!this.overlay.parentNode) {
        document.body.appendChild(this.overlay);
      }
    },

    /**
     * @private
     */
    _endPan: function GrabToPan__endPan() {
      this.element.removeEventListener('scroll', this._endPan, true);
      this.document.removeEventListener('mousemove', this._onmousemove, true);
      this.document.removeEventListener('mouseup', this._endPan, true);
      if (this.overlay.parentNode) {
        this.overlay.parentNode.removeChild(this.overlay);
      }
    }
  };

  // Get the correct (vendor-prefixed) name of the matches method.
  var matchesSelector;
  ['webkitM', 'mozM', 'msM', 'oM', 'm'].some(function(prefix) {
    var name = prefix + 'atches';
    if (name in document.documentElement) {
      matchesSelector = name;
    }
    name += 'Selector';
    if (name in document.documentElement) {
      matchesSelector = name;
    }
    return matchesSelector; // If found, then truthy, and [].some() ends.
  });

  // Browser sniffing because it's impossible to feature-detect
  // whether event.which for onmousemove is reliable
  var isNotIEorIsIE10plus = !document.documentMode || document.documentMode > 9;
  var chrome = window.chrome;
  var isChrome15OrOpera15plus = chrome && (chrome.webstore || chrome.app);
  //                                       ^ Chrome 15+       ^ Opera 15+
  var isSafari6plus = /Apple/.test(navigator.vendor) &&
                      /Version\/([6-9]\d*|[1-5]\d+)/.test(navigator.userAgent);

  /**
   * Whether the left mouse is not pressed.
   * @param event {MouseEvent}
   * @return {boolean} True if the left mouse button is not pressed.
   *                   False if unsure or if the left mouse button is pressed.
   */
  function isLeftMouseReleased(event) {
    if ('buttons' in event && isNotIEorIsIE10plus) {
      // http://www.w3.org/TR/DOM-Level-3-Events/#events-MouseEvent-buttons
      // Firefox 15+
      // Internet Explorer 10+
      return !(event.buttons | 1);
    }
    if (isChrome15OrOpera15plus || isSafari6plus) {
      // Chrome 14+
      // Opera 15+
      // Safari 6.0+
      return event.which === 0;
    }
  }

  exports.GrabToPan = GrabToPan;
}));
<commit_msg>Update grab_to_pan.js<commit_after>/* Copyright 2013 Rob Wu <rob@robwu.nl>
 * https://github.com/Rob--W/grab-to-pan.js
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    define('pdfjs-web/grab_to_pan', ['exports'], factory);
  } else if (typeof exports !== 'undefined') {
    factory(exports);
  } else {
    factory((root.pdfjsWebGrabToPan = {}));
  }
}(this, function (exports) {
  /**
   * Construct a GrabToPan instance for a given HTML element.
   * @param options.element {Element}
   * @param options.ignoreTarget {function} optional. See `ignoreTarget(node)`
   * @param options.onActiveChanged {function(boolean)} optional. Called
   *  when grab-to-pan is (de)activated. The first argument is a boolean that
   *  shows whether grab-to-pan is activated.
   */
  function GrabToPan(options) {
    this.element = options.element;
    this.document = options.element.ownerDocument;
    if (typeof options.ignoreTarget === 'function') {
      this.ignoreTarget = options.ignoreTarget;
    }
    this.onActiveChanged = options.onActiveChanged;

    // Bind the contexts to ensure that `this` always points to
    // the GrabToPan instance.
    this.activate = this.activate.bind(this);
    this.deactivate = this.deactivate.bind(this);
    this.toggle = this.toggle.bind(this);
    this._onmousedown = this._onmousedown.bind(this);
    this._onmousemove = this._onmousemove.bind(this);
    this._endPan = this._endPan.bind(this);

    // This overlay will be inserted in the document when the mouse moves during
    // a grab operation, to ensure that the cursor has the desired appearance.
    var overlay = this.overlay = document.createElement('div');
    overlay.className = 'grab-to-pan-grabbing';
  }
  GrabToPan.prototype = {
    /**
     * Class name of element which can be grabbed
     */
    CSS_CLASS_GRAB: 'grab-to-pan-grab',

    /**
     * Bind a mousedown event to the element to enable grab-detection.
     */
    activate: function GrabToPan_activate() {
      if (!this.active) {
        this.active = true;
        this.element.addEventListener('mousedown', this._onmousedown, true);
        this.element.classList.add(this.CSS_CLASS_GRAB);
        if (this.onActiveChanged) {
          this.onActiveChanged(true);
        }
      }
    },

    /**
     * Removes all events. Any pending pan session is immediately stopped.
     */
    deactivate: function GrabToPan_deactivate() {
      if (this.active) {
        this.active = false;
        this.element.removeEventListener('mousedown', this._onmousedown, true);
        this._endPan();
        this.element.classList.remove(this.CSS_CLASS_GRAB);
        if (this.onActiveChanged) {
          this.onActiveChanged(false);
        }
      }
    },

    toggle: function GrabToPan_toggle() {
      if (this.active) {
        this.deactivate();
      } else {
        this.activate();
      }
    },

    /**
     * Whether to not pan if the target element is clicked.
     * Override this method to change the default behaviour.
     *
     * @param node {Element} The target of the event
     * @return {boolean} Whether to not react to the click event.
     */
    ignoreTarget: function GrabToPan_ignoreTarget(node) {
      // Use matchesSelector to check whether the clicked element
      // is (a child of) an input element / link
      return node[matchesSelector](
        'a[href], a[href] *, input, textarea, button, button *, select, option'
      );
    },

    /**
     * @private
     */
    _onmousedown: function GrabToPan__onmousedown(event) {
      if (event.button !== 0 || this.ignoreTarget(event.target)) {
        return;
      }
      if (event.originalTarget) {
        try {
          /* jshint expr:true */
          event.originalTarget.tagName;
        } catch (e) {
          // Mozilla-specific: element is a scrollbar (XUL element)
          return;
        }
      }

      this.scrollLeftStart = this.element.scrollLeft;
      this.scrollTopStart = this.element.scrollTop;
      this.clientXStart = event.clientX;
      this.clientYStart = event.clientY;
      this.document.addEventListener('mousemove', this._onmousemove, true);
      this.document.addEventListener('mouseup', this._endPan, true);
      // When a scroll event occurs before a mousemove, assume that the user
      // dragged a scrollbar (necessary for Opera Presto, Safari and IE)
      // (not needed for Chrome/Firefox)
      this.element.addEventListener('scroll', this._endPan, true);
      event.preventDefault();
      event.stopPropagation();
      this.document.documentElement.classList.add(this.CSS_CLASS_GRABBING);

      var focusedElement = document.activeElement;
      if (focusedElement && !focusedElement.contains(event.target)) {
        focusedElement.blur();
      }
    },

    /**
     * @private
     */
    _onmousemove: function GrabToPan__onmousemove(event) {
      this.element.removeEventListener('scroll', this._endPan, true);
      if (isLeftMouseReleased(event)) {
        this._endPan();
        return;
      }
      var xDiff = event.clientX - this.clientXStart;
      var yDiff = event.clientY - this.clientYStart;
      this.element.scrollTop = this.scrollTopStart - yDiff;
      this.element.scrollLeft = this.scrollLeftStart - xDiff;
      if (!this.overlay.parentNode) {
        document.body.appendChild(this.overlay);
      }
    },

    /**
     * @private
     */
    _endPan: function GrabToPan__endPan() {
      this.element.removeEventListener('scroll', this._endPan, true);
      this.document.removeEventListener('mousemove', this._onmousemove, true);
      this.document.removeEventListener('mouseup', this._endPan, true);
      if (this.overlay.parentNode) {
        this.overlay.parentNode.removeChild(this.overlay);
      }
    }
  };

  // Get the correct (vendor-prefixed) name of the matches method.
  var matchesSelector;
  ['webkitM', 'mozM', 'msM', 'oM', 'm'].some(function(prefix) {
    var name = prefix + 'atches';
    if (name in document.documentElement) {
      matchesSelector = name;
    }
    name += 'Selector';
    if (name in document.documentElement) {
      matchesSelector = name;
    }
    return matchesSelector; // If found, then truthy, and [].some() ends.
  });

  // Browser sniffing because it's impossible to feature-detect
  // whether event.which for onmousemove is reliable
  var isNotIEorIsIE10plus = !document.documentMode || document.documentMode > 9;
  var chrome = window.chrome;
  var isChrome15OrOpera15plus = chrome && (chrome.webstore || chrome.app);
  //                                       ^ Chrome 15+       ^ Opera 15+
  var isSafari6plus = /Apple/.test(navigator.vendor) &&
                      /Version\/([6-9]\d*|[1-5]\d+)/.test(navigator.userAgent);

  /**
   * Whether the left mouse is not pressed.
   * @param event {MouseEvent}
   * @return {boolean} True if the left mouse button is not pressed.
   *                   False if unsure or if the left mouse button is pressed.
   */
  function isLeftMouseReleased(event) {
    if ('buttons' in event && isNotIEorIsIE10plus) {
      // http://www.w3.org/TR/DOM-Level-3-Events/#events-MouseEvent-buttons
      // Firefox 15+
      // Internet Explorer 10+
      return !(event.buttons & 1);
    }
    if (isChrome15OrOpera15plus || isSafari6plus) {
      // Chrome 14+
      // Opera 15+
      // Safari 6.0+
      return event.which === 0;
    }
  }

  exports.GrabToPan = GrabToPan;
}));
<|endoftext|>


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

    var idUser = 1;
    var sessionId = "token";

    events = getRappels(idUser, sessionId);

    events = [{
        title: "Olympics",
        location: "Sochi",
        start: {
            date: "20140607", time: "17.00"
        },
        end: {
            date: "20140623", time: "17.00"
        }}]

    var selectedDate;

    var options = {
        onDayClick: function(e) {
            selectedDate = e.data.date;
            $("#shareEvent").removeAttr("disabled");
            $("#deleteEvent").removeAttr("disabled");
        },
        onGridShow: function(e) {
            $("#shareEvent").attr("disabled", "disabled");
            $("#deleteEvent").attr("disabled", "disabled");
        },
        color: "green",
        events: events,
        firstDayOfWeek: "Monday",
        showDays: true,
        dayHuman: [
            ["D", "Dimanche"],
            ["L", "Lundi"],
            ["M", "Mardi"],
            ["M", "Mercredi"],
            ["J", "Jeudi"],
            ["V", "Vendredi"],
            ["S", "Samedi"]
        ],
        monthHuman: [
            ["Janv", "Janvier"],
            ["Fevr", "Février"],
            ["Mars", "Mars"],
            ["Avr", "Avril"],
            ["Mai", "Mai"],
            ["Juin", "Juin"],
            ["Juill", "Juillet"],
            ["Août", "Août"],
            ["Sept", "Septembre"],
            ["Oct", "Octobre"],
            ["Nov", "Novembre"],
            ["Dec", "Décembre"]
        ]
    };

    $("#loadCalendar").kalendar(options); //Load the calendar
    $("#startDate, #endDate").datetimepicker();

    $("#addEvent").on("click", function() {
        var button = $("#formAddEvent").find("button[type=submit]");
        buttonBehaviourSubmitDefault(button);
    });

    $("#formAddEvent").on("submit", function(e) {
        e.preventDefault();
        var button = $(this).find("button[type=submit]");
        var begin = new Date($(this.startDate).val()).getTime();
        var end = new Date($(this.endDate).val()).getTime();
        if (begin > end) {
            var error = "La date de fin doit être supérieure à celle de début";
            buttonBehaviourSubmitError(button, error);
        }
        else {
            var title = $(this.title).val();
            var location = $(this.location).val();

            if (addRappel(idUser, sessionId, title, location, begin, end)) {
                var message = "Le rappel a été ajouté avec succès";
                buttonBehaviourSubmitSuccess(button, message);
            }
            else {
                var error = "Problème lors de l'ajout de l'évènement";
                buttonBehaviourSubmitError(button, error);
            }
        }
    });

    //SHARE
    $('button#shareEvent').on('click', function(e)
    {
        e.preventDefault();
        var button = $("#formShareEvent").find("button[type=submit]");
        buttonBehaviourSubmitDefault(button);

        var dayEvents = getDayEvents(selectedDate);
        var shareContentTableModal = $("#shareEventContent tbody");
        var eventsTable = $("div#shareEventsTable");

        $("#shareEventsContacts").hide();

        eventsTable.show();
        shareContentTableModal.empty(); //cleaning before append

        for (var i = 0; i < dayEvents.length; i++) {
            var templateEvent = getRowEvent(dayEvents[i]);
            shareContentTableModal.append(templateEvent);
        }

        var message = 'Sélectionner les contacts';
        button.attr('id', 'shareFirstStep');
        buttonBehaviourSubmitDefault(button, message);

        $("button#shareFirstStep").on("click", function(e){
            e.preventDefault();
            console.log("test");
            var button = $(this);

            // At least one event is checked
            if (isAtLeastOneCheckedBoxChecked('#tableShareEvents')) {
                $("input:checkbox:not(:checked)").each(function()
                                                       {
                                                           $(this).closest("tr").remove();
                                                       });
                $("div#shareEventsContacts tbody").empty();
                $("div#shareEventsContacts").fadeIn(); // Display contacts

                var message = "Partager";
                button.attr('id', 'shareSecondStep');
                buttonBehaviourSubmitDefault(button, message);

                var contacts = getContacts(idUser, sessionId);
                contacts = [{
                    id: 1,
                    name: 'franck',
                    email: 'test@lol'
                }];
                // if at leasts 1 contact
                if (typeof contacts != 'undefined') {
                    for (var i = 0; i < contacts.length; i++) {
                        var templateContact = getRowContact(contacts[i]);
                        $("table#tableShareContacts tbody").append(templateContact);
                    }

                    $("button#shareSecondStep").on("click", function(e) {
                        e.preventDefault();

                        if (isAtLeastOneCheckedBoxChecked('#shareEventsContacts')) {

                            var status = true;
                            $("#tableShareEvents input:checkbox:checked").each(function() { // each event
                                console.log(this);
                                $("#tableShareContacts input:checkbox:checked").each(function(){ // each contact
                                    console.log("salut2");
                                    var rappelId;
                                    var contactId;
                                    var contactType;
                                    //if(!shareRappel(idUser, sessionId, rappelId, contactId, contactType)){
                                    //  status = false;
                                    //}
                                });
                            });
                            if(status){
                                var message = "Rappels partagés avec succès";
                                buttonBehaviourSubmitSuccess(button, message);
                            }
                            else{
                                var error = "Echec du partage";
                                buttonBehaviourSubmitError(button, error);
                            }
                        }
                        else{ // No contact checked
                            var error = "Aucun contact sélectionné";
                            buttonBehaviourSubmitError(button, error);
                        }
                    });
                }
                else {
                    $("div#shareEventsContacts table").remove();
                    var error = "Aucun contact";
                    buttonBehaviourSubmitError(button, error);
                }

            }
            else { // No event checked
                var error = "Sélectionner au moins un rappel";
                buttonBehaviourSubmitError(button, error);
            }
        });

    });

    $('button#deleteEvent').on('click', function()
    {
        var dayEvents = getDayEvents(selectedDate);
        var deleteContentModal = $("#deleteEventContent tbody");

        deleteContentModal.empty(); //cleaning before append

        for (var i = 0; i < dayEvents.length; i++) {
            var templateEvent = getRowEvent(dayEvents[i]);

            deleteContentModal.append(templateEvent);
        }
        var button = $("#formDeleteEvent").find("button[type=submit]");
        buttonBehaviourSubmitDefault(button);
    });

    $("#formDeleteEvent").on("submit", function(e) {
        e.preventDefault();
        var button = $(this).find('button[type=submit]');
        if (isAtLeastOneCheckedBoxChecked("tableDeleteEvent")) {
            $("input:checkbox:checked").each(function()
            {
                var event = $(this).closest("tr");
                var rappelId = event.attr("id");
                //remove from the DOM
                if (removeRappel(idUser, sessionId, rappelId)) {
                    event.remove();
                    var message = "Recharger la page pour avoir le calendrier à jour";
                    buttonBehaviourSubmitSuccess(button, message);
                }
                else {
                    var error = "Les rappels n'ont pas pu être supprimés";
                    buttonBehaviourSubmitError(button, error);
                }
            });
        }
        else{
            var error = "Sélectionner au moins un rappel";
            buttonBehaviourSubmitError(button, error);
        }
    });
});

// return events of the day
function getDayEvents(datePicked) {
    var dayEvents = [];
    //Convert into date
    datePicked = getRawDate(new Date(datePicked));
    for (var i = 0; i < events.length; i++) {
        var startDate = getRawDate(events[i].start.d);
        var endDate = getRawDate(events[i].end.d);

        if (datePicked >= startDate && datePicked <= endDate) {
            dayEvents.push(events[i]);
        }
    }
    return dayEvents;
}

function getFormattedDate(dateToBeFormatted, format) {
    return $.datepicker.formatDate(format, new Date(dateToBeFormatted));
}

function getFancyDate(date) {
    return getFormattedDate(date, 'dd MM yy');
}

function getRawDate(date) {
    return getFormattedDate(date, 'yymmdd');
}

function getRawHours(date) {
    date = new Date();
    return date.getHours() + date.getMinutes();
}

function getRowEvent(event) {
    var source = $("#event-table-template").html();
    var context = {
        id: event.id,
        title: event.title,
        start: getFancyDate((event.start.d)),
        end: getFancyDate(event.end.d),
        location: event.location
    };
    var template = Handlebars.compile(source);
    var html = template(context);
    return html;
}

function getRowContact(contact) {
    var source = $("#contact-table-template").html();
    var context = {
        id: contact.id,
        name: contact.name,
        email: contact.email
    }
    var template = Handlebars.compile(source);
    var html = template(context);
    return html;
}

function isAtLeastOneCheckedBoxChecked(container) {
    var atLeastOneIsChecked = $(container + ' :checkbox:checked').length > 0;
    return atLeastOneIsChecked;
}

function getFullPartDate(number) {
    return ((number + 1) < 10 ? "0" + (number + 1) : (number + 1));
}

<commit_msg>events can be share properly<commit_after>$(document).ready(function() {

    var idUser = 1;
    var sessionId = "token";

    events = getRappels(idUser, sessionId);

    var selectedDate;

    var options = {
        onDayClick: function(e) {
            selectedDate = e.data.date;
            $("#shareEvent").removeAttr("disabled");
            $("#deleteEvent").removeAttr("disabled");
        },
        onGridShow: function(e) {
            $("#shareEvent").attr("disabled", "disabled");
            $("#deleteEvent").attr("disabled", "disabled");
        },
        color: "green",
        events: events,
        firstDayOfWeek: "Monday",
        showDays: true,
        dayHuman: [
            ["D", "Dimanche"],
            ["L", "Lundi"],
            ["M", "Mardi"],
            ["M", "Mercredi"],
            ["J", "Jeudi"],
            ["V", "Vendredi"],
            ["S", "Samedi"]
        ],
        monthHuman: [
            ["Janv", "Janvier"],
            ["Fevr", "Février"],
            ["Mars", "Mars"],
            ["Avr", "Avril"],
            ["Mai", "Mai"],
            ["Juin", "Juin"],
            ["Juill", "Juillet"],
            ["Août", "Août"],
            ["Sept", "Septembre"],
            ["Oct", "Octobre"],
            ["Nov", "Novembre"],
            ["Dec", "Décembre"]
        ]
    };

    $("#loadCalendar").kalendar(options); //Load the calendar
    $("#startDate, #endDate").datetimepicker();

    $("#addEvent").on("click", function() {
        var button = $("#formAddEvent").find("button[type=submit]");
        buttonBehaviourSubmitDefault(button);
    });

    $("#formAddEvent").on("submit", function(e) {
        e.preventDefault();
        var button = $(this).find("button[type=submit]");
        var begin = new Date($(this.startDate).val()).getTime();
        var end = new Date($(this.endDate).val()).getTime();
        if (begin > end) {
            var error = "La date de fin doit être supérieure à celle de début";
            buttonBehaviourSubmitError(button, error);
        }
        else {
            var title = $(this.title).val();
            var location = $(this.location).val();

            if (addRappel(idUser, sessionId, title, location, begin, end)) {
                var message = "Le rappel a été ajouté avec succès";
                buttonBehaviourSubmitSuccess(button, message);
            }
            else {
                var error = "Problème lors de l'ajout de l'évènement";
                buttonBehaviourSubmitError(button, error);
            }
        }
    });

    //SHARE
    $('button#shareEvent').on('click', function(e)
    {
        e.preventDefault();

        var button = $('#do_shareEvent');
        var button2 = $("#do_shareEventFinal");

        button.parent().show();
        button2.parent().hide();

        var message = 'Sélectionner les contacts';
        buttonBehaviourSubmitDefault(button, message);

        var message = "Partager";
        buttonBehaviourSubmitDefault(button2, message);

        var dayEvents = getDayEvents(selectedDate);
        var shareContentTableModal = $("#shareEventContent tbody");
        var eventsTable = $("div#shareEventsTable");

        $("#shareEventsContacts").hide();

        eventsTable.show();
        shareContentTableModal.empty(); //cleaning before append

        for (var i = 0; i < dayEvents.length; i++) {
            var templateEvent = getRowEvent(dayEvents[i]);
            shareContentTableModal.append(templateEvent);
        }
    });

    $("#do_shareEvent").on("click", function(e){
        e.preventDefault();
        var button = $(this);

        // At least one event is checked
        if (isAtLeastOneCheckedBoxChecked('#tableShareEvents')) {
            $("input:checkbox:not(:checked)").each(function()
            {
                $(this).closest("tr").remove();
            });

            $("div#shareEventsContacts tbody").empty();
            $("div#shareEventsContacts").fadeIn(); // Display contacts

            var contacts = getContacts(idUser, sessionId);

            // if at leasts 1 contact
            if (typeof contacts != 'undefined') {
                for (var i = 0; i < contacts.length; i++) {
                    var templateContact = getRowContact(contacts[i]);
                    $("table#tableShareContacts tbody").append(templateContact);
                }

                $(button).parent().hide();
                $("#do_shareEventFinal").parent().show();

            }
            else {
                $("div#shareEventsContacts table").remove();
                var error = "Aucun contact";
                buttonBehaviourSubmitError(button, error);
            }
        }
        else { // No event checked
            var error = "Sélectionner au moins un rappel";
            buttonBehaviourSubmitError(button, error);
        }

    });

    $("#do_shareEventFinal").on('click', function(e){
        e.preventDefault();
        var button = $(this);
        if (isAtLeastOneCheckedBoxChecked('#shareEventsContacts')) {
            var status = true;
            $("#tableShareEvents input:checkbox:checked").each(function() { // each event
                var event = $(this);
                $("#tableShareContacts input:checkbox:checked").each(function(){ // each contact
                    var contact = $(this);
                    var rappelId = event.parent().parent().attr('id');
                    var contactId = contact.parent().parent().attr('id');
                    var contactType= contact.parent().parent().attr('data-type');
                    if(!shareRappel(idUser, sessionId, rappelId, contactId, contactType)){
                        status = false;
                    }
                });
            });
            if(status){
                var message = "Rappels partagés avec succès";
                buttonBehaviourSubmitSuccess(button, message);
            }
            else{
                var error = "Echec du partage";
                buttonBehaviourSubmitError(button, error);
            }
        }
        else{ // No contact checked
            var error = "Aucun contact sélectionné";
            buttonBehaviourSubmitError(button, error);
        }
    });

    $('button#deleteEvent').on('click', function()
    {
        var dayEvents = getDayEvents(selectedDate);
        var deleteContentModal = $("#deleteEventContent tbody");

        deleteContentModal.empty(); //cleaning before append

        for (var i = 0; i < dayEvents.length; i++) {
            var templateEvent = getRowEvent(dayEvents[i]);

            deleteContentModal.append(templateEvent);
        }
        var button = $("#formDeleteEvent").find("button[type=submit]");
        buttonBehaviourSubmitDefault(button);
    });

    $("#formDeleteEvent").on("submit", function(e) {
        e.preventDefault();
        var button = $(this).find('button[type=submit]');
        if (isAtLeastOneCheckedBoxChecked("tableDeleteEvent")) {
            $("input:checkbox:checked").each(function()
            {
                var event = $(this).closest("tr");
                var rappelId = event.attr("id");
                //remove from the DOM
                if (removeRappel(idUser, sessionId, rappelId)) {
                    event.remove();
                    var message = "Recharger la page pour avoir le calendrier à jour";
                    buttonBehaviourSubmitSuccess(button, message);
                }
                else {
                    var error = "Les rappels n'ont pas pu être supprimés";
                    buttonBehaviourSubmitError(button, error);
                }
            });
        }
        else{
            var error = "Sélectionner au moins un rappel";
            buttonBehaviourSubmitError(button, error);
        }
    });
});

// return events of the day
function getDayEvents(datePicked) {
    var dayEvents = [];
    //Convert into date
    datePicked = getRawDate(new Date(datePicked));
    for (var i = 0; i < events.length; i++) {
        var startDate = getRawDate(events[i].start.d);
        var endDate = getRawDate(events[i].end.d);

        if (datePicked >= startDate && datePicked <= endDate) {
            dayEvents.push(events[i]);
        }
    }
    return dayEvents;
}

function getFormattedDate(dateToBeFormatted, format) {
    return $.datepicker.formatDate(format, new Date(dateToBeFormatted));
}

function getFancyDate(date) {
    return getFormattedDate(date, 'dd MM yy');
}

function getRawDate(date) {
    return getFormattedDate(date, 'yymmdd');
}

function getRawHours(date) {
    date = new Date();
    return date.getHours() + date.getMinutes();
}

function getRowEvent(event) {
    var source = $("#event-table-template").html();
    var context = {
        id: event.id,
        title: event.title,
        start: getFancyDate((event.start.d)),
        end: getFancyDate(event.end.d),
        location: event.location
    };
    var template = Handlebars.compile(source);
    var html = template(context);
    return html;
}

function getRowContact(contact) {
    var source = $("#contact-table-template").html();
    var context = {
        id: contact.id,
        name: contact.name,
        email: contact.email,
        type: contact.type
    }
    var template = Handlebars.compile(source);
    var html = template(context);
    return html;
}

function isAtLeastOneCheckedBoxChecked(container) {
    var atLeastOneIsChecked = $(container + ' :checkbox:checked').length > 0;
    return atLeastOneIsChecked;
}

function getFullPartDate(number) {
    return ((number + 1) < 10 ? "0" + (number + 1) : (number + 1));
}

<|endoftext|>


<commit_before>jQuery.fn.cleardefault = function() {
    return this.focus(function() {
        if( this.value == this.defaultValue ) {
            this.value = "";
        }
    }).blur(function() {
            if( !this.value.length ) {
                this.value = this.defaultValue;
            }
        });
};
/* End input clear functionality */
$(function() {
    $("input[type=text]").cleardefault();
//    /* Load more functionality */
//
//    var loadMore = function () {
//        if(!$('.b-post-list').size()){
//            return false;
//        }
//        $.ajax({
//            url: 'blog-list.html',
//            success: function (data) {
//                var $data = $(data).find('.b-post-list article').css({'opacity': 0}).addClass('new-item');
//                // Replace div#the-posts with the name of your post container
//                $('.b-post-list').append($data);
//                $('.b-post-list').find('.new-item').each(function(){
//                    var $self = $(this);
//                    $self.animate({
//                        opacity: 1
//                    },{
//                        queue: false,
//                        complete: function(){
//                            $(this).removeAttr('style').removeAttr('class');
//                        }
//                    }, 500);
//                });
//            }
//        }); // End Ajax
//        return false;
//    }; // End loadMore
//
//    $('.load-more-link').on('click', loadMore);
//    /* Load more functionality */
});
$(window).load(function() {
    if($('.slides').size()){
        $('.slides').each(function(){
            var slider = $(this);
            var displayPageNumber = function(slider, current){
                var navContainer = slider.closest('.b-slider-wrapper"').find('.slider-nav-panel'),
                    totalCol = slider.find('> div').size();

                navContainer.find('.current-number').text(current);
                navContainer.find('.total-number').text(totalCol);

            };
            slider.caroufredsel({
                items: 1,
                visible: 1,
                width: 'auto',
                align: 'center',
                auto: false,
                next: slider.siblings('.slider-nav-panel').find('.next-slider-arrow'),
                prev: slider.siblings('.slider-nav-panel').find('.prev-slider-arrow'),
                onCreate: function(data){
                    displayPageNumber($(this), slider.triggerHandler( 'currentPosition' )+1);
                },
                scroll: {
                    onBefore: function( data ) {
                        displayPageNumber($(this), slider.triggerHandler( 'currentPosition' )+1);
                    }
                }
            });
        });
    }

    // ikoptelov 08.08.2013 Small and Simple tabs snippet
    $('.js-simple-tabs').each(function(){
        var nav = $(this).find('.js-tabs-nav a'),
            tabs = $(this).find('.js-tabs-list').children();
        tabs.hide();
        tabs.filter(nav.filter('.current').attr('href')).show();
        nav.on('click', function(){
            tabs.hide();
            nav.removeClass('current');
            $(this).addClass('current');
            tabs.filter($(this).attr('href')).show();
            return false;
        });
    });
    // ikoptelov 08.08.2013 Small and Simple tabs snippet
    // var oneImageCarousel = $(".js-oneimage-carousel");

    /*if (oneImageCarousel.size() != 0) {
        oneImageCarousel.find('.js-carousel-container').carouFredSel({
            circular: false,
            infinite: false,
            auto    : false,
            prev    : {
                button  : null
            },
            next    : {
                button  : null
            },
            onCreate : function( data ) {
                data.items.each(function(){
                    $(this).addClass('visible');
                });
            },
            scroll  : {
                onBefore : function( data ) {
                    oneImageCarousel.find('.js-carousel-item').removeClass('visible');
                },
                onAfter : function( data ) {
                    data.items.visible.each(function(){
                        $(this).addClass('visible');
                    });
                }
            },
            pagination  : oneImageCarousel.find('.js-oneimage-carousel-nav')
        });
    }*/
    // end ikoptelov 08.08.2013

    $('#russia_image_block').find('.order').click(function(e){
        e.preventDefault();
        $('#russia_image_block').find('.order').removeClass('current');
        $(this).addClass('current');
        $('#russia_image_widget').load($(this).attr('href'), function(){
            $('#russia_image_widget').caroufredsel({
                items: 1,
                visible: 1,
                width: 'auto',
                align: 'center',
                auto: false,
                pagination: {
                    container: $('#russia_image_block').find('.b-pagination-nav ul'),
                    anchorBuilder: function(nr){
                        return '
'+nr+'
';
                    }
                },
                onCreate : function( data ) {
                    data.items.each(function(){
                        $(this).addClass('visible');
                    });
                },
                scroll  : {
                    onBefore : function( data ) {
                        $('#russia_image_widget').children().removeClass('visible');
                    },
                    onAfter : function( data ) {
                        data.items.visible.each(function(){
                            $(this).addClass('visible');
                        });
                    }
                }
            });
        });
    });

    $('#cinema_block').find('.order').click(function(e){
        e.preventDefault();
        $('#cinema_block').find('.order').removeClass('current');
        $(this).addClass('current');
        $('#cinema_widget').load($(this).attr('href'), function(){
            $('#cinema_widget').caroufredsel({
                items: 1,
                visible: 1,
                width: 'auto',
                align: 'center',
                auto: false,
                pagination: {
                    container: $('#cinema_block').find('.b-pagination-nav ul'),
                    anchorBuilder: function(nr){
                        return '
'+nr+'
';
                    }
                },
                onCreate : function( data ) {
                    data.items.each(function(){
                        $(this).addClass('visible');
                    });
                },
                scroll  : {
                    onBefore : function( data ) {
                        $('#cinema_widget').children().removeClass('visible');
                    },
                    onAfter : function( data ) {
                        data.items.visible.each(function(){
                            $(this).addClass('visible');
                        });
                    }
                }
            });
        });
    });

    $('#theater_block').find('.order').click(function(e){
        e.preventDefault();
        $('#theater_block').find('.order').removeClass('current');
        $(this).addClass('current');
        $('#theater_widget').load($(this).attr('href'));
    });

    $('#lecture_block').find('.order').click(function(e){
        e.preventDefault();
        $('#lecture_block').find('.order').removeClass('current');
        $(this).addClass('current');
        $('#lecture_widget').load($(this).attr('href'), function(){
            $('#lecture_widget').caroufredsel({
                items: 1,
                visible: 1,
                width: 'auto',
                align: 'center',
                auto: false,
                pagination: {
                    container: $('#lecture_block').find('.b-pagination-nav ul'),
                    anchorBuilder: function(nr){
                        return '
'+nr+'
';
                    }
                },
                onCreate : function( data ) {
                    data.items.each(function(){
                        $(this).addClass('visible');
                    });
                },
                scroll  : {
                    onBefore : function( data ) {
                        $('#lecture_widget').children().removeClass('visible');
                    },
                    onAfter : function( data ) {
                        data.items.visible.each(function(){
                            $(this).addClass('visible');
                        });
                    }
                }
            });
        });
    });

    // From old js
    var qtipDefaults = {
        position: {
            my: "top center",
            at: "bottom center"
        },
        show: {
            event: "click",
            effect: function() {
                $(this).slideDown(100);
            },
            solo: true,
            modal: {
                on: true
            }
        },
        hide: {
            event: "unfocus",
            effect: function() {
                $(this).slideUp(100);
            }
        },
        style: {
            classes: "qtip-light qtip-shadow",
            tip: {
                corner: true,
                width:  24,
                height: 12
            }
        }
    };
    if ($("a[href='#login-popup']").length > 0) {
        $("a[href='#login-popup']")
            .qtip($.extend(true, qtipDefaults, {
                content: $("#login-popup")
            }))
            .click(function() {
                return false;
            });
    }
    if ($("a[href='#appstore-popup']").length > 0) {
        $("a[href='#appstore-popup']")
            .qtip($.extend(true, qtipDefaults, {
                content: $("#appstore-popup").html(),
                position: {
                    my: "top right"
                },
                style: {
                    tip: {
                        mimic: "top center",
                        offset: 30
                    }
                }
            }))
            .click(function() {
                return false;
            });
    }

});<commit_msg>#12228<commit_after>jQuery.fn.cleardefault = function() {
    return this.focus(function() {
        if( this.value == this.defaultValue ) {
            this.value = "";
        }
    }).blur(function() {
            if( !this.value.length ) {
                this.value = this.defaultValue;
            }
        });
};
/* End input clear functionality */
$(function() {
    $("input[type=text]").cleardefault();
//    /* Load more functionality */
//
//    var loadMore = function () {
//        if(!$('.b-post-list').size()){
//            return false;
//        }
//        $.ajax({
//            url: 'blog-list.html',
//            success: function (data) {
//                var $data = $(data).find('.b-post-list article').css({'opacity': 0}).addClass('new-item');
//                // Replace div#the-posts with the name of your post container
//                $('.b-post-list').append($data);
//                $('.b-post-list').find('.new-item').each(function(){
//                    var $self = $(this);
//                    $self.animate({
//                        opacity: 1
//                    },{
//                        queue: false,
//                        complete: function(){
//                            $(this).removeAttr('style').removeAttr('class');
//                        }
//                    }, 500);
//                });
//            }
//        }); // End Ajax
//        return false;
//    }; // End loadMore
//
//    $('.load-more-link').on('click', loadMore);
//    /* Load more functionality */
});
$(window).load(function() {
    if($('.slides').size()){
        $('.slides').each(function(){
            var slider = $(this);
            var displayPageNumber = function(slider, current){
                var navContainer = slider.closest('.b-slider-wrapper"').find('.slider-nav-panel'),
                    totalCol = slider.find('> div').size();

                navContainer.find('.current-number').text(current);
                navContainer.find('.total-number').text(totalCol);

            };
            slider.caroufredsel({
                items: 1,
                visible: 1,
                width: 'auto',
                align: 'center',
                auto: false,
                next: slider.siblings('.slider-nav-panel').find('.next-slider-arrow'),
                prev: slider.siblings('.slider-nav-panel').find('.prev-slider-arrow'),
                onCreate: function(data){
                    displayPageNumber($(this), slider.triggerHandler( 'currentPosition' )+1);
                },
                scroll: {
                    onBefore: function( data ) {
                        displayPageNumber($(this), slider.triggerHandler( 'currentPosition' )+1);
                    }
                }
            });
        });
    }

    // ikoptelov 08.08.2013 Small and Simple tabs snippet
    $('.js-simple-tabs').each(function(){
        var nav = $(this).find('.js-tabs-nav a'),
            tabs = $(this).find('.js-tabs-list').children();
        tabs.hide();
        tabs.filter(nav.filter('.current').attr('href')).show();
        nav.on('click', function(){
            tabs.hide();
            nav.removeClass('current');
            $(this).addClass('current');
            tabs.filter($(this).attr('href')).show();
            return false;
        });
    });
    // ikoptelov 08.08.2013 Small and Simple tabs snippet
    // var oneImageCarousel = $(".js-oneimage-carousel");

    /*if (oneImageCarousel.size() != 0) {
        oneImageCarousel.find('.js-carousel-container').carouFredSel({
            circular: false,
            infinite: false,
            auto    : false,
            prev    : {
                button  : null
            },
            next    : {
                button  : null
            },
            onCreate : function( data ) {
                data.items.each(function(){
                    $(this).addClass('visible');
                });
            },
            scroll  : {
                onBefore : function( data ) {
                    oneImageCarousel.find('.js-carousel-item').removeClass('visible');
                },
                onAfter : function( data ) {
                    data.items.visible.each(function(){
                        $(this).addClass('visible');
                    });
                }
            },
            pagination  : oneImageCarousel.find('.js-oneimage-carousel-nav')
        });
    }*/
    // end ikoptelov 08.08.2013

    $('#russia_image_block').find('.order').click(function(e){
        e.preventDefault();
        $('#russia_image_block').find('.order').removeClass('current');
        $(this).addClass('current');
        $('#russia_image_widget').load($(this).attr('href'), function(){
            $('#russia_image_widget').caroufredsel({
                items: 1,
                visible: 1,
                width: 'auto',
                align: 'center',
                auto: false,
                pagination: {
                    container: $('#russia_image_block').find('.b-pagination-nav ul'),
                    anchorBuilder: function(nr){
                        return '
'+nr+'
';
                    }
                },
                onCreate : function( data ) {
                    data.items.each(function(){
                        $(this).addClass('visible');
                    });
                },
                scroll  : {
                    onBefore : function( data ) {
                        $('#russia_image_widget').children().removeClass('visible');
                    },
                    onAfter : function( data ) {
                        data.items.visible.each(function(){
                            $(this).addClass('visible');
                        });
                    }
                }
            });
        });
    });

    $('#cinema_block').find('.order').click(function(e){
        e.preventDefault();
        $('#cinema_block').find('.order').removeClass('current');
        $(this).addClass('current');
        $('#cinema_widget').load($(this).attr('href'), function(){
            $('#cinema_widget').caroufredsel({
                items: 1,
                visible: 1,
                width: 'auto',
                align: 'center',
                auto: false,
                pagination: {
                    container: $('#cinema_block').find('.b-pagination-nav ul'),
                    anchorBuilder: function(nr){
                        return '
'+nr+'
';
                    }
                },
                onCreate : function( data ) {
                    data.items.each(function(){
                        $(this).addClass('visible');
                    });
                },
                scroll  : {
                    onBefore : function( data ) {
                        $('#cinema_widget').children().removeClass('visible');
                    },
                    onAfter : function( data ) {
                        data.items.visible.each(function(){
                            $(this).addClass('visible');
                        });
                    }
                }
            });
        });
    });

    $('#theater_block').find('.order').click(function(e){
        e.preventDefault();
        $('#theater_block').find('.order').removeClass('current');
        $(this).addClass('current');
        $('#theater_widget').load($(this).attr('href'));
    });

    $('#lecture_block').find('.order').click(function(e){
        e.preventDefault();
        $('#lecture_block').find('.order').removeClass('current');
        $(this).addClass('current');
        $('#lecture_widget').load($(this).attr('href'), function(){
//            $('#lecture_widget').caroufredsel({
//                items: 1,
//                visible: 1,
//                width: 'auto',
//                align: 'center',
//                auto: false,
//                pagination: {
//                    container: $('#lecture_block').find('.b-pagination-nav ul'),
//                    anchorBuilder: function(nr){
//                        return '
'+nr+'
';
//                    }
//                },
//                onCreate : function( data ) {
//                    data.items.each(function(){
//                        $(this).addClass('visible');
//                    });
//                },
//                scroll  : {
//                    onBefore : function( data ) {
//                        $('#lecture_widget').children().removeClass('visible');
//                    },
//                    onAfter : function( data ) {
//                        data.items.visible.each(function(){
//                            $(this).addClass('visible');
//                        });
//                    }
//                }
//            });
        });
    });

    // From old js
    var qtipDefaults = {
        position: {
            my: "top center",
            at: "bottom center"
        },
        show: {
            event: "click",
            effect: function() {
                $(this).slideDown(100);
            },
            solo: true,
            modal: {
                on: true
            }
        },
        hide: {
            event: "unfocus",
            effect: function() {
                $(this).slideUp(100);
            }
        },
        style: {
            classes: "qtip-light qtip-shadow",
            tip: {
                corner: true,
                width:  24,
                height: 12
            }
        }
    };
    if ($("a[href='#login-popup']").length > 0) {
        $("a[href='#login-popup']")
            .qtip($.extend(true, qtipDefaults, {
                content: $("#login-popup")
            }))
            .click(function() {
                return false;
            });
    }
    if ($("a[href='#appstore-popup']").length > 0) {
        $("a[href='#appstore-popup']")
            .qtip($.extend(true, qtipDefaults, {
                content: $("#appstore-popup").html(),
                position: {
                    my: "top right"
                },
                style: {
                    tip: {
                        mimic: "top center",
                        offset: 30
                    }
                }
            }))
            .click(function() {
                return false;
            });
    }

});<|endoftext|>


<commit_before>angular.module('PaperUI.controllers.setup', []).controller('SetupPageController', function($scope, $location, thingTypeRepository, bindingRepository) {
    $scope.navigateTo = function(path) {
        $location.path('inbox/' + path);
    }
    $scope.thingTypes = [];
    function getThingTypes() {
        thingTypeRepository.getAll(function(thingTypes) {
            $.each(thingTypes, function(i, thingType) {
                $scope.thingTypes[thingType.UID] = thingType;
            });
        });
    }
    $scope.getThingTypeLabel = function(key) {
        if ($scope.thingTypes && Object.keys($scope.thingTypes).length != 0) {
            if ($scope.thingTypes[key]) {
                return $scope.thingTypes[key].label;
            } else {
                return "Unkown device";
            }
        } else {
            thingTypeRepository.setDirty(false);
        }
    };
    getThingTypes();
}).controller('InboxController', function($scope, $timeout, $mdDialog, $q, inboxService, discoveryResultRepository, thingTypeRepository, thingService, toastService) {
    $scope.setHeaderText('Shows a list of found things in your home.')

    $scope.showScanDialog = function(event) {
        $mdDialog.show({
            controller : 'ScanDialogController',
            templateUrl : 'partials/dialog.scan.html',
            targetEvent : event,
        });
    }

    $scope.refresh = function() {
        discoveryResultRepository.getAll(true);
    };

}).controller('InboxEntryController', function($scope, $mdDialog, $q, inboxService, discoveryResultRepository, thingTypeRepository, thingService, toastService, thingRepository) {
    $scope.approve = function(thingUID, thingTypeUID, event) {
        $mdDialog.show({
            controller : 'ApproveInboxEntryDialogController',
            templateUrl : 'partials/dialog.approveinboxentry.html',
            targetEvent : event,
            locals : {
                discoveryResult : discoveryResultRepository.find(function(discoveryResult) {
                    return discoveryResult.thingUID === thingUID;
                })
            }
        }).then(function(result) {
            inboxService.approve({
                'thingUID' : thingUID,
                'enableChannels' : !$scope.advancedMode
            }, result.label).$promise.then(function() {
                thingRepository.setDirty(true);
                toastService.showDefaultToast('Thing added.', 'Show Thing', 'configuration/things/view/' + thingUID);
                var thingType = thingTypeRepository.find(function(thingType) {
                    return thingTypeUID === thingType.UID;
                });

                if (thingType && thingType.bridge) {
                    $scope.navigateTo('setup/search/' + thingUID.split(':')[0]);
                } else {
                    discoveryResultRepository.getAll(true);
                }
            });
        });
    };
    $scope.ignore = function(thingUID) {
        inboxService.ignore({
            'thingUID' : thingUID
        }, function() {
            $scope.refresh();
        });
    };
    $scope.unignore = function(thingUID) {
        inboxService.unignore({
            'thingUID' : thingUID
        }, function() {
            $scope.refresh();
        });
    };
    $scope.remove = function(thingUID, event) {
        var discoveryResult = discoveryResultRepository.find(function(discoveryResult) {
            return discoveryResult.thingUID === thingUID;
        });
        var confirm = $mdDialog.confirm().title('Remove ' + discoveryResult.label).content('Would you like to remove the discovery result from the inbox?').ariaLabel('Remove Discovery Result').ok('Remove').cancel('Cancel').targetEvent(event);
        $mdDialog.show(confirm).then(function() {
            inboxService.remove({
                'thingUID' : thingUID
            }, function() {
                $scope.refresh();
                toastService.showSuccessToast('Inbox entry removed');
            });
        });
    };
    $scope.bindings;
    $scope.$watch("data.discoveryResults", function(results) {
        if (results) {
            refreshBindings();
        }
    })
    function refreshBindings() {
        $scope.bindings = [];
        if ($scope.data && $scope.data.discoveryResults && $scope.data.bindings && $scope.data.bindings.length > 0) {
            var arr = [];
            for (var i = 0; i < $scope.data.bindings.length; i++) {
                var a = $.grep($scope.data.discoveryResults, function(result) {
                    return result.bindingType == $scope.data.bindings[i].id;
                });
                if (a.length > 0) {
                    $scope.bindings.push($scope.data.bindings[i]);
                }

            }
        }
    }
    $scope.clearAll = function() {
        $scope.searchText = "";
        $scope.$broadcast("ClearFilters");
    }
}).controller('ScanDialogController', function($scope, $rootScope, $timeout, $mdDialog, discoveryService, bindingRepository) {
    $scope.supportedBindings = [];
    $scope.activeScans = [];

    $scope.scan = function(bindingId) {
        $scope.activeScans.push(bindingId);
        discoveryService.scan({
            'bindingId' : bindingId
        }, function(response) {
            var timeout = parseInt(response.timeout);
            timeout = (!isNaN(timeout) ? timeout : 3) * 1000;
            setTimeout(function() {
                $scope.$apply(function() {
                    $scope.activeScans.splice($scope.activeScans.indexOf(bindingId), 1)
                });
            }, timeout);
        });

    };

    bindingRepository.getAll();

    $scope.getBindingById = function(bindingId) {
        for (var i = 0; i < $rootScope.data.bindings.length; i++) {
            var binding = $rootScope.data.bindings[i];
            if (binding.id === bindingId) {
                return binding;
            }
        }
        return {};
    }

    discoveryService.getAll(function(response) {
        $scope.supportedBindings = response;
    });

    $scope.close = function() {
        $mdDialog.hide();
    }
}).controller('ApproveInboxEntryDialogController', function($scope, $mdDialog, discoveryResult, thingTypeRepository) {
    $scope.discoveryResult = discoveryResult;
    $scope.label = discoveryResult.label;
    $scope.thingType = null;
    $scope.thingTypeUID = discoveryResult.thingTypeUID;
    thingTypeRepository.getOne(function(thingType) {
        return thingType.UID === $scope.thingTypeUID;
    }, function(thingType) {
        $scope.thingType = thingType;
    });

    $scope.close = function() {
        $mdDialog.cancel();
    }
    $scope.approve = function(label) {
        $mdDialog.hide({
            label : label
        });
    }
}).controller('ManualSetupConfigureController', function($scope, $routeParams, $mdDialog, $location, toastService, bindingRepository, thingTypeService, thingService, thingRepository, configService, linkService) {

    var thingTypeUID = $routeParams.thingTypeUID;

    function generateUUID() {
        var d = new Date().getTime();
        var uuid = 'xxxxxxxx'.replace(/[x]/g, function(c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    }

    $scope.thingType = null;
    $scope.thing = {
        UID : null,
        thingTypeUID : thingTypeUID,
        configuration : {},
        item : {
            label : null,
            groupNames : []
        }
    };
    $scope.thingID = null;

    $scope.addThing = function(thing) {
        thing.UID = thing.thingTypeUID + ":" + thing.ID;
        thing.configuration = configService.setConfigDefaults(thing.configuration, $scope.parameters, true);
        thingService.add(thing, function() {
            toastService.showDefaultToast('Thing added.', 'Show Thing', 'configuration/things/view/' + thing.UID);
            $location.path('configuration/things');
        });
    };

    thingTypeService.getByUid({
        thingTypeUID : thingTypeUID
    }, function(thingType) {
        $scope.setTitle('Configure ' + thingType.label);
        $scope.setHeaderText(thingType.description);
        $scope.thingType = thingType;
        $scope.parameters = configService.getRenderingModel(thingType.configParameters, thingType.parameterGroups);
        $scope.thing.ID = generateUUID();
        $scope.thing.item.label = thingType.label;
        $scope.thing.label = thingType.label;

        configService.setDefaults($scope.thing, $scope.thingType)
    });
}).controller('SetupWizardController', function($scope, discoveryResultRepository) {
    $scope.showIgnored = false;
    $scope.toggleShowIgnored = function() {
        $scope.showIgnored = !$scope.showIgnored;
    }
    $scope.refresh = function() {
        discoveryResultRepository.getAll(true);
    };
    $scope.refresh();
    $scope.filter = function(discoveryResult) {
        return $scope.showIgnored || discoveryResult.flag === 'NEW';
    }
    $scope.areEntriesIgnored = function(discoveryResults) {
        return $.grep(discoveryResults, function(discoveryResult) {
            return discoveryResult.flag === 'IGNORED';
        }).length > 0;
    }
}).controller('SetupWizardBindingsController', function($scope, bindingRepository, discoveryService) {
    $scope.setSubtitle([ 'Choose Binding' ]);
    $scope.setHeaderText('Choose a Binding for which you want to add new things.');
    bindingRepository.getAll();
    $scope.selectBinding = function(bindingId) {
        discoveryService.getAll(function(supportedBindings) {
            if (supportedBindings.indexOf(bindingId) >= 0) {
                $scope.navigateTo('setup/search/' + bindingId);
            } else {
                $scope.navigateTo('setup/thing-types/' + bindingId);
            }
        });
    }
}).controller('SetupWizardSearchBindingController', function($scope, discoveryResultRepository, discoveryService, thingTypeRepository, bindingRepository) {
    $scope.showIgnored = false;
    $scope.toggleShowIgnored = function() {
        $scope.showIgnored = !$scope.showIgnored;
    }
    $scope.bindingId = $scope.path[4];
    var binding = bindingRepository.find(function(binding) {
        return binding.id === $scope.bindingId;
    });
    $scope.setSubtitle([ binding ? binding.name : '', 'Search' ]);
    $scope.setHeaderText('Searching for new things for the ' + (binding ? binding.name : '') + '.');

    $scope.discoverySupported = true;
    discoveryService.getAll(function(supportedBindings) {
        if (supportedBindings.indexOf($scope.bindingId) >= 0) {
            $scope.discoverySupported = true;
            $scope.scan($scope.bindingId);
        }
    });

    $scope.scanning = false;
    $scope.filter = function(discoveryResult) {
        return ($scope.showIgnored || discoveryResult.flag === 'NEW') && discoveryResult.thingUID.split(':')[0] === $scope.bindingId;
    }
    $scope.scan = function(bindingId) {
        $scope.scanning = true;
        discoveryService.scan({
            'bindingId' : bindingId
        }, function(response) {
            var timeout = parseInt(response.timeout);
            timeout = (!isNaN(timeout) ? timeout : 10) * 1000;
            setTimeout(function() {
                $scope.$apply(function() {
                    $scope.scanning = false;
                });
            }, timeout);
        });

    };

    $scope.refresh = function() {
        discoveryResultRepository.getAll(true);
    };
    $scope.refresh();
}).controller('SetupWizardThingTypesController', function($scope, bindingRepository) {
    $scope.bindingId = $scope.path[4];
    var binding = bindingRepository.find(function(binding) {
        return binding.id === $scope.bindingId;
    });
    $scope.setSubtitle([ binding ? binding.name : '', 'Choose Thing' ]);
    $scope.setHeaderText('Choose a Thing from the ' + (binding ? binding.name : '') + ' which you want to add.');

    $scope.selectThingType = function(thingTypeUID) {
        $scope.navigateTo('setup/add/' + thingTypeUID);
    }
    $scope.filter = function(thingType) {
        return (thingType.UID.split(':')[0] === $scope.bindingId) && (thingType.listed);
    }
});<commit_msg>On adding Thing from Inbox check for missing settings (#3657) (#4702)<commit_after>angular.module('PaperUI.controllers.setup', []).controller('SetupPageController', function($scope, $location, thingTypeRepository, bindingRepository) {
    $scope.navigateTo = function(path) {
        $location.path('inbox/' + path);
    }
    $scope.navigateToConfig = function(path) {
        $location.path('configuration/' + path);
    }
    $scope.thingTypes = [];
    function getThingTypes() {
        thingTypeRepository.getAll(function(thingTypes) {
            $.each(thingTypes, function(i, thingType) {
                $scope.thingTypes[thingType.UID] = thingType;
            });
        });
    }
    $scope.getThingTypeLabel = function(key) {
        if ($scope.thingTypes && Object.keys($scope.thingTypes).length != 0) {
            if ($scope.thingTypes[key]) {
                return $scope.thingTypes[key].label;
            } else {
                return "Unkown device";
            }
        } else {
            thingTypeRepository.setDirty(false);
        }
    };
    getThingTypes();
}).controller('InboxController', function($scope, $timeout, $mdDialog, $q, inboxService, discoveryResultRepository, thingTypeRepository, thingService, toastService) {
    $scope.setHeaderText('Shows a list of found things in your home.')

    $scope.showScanDialog = function(event) {
        $mdDialog.show({
            controller : 'ScanDialogController',
            templateUrl : 'partials/dialog.scan.html',
            targetEvent : event,
        });
    }

    $scope.refresh = function() {
        discoveryResultRepository.getAll(true);
    };

}).controller('InboxEntryController', function($scope, $mdDialog, $q, inboxService, discoveryResultRepository, thingTypeRepository, thingService, toastService, thingRepository, configDescriptionService) {
    $scope.approve = function(thingUID, thingTypeUID, event) {
        $mdDialog.show({
            controller : 'ApproveInboxEntryDialogController',
            templateUrl : 'partials/dialog.approveinboxentry.html',
            targetEvent : event,
            locals : {
                discoveryResult : discoveryResultRepository.find(function(discoveryResult) {
                    return discoveryResult.thingUID === thingUID;
                })
            }
        }).then(function(result) {
            inboxService.approve({
                'thingUID' : thingUID,
                'enableChannels' : !$scope.advancedMode
            }, result.label).$promise.then(function() {
                thingRepository.setDirty(true);
                var thingType = thingTypeRepository.find(function(thingType) {
                    return thingTypeUID === thingType.UID;
                });

                var configRequired = false;
                thingRepository.getOne(function(thing) {
                    return thing.UID === thingUID;
                }, function(thing) {
                    configDescriptionService.getByUri({
                        uri : 'thing-type:' + thingType.UID
                    }, function(configDescription) {
                        if (configDescription.parameters) {
                            for (var i = 0; i < configDescription.parameters.length; i++) {
                                var parameter = configDescription.parameters[i];
                                if (parameter.required) {
                                    if (thing.configuration.hasOwnProperty(parameter.name)) {
                                        if (thing.configuration[parameter.name] === '') {
                                            configRequired = true;
                                            break;
                                        }
                                    } else {
                                        configRequired = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }).$promise.finally(function() {
                        if (configRequired) {
                            $scope.navigateToConfig('things/edit/' + thingUID);
                            toastService.showDefaultToast('Thing added and must be configured');
                        } else {
                            toastService.showDefaultToast('Thing added.', 'Show Thing', 'configuration/things/view/' + thingUID);
                            if (thingType && thingType.bridge) {
                                $scope.navigateTo('setup/search/' + thingUID.split(':')[0]);
                            } else {
                                discoveryResultRepository.getAll(true);
                            }
                        }
                    });
                });
            });
        });
    };
    $scope.ignore = function(thingUID) {
        inboxService.ignore({
            'thingUID' : thingUID
        }, function() {
            $scope.refresh();
        });
    };
    $scope.unignore = function(thingUID) {
        inboxService.unignore({
            'thingUID' : thingUID
        }, function() {
            $scope.refresh();
        });
    };
    $scope.remove = function(thingUID, event) {
        var discoveryResult = discoveryResultRepository.find(function(discoveryResult) {
            return discoveryResult.thingUID === thingUID;
        });
        var confirm = $mdDialog.confirm().title('Remove ' + discoveryResult.label).content('Would you like to remove the discovery result from the inbox?').ariaLabel('Remove Discovery Result').ok('Remove').cancel('Cancel').targetEvent(event);
        $mdDialog.show(confirm).then(function() {
            inboxService.remove({
                'thingUID' : thingUID
            }, function() {
                $scope.refresh();
                toastService.showSuccessToast('Inbox entry removed');
            });
        });
    };
    $scope.bindings;
    $scope.$watch("data.discoveryResults", function(results) {
        if (results) {
            refreshBindings();
        }
    })
    function refreshBindings() {
        $scope.bindings = [];
        if ($scope.data && $scope.data.discoveryResults && $scope.data.bindings && $scope.data.bindings.length > 0) {
            var arr = [];
            for (var i = 0; i < $scope.data.bindings.length; i++) {
                var a = $.grep($scope.data.discoveryResults, function(result) {
                    return result.bindingType == $scope.data.bindings[i].id;
                });
                if (a.length > 0) {
                    $scope.bindings.push($scope.data.bindings[i]);
                }

            }
        }
    }
    $scope.clearAll = function() {
        $scope.searchText = "";
        $scope.$broadcast("ClearFilters");
    }
}).controller('ScanDialogController', function($scope, $rootScope, $timeout, $mdDialog, discoveryService, bindingRepository) {
    $scope.supportedBindings = [];
    $scope.activeScans = [];

    $scope.scan = function(bindingId) {
        $scope.activeScans.push(bindingId);
        discoveryService.scan({
            'bindingId' : bindingId
        }, function(response) {
            var timeout = parseInt(response.timeout);
            timeout = (!isNaN(timeout) ? timeout : 3) * 1000;
            setTimeout(function() {
                $scope.$apply(function() {
                    $scope.activeScans.splice($scope.activeScans.indexOf(bindingId), 1)
                });
            }, timeout);
        });

    };

    bindingRepository.getAll();

    $scope.getBindingById = function(bindingId) {
        for (var i = 0; i < $rootScope.data.bindings.length; i++) {
            var binding = $rootScope.data.bindings[i];
            if (binding.id === bindingId) {
                return binding;
            }
        }
        return {};
    }

    discoveryService.getAll(function(response) {
        $scope.supportedBindings = response;
    });

    $scope.close = function() {
        $mdDialog.hide();
    }
}).controller('ApproveInboxEntryDialogController', function($scope, $mdDialog, discoveryResult, thingTypeRepository) {
    $scope.discoveryResult = discoveryResult;
    $scope.label = discoveryResult.label;
    $scope.thingType = null;
    $scope.thingTypeUID = discoveryResult.thingTypeUID;
    thingTypeRepository.getOne(function(thingType) {
        return thingType.UID === $scope.thingTypeUID;
    }, function(thingType) {
        $scope.thingType = thingType;
    });

    $scope.close = function() {
        $mdDialog.cancel();
    }
    $scope.approve = function(label) {
        $mdDialog.hide({
            label : label
        });
    }
}).controller('ManualSetupConfigureController', function($scope, $routeParams, $mdDialog, $location, toastService, bindingRepository, thingTypeService, thingService, thingRepository, configService, linkService) {

    var thingTypeUID = $routeParams.thingTypeUID;

    function generateUUID() {
        var d = new Date().getTime();
        var uuid = 'xxxxxxxx'.replace(/[x]/g, function(c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    }

    $scope.thingType = null;
    $scope.thing = {
        UID : null,
        thingTypeUID : thingTypeUID,
        configuration : {},
        item : {
            label : null,
            groupNames : []
        }
    };
    $scope.thingID = null;

    $scope.addThing = function(thing) {
        thing.UID = thing.thingTypeUID + ":" + thing.ID;
        thing.configuration = configService.setConfigDefaults(thing.configuration, $scope.parameters, true);
        thingService.add(thing, function() {
            toastService.showDefaultToast('Thing added.', 'Show Thing', 'configuration/things/view/' + thing.UID);
            $location.path('configuration/things');
        });
    };

    thingTypeService.getByUid({
        thingTypeUID : thingTypeUID
    }, function(thingType) {
        $scope.setTitle('Configure ' + thingType.label);
        $scope.setHeaderText(thingType.description);
        $scope.thingType = thingType;
        $scope.parameters = configService.getRenderingModel(thingType.configParameters, thingType.parameterGroups);
        $scope.thing.ID = generateUUID();
        $scope.thing.item.label = thingType.label;
        $scope.thing.label = thingType.label;

        configService.setDefaults($scope.thing, $scope.thingType)
    });
}).controller('SetupWizardController', function($scope, discoveryResultRepository) {
    $scope.showIgnored = false;
    $scope.toggleShowIgnored = function() {
        $scope.showIgnored = !$scope.showIgnored;
    }
    $scope.refresh = function() {
        discoveryResultRepository.getAll(true);
    };
    $scope.refresh();
    $scope.filter = function(discoveryResult) {
        return $scope.showIgnored || discoveryResult.flag === 'NEW';
    }
    $scope.areEntriesIgnored = function(discoveryResults) {
        return $.grep(discoveryResults, function(discoveryResult) {
            return discoveryResult.flag === 'IGNORED';
        }).length > 0;
    }
}).controller('SetupWizardBindingsController', function($scope, bindingRepository, discoveryService) {
    $scope.setSubtitle([ 'Choose Binding' ]);
    $scope.setHeaderText('Choose a Binding for which you want to add new things.');
    bindingRepository.getAll();
    $scope.selectBinding = function(bindingId) {
        discoveryService.getAll(function(supportedBindings) {
            if (supportedBindings.indexOf(bindingId) >= 0) {
                $scope.navigateTo('setup/search/' + bindingId);
            } else {
                $scope.navigateTo('setup/thing-types/' + bindingId);
            }
        });
    }
}).controller('SetupWizardSearchBindingController', function($scope, discoveryResultRepository, discoveryService, thingTypeRepository, bindingRepository) {
    $scope.showIgnored = false;
    $scope.toggleShowIgnored = function() {
        $scope.showIgnored = !$scope.showIgnored;
    }
    $scope.bindingId = $scope.path[4];
    var binding = bindingRepository.find(function(binding) {
        return binding.id === $scope.bindingId;
    });
    $scope.setSubtitle([ binding ? binding.name : '', 'Search' ]);
    $scope.setHeaderText('Searching for new things for the ' + (binding ? binding.name : '') + '.');

    $scope.discoverySupported = true;
    discoveryService.getAll(function(supportedBindings) {
        if (supportedBindings.indexOf($scope.bindingId) >= 0) {
            $scope.discoverySupported = true;
            $scope.scan($scope.bindingId);
        }
    });

    $scope.scanning = false;
    $scope.filter = function(discoveryResult) {
        return ($scope.showIgnored || discoveryResult.flag === 'NEW') && discoveryResult.thingUID.split(':')[0] === $scope.bindingId;
    }
    $scope.scan = function(bindingId) {
        $scope.scanning = true;
        discoveryService.scan({
            'bindingId' : bindingId
        }, function(response) {
            var timeout = parseInt(response.timeout);
            timeout = (!isNaN(timeout) ? timeout : 10) * 1000;
            setTimeout(function() {
                $scope.$apply(function() {
                    $scope.scanning = false;
                });
            }, timeout);
        });

    };

    $scope.refresh = function() {
        discoveryResultRepository.getAll(true);
    };
    $scope.refresh();
}).controller('SetupWizardThingTypesController', function($scope, bindingRepository) {
    $scope.bindingId = $scope.path[4];
    var binding = bindingRepository.find(function(binding) {
        return binding.id === $scope.bindingId;
    });
    $scope.setSubtitle([ binding ? binding.name : '', 'Choose Thing' ]);
    $scope.setHeaderText('Choose a Thing from the ' + (binding ? binding.name : '') + ' which you want to add.');

    $scope.selectThingType = function(thingTypeUID) {
        $scope.navigateTo('setup/add/' + thingTypeUID);
    }
    $scope.filter = function(thingType) {
        return (thingType.UID.split(':')[0] === $scope.bindingId) && (thingType.listed);
    }
});<|endoftext|>