<commit_before>angular.module('help-directive', ['mm.foundation'])

.factory('HelpPopupService', ['$q', function($q) {
  var lexicon = {};
  var promises = [];

  function getHelpItem(key) {
    return $q.all(promises).then(function() {
      return lexicon[key];
    });
  }

  function loadLexicon(newLexicon) {
    promises.push(newLexicon);
    newLexicon.then(function(data) {
      for (propertyName in data) {
        if (data.hasOwnProperty(propertyName)) {
          lexicon[propertyName] = data[propertyName];
        }
      }
    });
  };

  return {
    getHelpItem: getHelpItem,
    loadLexicon: loadLexicon
  };
}])

.directive('inlineHelp', ['HelpPopupService', function(HelpPopupService) {
  return {
    restrict: 'AE',
    replace: false,
    template: '',
    scope: {
      helpKey: '@'
    },
    link: function(scope) {
      var helpItem = HelpPopupService.getHelpItem(scope.helpKey);
      scope.title = helpItem.title;
      scope.helpText = helpItem.text;
      scope.link = helpItem.link;
    }
  }
}]);<commit_msg>bug fix<commit_after>angular.module('help-directive', ['mm.foundation'])

.factory('HelpPopupService', ['$q', function($q) {
  var lexicons = {};
  var promises = [];

  function getHelpItem(key) {
    return $q.all(promises).then(function() {
      return lexicons[key];
    });
  }

  function loadLexicon(newLexicon) {
    promises.push(newLexicon);
    newLexicon.then(function(getResult) {
      var lexicon = getResult.data;
      for (propertyName in lexicon) {
        if (lexicon.hasOwnProperty(propertyName)) {
          lexicons[propertyName] = lexicon[propertyName];
        }
      }
    });
  };

  return {
    getHelpItem: getHelpItem,
    loadLexicon: loadLexicon
  };
}])

.directive('inlineHelp', ['HelpPopupService', function(HelpPopupService) {
  return {
    restrict: 'AE',
    replace: false,
    template: '',
    scope: {
      helpKey: '@'
    },
    link: function(scope) {
      var helpItem = HelpPopupService.getHelpItem(scope.helpKey);
      scope.title = helpItem.title;
      scope.helpText = helpItem.text;
      scope.link = helpItem.link;
    }
  }
}]);<|endoftext|>


<commit_before>goog.provide('napster.datahelpers');

var datahelpers	= new function () {

/**
* @namespace Datahelpers
*/
var self	= this;

/**
* @function
* @property {function} Returns generic handler for Firebase child_added event
* @param {object} dataLocation
* @param {function} opt_callback
*/
var onChildAdded;

/**
* @function
* @property {function} Returns generic handler for Firebase child_removed event
* @param {object} dataLocation
* @param {function} opt_callback
*/
var onChildRemoved;

/**
* @function
* @property {function} Returns generic handler for Firebase value event
* @param {object} dataLocation
* @param {string} key
* @param {function} opt_callback
*/
var onValue;

/**
* @function
* @property {void} Processes track
* @param {string} trackid
* @param {function} callback
*/
var processTrack;

/**
* @function
* @property {void} Syncs local data for specified group
* @param {string} groupid
*/
var syncGroup;

/**
* @function
* @property {void} Syncs local data for specified track
* @param {string} trackid
*/
var syncTrack;

self.onChildAdded	= function (dataLocation, opt_callback) {
	return function (newData) {
		var key	= newData.name();
		dataLocation[key]	= newData.val();
		opt_callback && opt_callback(dataLocation, key, newData);
		ui.update();
	};
};

self.onChildRemoved	= function (dataLocation, opt_callback) {
	return function (newData) {
		var key	= newData.name();
		if (dataLocation[key]) {
			goog.object.remove(dataLocation, key);
		}
		else {
			goog.object.remove(dataLocation, newData.val());
		}
		opt_callback && opt_callback(dataLocation, key, newData);
		ui.update();
	};
};

self.onValue	= function (dataLocation, key, opt_callback) {
	return function (newData) {
		dataLocation[key]	= newData.val();
		opt_callback && opt_callback(dataLocation, key, newData);
		ui.update();
	};
};

self.processTrack	= function (track, callback) {
	track.length	= stream.processTime(track.length);

	/* Will equal epoch if not yet played */
	track.lastPlayed	= new Date(track.lastPlayed || 0).format('{12hr}{tt}, {yyyy}-{MM}-{dd}');

	datastore.user(track.lastPlayedBy).username.once('value', function (username) {
		track.lastPlayedBy	= username.val();
		callback(track);
	});
};

self.syncGroup	= function (groupid, shouldStopSync) {
	datastore.eventHandlers.syncGroup			= datastore.eventHandlers.syncGroup || {};
	datastore.eventHandlers.syncGroup[groupid]	= datastore.eventHandlers.syncGroup[groupid] || {};
	var eventHandlers	= datastore.eventHandlers.syncGroup[groupid];

	datastore.data.group[groupid]	= datastore.data.group[groupid] || {id: groupid, members: {}, messages: {}, name: ''};

	var members		= datastore.group(groupid).members.limit(500);
	var messages	= datastore.group(groupid).messages.limit(500);
	var name		= datastore.group(groupid).name;

	members.off('child_added', eventHandlers.members);
	messages.off('child_added', eventHandlers.messages);
	name.off('value', eventHandlers.name);

	if (!shouldStopSync) {
		eventHandlers.members	= members.on('child_added', self.onChildAdded(datastore.data.group[groupid].members, function (o, k) {
			var userid	= o[k];
			datastore.user(userid).username.once('value', function (data) {
				var username	= data.val();

				/* Exclude temp users from member list */
				if (username.startsWith('temporary-account')) {
					return;
				}

				o[k]	= {username: username};

				datastore.user(userid).nowPlayingChild.track.off('value', eventHandlers.memberTracks);
				eventHandlers.memberTracks	= datastore.user(userid).nowPlayingChild.track.on('value', function (data) {
					datastore.track(data.val()).title.once('value', function (data) {
						o[k].listeningTo	= data.val();
						ui.update();
					});
				});
			});
		}));

		eventHandlers.messages	= messages.on('child_added', self.onChildAdded(datastore.data.group[groupid].messages, function (o, k) {
			var userid	= o[k].author;
			datastore.user(userid).username.once('value', function (data) {
				o[k].author	= data.val();
				ui.update();
			});

			o[k].created	= new Date(o[k].created).toLocaleString();
			o[k].text		= o[k].text.compact().truncate(1000);
		}));

		eventHandlers.name	= name.on('value', self.onValue(datastore.data.group[groupid], 'name'));
	}
	else {
		goog.object.remove(datastore.data.group, groupid);
	}
};

self.syncTrack	= function (trackid, shouldStopSync) {
	datastore.eventHandlers.syncTrackHelper	= datastore.eventHandlers.syncTrackHelper || {};

	datastore.data.track[trackid]	= datastore.data.track[trackid] || {id: trackid};

	var track	= datastore.track(trackid);

	track.off('value', datastore.eventHandlers.syncTrackHelper[trackid]);

	if (!shouldStopSync) {
		datastore.eventHandlers.syncTrackHelper[trackid]	= track.on('value', function (newData) {
			self.processTrack(newData.val(), function (processedTrack) {
				goog.object.forEach(processedTrack, function (value, key) {
					datastore.data.track[trackid][key]	= value;
				});
				ui.update();
			});
		});
	}
	else {
		goog.object.remove(datastore.data.track, trackid);
	}
};

};
<commit_msg>minor bugfix<commit_after>goog.provide('napster.datahelpers');

var datahelpers	= new function () {

/**
* @namespace Datahelpers
*/
var self	= this;

/**
* @function
* @property {function} Returns generic handler for Firebase child_added event
* @param {object} dataLocation
* @param {function} opt_callback
*/
var onChildAdded;

/**
* @function
* @property {function} Returns generic handler for Firebase child_removed event
* @param {object} dataLocation
* @param {function} opt_callback
*/
var onChildRemoved;

/**
* @function
* @property {function} Returns generic handler for Firebase value event
* @param {object} dataLocation
* @param {string} key
* @param {function} opt_callback
*/
var onValue;

/**
* @function
* @property {void} Processes track
* @param {string} trackid
* @param {function} callback
*/
var processTrack;

/**
* @function
* @property {void} Syncs local data for specified group
* @param {string} groupid
*/
var syncGroup;

/**
* @function
* @property {void} Syncs local data for specified track
* @param {string} trackid
*/
var syncTrack;

self.onChildAdded	= function (dataLocation, opt_callback) {
	return function (newData) {
		var key	= newData.name();
		dataLocation[key]	= newData.val();
		opt_callback && opt_callback(dataLocation, key, newData);
		ui.update();
	};
};

self.onChildRemoved	= function (dataLocation, opt_callback) {
	return function (newData) {
		var key	= newData.name();
		if (dataLocation[key]) {
			goog.object.remove(dataLocation, key);
		}
		else {
			goog.object.remove(dataLocation, newData.val());
		}
		opt_callback && opt_callback(dataLocation, key, newData);
		ui.update();
	};
};

self.onValue	= function (dataLocation, key, opt_callback) {
	return function (newData) {
		dataLocation[key]	= newData.val();
		opt_callback && opt_callback(dataLocation, key, newData);
		ui.update();
	};
};

self.processTrack	= function (track, callback) {
	track.length	= stream.processTime(track.length);

	/* Will equal epoch if not yet played */
	track.lastPlayed	= new Date(track.lastPlayed || 0).format('{12hr}{tt}, {yyyy}-{MM}-{dd}');

	datastore.user(track.lastPlayedBy).username.once('value', function (username) {
		track.lastPlayedBy	= username.val();
		callback(track);
	});
};

self.syncGroup	= function (groupid, shouldStopSync) {
	datastore.eventHandlers.syncGroup			= datastore.eventHandlers.syncGroup || {};
	datastore.eventHandlers.syncGroup[groupid]	= datastore.eventHandlers.syncGroup[groupid] || {};
	var eventHandlers	= datastore.eventHandlers.syncGroup[groupid];

	datastore.data.group[groupid]	= datastore.data.group[groupid] || {id: groupid, members: {}, messages: {}, name: ''};

	var members		= datastore.group(groupid).members.limit(500);
	var messages	= datastore.group(groupid).messages.limit(500);
	var name		= datastore.group(groupid).name;

	members.off('child_added', eventHandlers.members);
	messages.off('child_added', eventHandlers.messages);
	name.off('value', eventHandlers.name);

	if (!shouldStopSync) {
		eventHandlers.members	= members.on('child_added', self.onChildAdded(datastore.data.group[groupid].members, function (o, k) {
			var userid	= o[k];
			datastore.user(userid).username.once('value', function (data) {
				var username	= data.val();

				/* Exclude temp users from member list */
				if (username.startsWith('temporary-account')) {
					goog.object.remove(o, k);
					return;
				}

				o[k]	= {username: username};

				datastore.user(userid).nowPlayingChild.track.off('value', eventHandlers.memberTracks);
				eventHandlers.memberTracks	= datastore.user(userid).nowPlayingChild.track.on('value', function (data) {
					datastore.track(data.val()).title.once('value', function (data) {
						o[k].listeningTo	= data.val();
						ui.update();
					});
				});
			});
		}));

		eventHandlers.messages	= messages.on('child_added', self.onChildAdded(datastore.data.group[groupid].messages, function (o, k) {
			var userid	= o[k].author;
			datastore.user(userid).username.once('value', function (data) {
				o[k].author	= data.val();
				ui.update();
			});

			o[k].created	= new Date(o[k].created).toLocaleString();
			o[k].text		= o[k].text.compact().truncate(1000);
		}));

		eventHandlers.name	= name.on('value', self.onValue(datastore.data.group[groupid], 'name'));
	}
	else {
		goog.object.remove(datastore.data.group, groupid);
	}
};

self.syncTrack	= function (trackid, shouldStopSync) {
	datastore.eventHandlers.syncTrackHelper	= datastore.eventHandlers.syncTrackHelper || {};

	datastore.data.track[trackid]	= datastore.data.track[trackid] || {id: trackid};

	var track	= datastore.track(trackid);

	track.off('value', datastore.eventHandlers.syncTrackHelper[trackid]);

	if (!shouldStopSync) {
		datastore.eventHandlers.syncTrackHelper[trackid]	= track.on('value', function (newData) {
			self.processTrack(newData.val(), function (processedTrack) {
				goog.object.forEach(processedTrack, function (value, key) {
					datastore.data.track[trackid][key]	= value;
				});
				ui.update();
			});
		});
	}
	else {
		goog.object.remove(datastore.data.track, trackid);
	}
};

};
<|endoftext|>


<commit_before>define(['text!../views/echoContent.html', 'text!../views/errorContent.html', 'utils', 'jquery'], function(html, errorHtml, utils, $) {
    'use strict';

    // ===================================
    // ECHO CONTENT
    // ===================================

    var _echoContent = function(posts) {
        var container = document.getElementById('echoContent');

        if (!utils._isUnd(posts) && !utils._isUnd(html)) {
            container.innerHTML = html;
            var miniPanel = document.getElementById('echoMiniPanel');

            if (!utils._isUnd(miniPanel)) {
                var title = document.createElement('h5'),
                    link = document.createElement('a'),
                    postsContainer = document.createElement('div'),
                    pContainer = document.getElementById('echoContentPanel');

                title.innerHTML = posts.title;
                utils._setAttr(link, 'href', posts.link + '.html');
                link.innerHTML = posts.link;
                postsContainer.className = 'postMenu';

                if (!utils._isUnd(posts.entries) && posts.entries.length > 0) {
                    var i = 0,
                        entries = posts.entries.length;
                    for (i; i < entries; i++) {
                        var subDiv = document.createElement('div'),
                            subLink = document.createElement('a');
                        utils._setAttr(subLink, 'href', '#');
                        utils._setAttr(subLink, 'data', posts.entries[i].link);
                        subLink.className = 'subMenuLink';
                        subLink.innerHTML = posts.entries[i].title;

                        subDiv.appendChild(subLink);
                        postsContainer.appendChild(subDiv);
                    }
                }
                utils._appendArr(miniPanel, [title, link, postsContainer]);
                container.appendChild(miniPanel);

                if (miniPanel.childNodes.length > 0) {
                    var j = 0,
                        minLength = miniPanel.childNodes.length,
                        firstNode = null;
                    for (j; j < minLength; j++) {
                        if (typeof miniPanel.childNodes[j] === 'object' && miniPanel.childNodes[j].tagName === 'DIV') {
                            firstNode = miniPanel.childNodes[j].childNodes[0].childNodes[0].getAttribute('data');
                        }
                    }
                    utils._appendContent(pContainer, firstNode);
                }
            }

            if (!utils._isUnd(document.getElementsByClassName('subMenuLink'))) {
                $('.subMenuLink').click(function(ev) {
                    utils._emptyContentContainer();

                    var panel = miniPanel.childNodes[3].childNodes,
                        link = ev.currentTarget.attributes.data.value,
                        i = 0,
                        panelLength = panel.length;

                    for (i; i < panelLength; i++) {
                        var links = panel[i].childNodes[0];
                        if ($(links).hasClass('now')) {
                            $(links).removeClass('now');
                        }
                    }

                    $(this).addClass('selected');
                    $(this).addClass('now');
                    utils._appendContent(pContainer, link);
                });
            }
        }
    };

    return {
        echoContent: _echoContent
    };
});
<commit_msg>echoContent.js change<commit_after>define(['text!../views/echoContent.html', 'text!../views/errorContent.html', 'utils', 'jquery'], function(html, errorHtml, utils, $) {
    'use strict';

    // ===================================
    // ECHO CONTENT
    // ===================================

    var _echoContent = function(posts) {
        var container = document.getElementById('container');

        if (!utils._isUnd(posts) && !utils._isUnd(html)) {
            container.innerHTML = html;
            var miniPanel = document.getElementById('echoMiniPanel');

            if (!utils._isUnd(miniPanel)) {
                var title = document.createElement('h5'),
                    link = document.createElement('a'),
                    postsContainer = document.createElement('div'),
                    pContainer = document.getElementById('echoContentPanel');

                title.innerHTML = posts.title;
                utils._setAttr(link, 'href', posts.link + '.html');
                link.innerHTML = posts.link;
                postsContainer.className = 'postMenu';

                if (!utils._isUnd(posts.entries) && posts.entries.length > 0) {
                    var i = 0,
                        entries = posts.entries.length;
                    for (i; i < entries; i++) {
                        var subDiv = document.createElement('div'),
                            subLink = document.createElement('a');
                        utils._setAttr(subLink, 'href', '#');
                        utils._setAttr(subLink, 'data', posts.entries[i].link);
                        subLink.className = 'subMenuLink';
                        subLink.innerHTML = posts.entries[i].title;

                        subDiv.appendChild(subLink);
                        postsContainer.appendChild(subDiv);
                    }
                }
                utils._appendArr(miniPanel, [title, link, postsContainer]);
                container.appendChild(miniPanel);

                if (miniPanel.childNodes.length > 0) {
                    var j = 0,
                        minLength = miniPanel.childNodes.length,
                        firstNode = null;
                    for (j; j < minLength; j++) {
                        if (typeof miniPanel.childNodes[j] === 'object' && miniPanel.childNodes[j].tagName === 'DIV') {
                            firstNode = miniPanel.childNodes[j].childNodes[0].childNodes[0].getAttribute('data');
                        }
                    }
                    utils._appendContent(pContainer, firstNode);
                }
            }

            if (!utils._isUnd(document.getElementsByClassName('subMenuLink'))) {
                $('.subMenuLink').click(function(ev) {
                    utils._emptyContentContainer();

                    var panel = miniPanel.childNodes[3].childNodes,
                        link = ev.currentTarget.attributes.data.value,
                        i = 0,
                        panelLength = panel.length;

                    for (i; i < panelLength; i++) {
                        var links = panel[i].childNodes[0];
                        if ($(links).hasClass('now')) {
                            $(links).removeClass('now');
                        }
                    }

                    $(this).addClass('selected');
                    $(this).addClass('now');
                    utils._appendContent(pContainer, link);
                });
            }
        }
    };

    return {
        echoContent: _echoContent
    };
});
<|endoftext|>


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

    window.Todo = Backbone.Model.extend({
        //Default Attributes
        defaults: {
            content: "new empty todo",
            parent: 0,
            indent: 0,
            order: 0,
            done: false
        },

        initialize: function() {
            if (!this.get("content")) {
              this.set({"content": this.defaults.content});
            }
        },

		done: function() {
			this.save({done: !this.get("done")});
		},

		setParent: function(parentTodo) {
			if(!parentTodo) {
				return false;
			}
			this.save({parent: parentTodo.id});
			return true;
		},

		indentBy: function(number) {
			this.save({indent: (this.get('indent') + (number ? number: 0))});
		}
    });

    window.TodoList = Backbone.Collection.extend({
        model: Todo,
//        localStorage: new Store("forgetmenot"),
		url: "fmn.php",

        nextOrder: function() {
            if (this.length === 0) {
                return 1;
            } else {
                return this.last().get('order') + 1;
            }
        },

		thoseWithParentOf: function(parentId) {
			return _.select(this.models, function(model) {
				return model.get('parent') == parentId;
			});
		},

		thatAreDone: function() {
			return _.select(this.models, function(model) {
				return model.get('done') == true;
			});
		},

        comparator: function(todo) {
          return todo.get('order');
        },

		// Get's passed current todo
		// Returns parent todo
		// Checking to make sure the
		// correct parent todo is returned
		getParentTodo: function(todo, previousTodo) {
			var previousTodo = this.at(Todos.indexOf(previousTodo ? previousTodo : todo) - 1);
			if (!previousTodo) {
				return false;
			} else if (todo.get('indent') == previousTodo.get('indent')) {
				return (previousTodo ? previousTodo : NaN);
			} else {
				return this.getParentTodo(todo, previousTodo);
			}

		},

		maintainChildrenOfParent: function(todo) {
			var childTodo = this.at(Todos.indexOf(childTodo ? childTodo: todo) + 1);
			if (!childTodo) {
				return false;
			} else {
				if(todo.get('indent') == 0 && todo.get('id') == this.getNextTodo(todo).get('parent')) {
					this.getNextTodo(todo).save({parent: todo.get('id'), indent: 1});
				}
				Todos.each(function(model){
					if (todo.get('id') === model.get('parent')) {
						model.save({indent: (todo.get('indent') + 1)});
					}
				});
				return this.maintainChildrenOfParent(childTodo);
			}

		},

		// Gets passed current todo
		// Sets current todo's parent todo Id correctly
		setParentTodo: function(todo) {
			todo.get('order');
			var previousTodo = this.getPreviousTodo(todo);
			if (previousTodo.get('parent') == '0') {
				todo.setParent(previousTodo);
			}
		},

		// Passed in current todo
		// Returns next todo item
		// Based off of todo's 'order' attribute
		getNextTodo: function(todo) {
			return this.at(Todos.indexOf(todo) + 1);
		},

		// Passed in current todo
		// Returns previous todo item
		// Based off of todo's 'order' attribute
		getPreviousTodo: function(todo) {
			return this.at(Todos.indexOf(todo) - 1);
		}

    });

    window.Todos = new TodoList;

    // Each Individual Todo Item View
    window.TodoView = Backbone.View.extend({
        tagName: "li",
        template: _.template($('#item-template').html()),

        events: {
            "dblclick .display"        :      	"edit",
            "click .display"        :      	"edit",
            "keydown .edit input"              :      	"keyboardActions",
			"click input.done"  			    : 		"toggleDone",
            "click .display .delete"					   : 	    "deleteTodo"
        },

        initialize: function() {
            _.bindAll(this, 'render', 'deleteTodo', 'close','save', 'keyboardActions');
            this.model.bind('change', this.render);
            this.el.id = this.model.get("id");
            // Give reverse access to a model's view by setting its 'this'
            // to a new attribute on the model
            this.model.view = this;
        },

        render: function() {
            $(this.el).html(this.template(this.model.toJSON()));
			this.el.className = 'todo indent-' + this.model.get('indent');
            this.input = this.$(".input");
            this.input.bind('blur', this.close);
            return this;
        },

        edit: function() {
            var content = this.model.get('content');
            $(this.el).addClass("editing");
            this.input.val(content);
            this.input.focus();
            //return false;
        },

        save: function(indent) {
			var $inputVal = this.input.val();
            this.model.save({
				content: ($inputVal == '' ? this.model.defaults.content : $inputVal)
			});
			this.model.indentBy(indent);
        },

		close: function() {
			this.save();
			$(this.el).removeClass("editing");
		},

        deleteTodo: function() {
            this.model.destroy();
            this.remove();
        },

        keyboardActions: function(e) {
			/**
				left arrow		37
				up arrow		38
				right arrow		39
				down arrow		40
			**/
			// Enter button
			if (e.keyCode == 13) {
				if(!Todos.getNextTodo(this.model)) {
					// If last todo then close current
					// and create a new todo
					this.close();
					forgetmenot.createNewAfter(this.model);
				} else if (this.model.get('indent') === Todos.getNextTodo(this.model).get('indent')) {
					// If next todo is at same indent
					// Then edit next todo
					this.editNextTodo(e);
				} else if (this.model.get('indent') > Todos.getNextTodo(this.model).get('indent')) {
					// If next todo is closer to indent '0'
					// Then we create a new todo after current
					forgetmenot.createNewAfter(this.model);
				} else {
				// If not last todo then edit next todo
					this.editNextTodo(e);
				}
			}
			// Tab key - move todo to right one
			// And make sub todo of parent (if it exists)
			if (e.keyCode == 9 && !e.shiftKey) {
				this.save();
				if(this.model.setParent(Todos.getParentTodo(this.model))) {
					this.save(1);
					Todos.maintainChildrenOfParent(this.model);
					this.edit();
				}
				e.preventDefault();
			}
			// Shift + Tab key - move todo to left one
			// And un-sub it from parent (if it exists)
			if (e.shiftKey && e.keyCode == 9) {
				this.save();
				if(this.model.get('indent') == 1) {
					this.model.save({
						indent: 0,
						parent: 0
					});
					Todos.maintainChildrenOfParent(this.model);
				} else if (!Todos.getPreviousTodo(this.model) || this.model.get('indent') == 0) {
					return false;
				} else {
					this.model.save({
						parent: Todos.get(this.model.get('parent')).get('parent'),
						indent: Todos.get(this.model.get('parent')).get('indent')
					});
					Todos.maintainChildrenOfParent(this.model);
				}
				this.edit();
				e.preventDefault();
			}
			/**
				Note for Up and Down keys:
				The '- 2' and none increments are
				due to the collection being kept at index 0
				but the order attribute being kept at index 1
			**/
			// Up key - close current todo and open todo above to edit
			if (e.keyCode == 38) {
				this.editPreviousTodo(e);
			}
			// Down key - close current todo and open todo above to edit
			if (e.keyCode == 40) {
				this.editNextTodo(e);
			}
			// Backspace key
			if (e.keyCode == 8) {
				if (this.input.val() == '') {
					this.editPreviousTodo(e);
					this.deleteTodo();
					e.preventDefault();
				}
			}
        },

		editNextTodo: function(e) {
			var todoToOpen = Todos.getNextTodo(this.model);
			// If we're already at the top then preventDefault()
			if (!todoToOpen) {
				e.preventDefault();
			} else {
				this.close();
				todoToOpen.view.edit();
			}
		},

		editPreviousTodo: function(e) {
			var todoToOpen = Todos.getPreviousTodo(this.model);
			// If we're already at the top then preventDefault()
			if (!todoToOpen) {
				e.preventDefault();
			} else {
				this.close();
				todoToOpen.view.edit();
			}
		},

		toggleDone: function() {
			this.model.done();
		}
    });

    window.TodoApp = Backbone.View.extend({
        el: $("#todoApp"),

        events: {
            //"dblclick"          :       "test",
            "click #createNew"  :       "createNew"
        },

        initialize: function() {
//            Backbone.emulateHTTP = true;
//            Backbone.emulateJSON = true;
            _.bindAll(this, 'createNew', 'createNewAfter', 'createNewBefore', 'addOne', 'addAll');
            Todos.bind('reset', this.addAll);
            //Todos.bind('refresh', this.resetOrder);
			Todos.bind('remove', this.resetOrder);
			Todos.bind('add', this.resetOrder);
            Todos.fetch();
			this.resetOrder();
			if (Todos.length == 0) {
				this.createNew({content: 'Start your first Todo!'});
				Todos.at(0).view.edit();
			}
        },

        createNew: function(o) {
            var todo = Todos.create({
				content: o.content ? o.content : ''
			});
            this.addOne(todo, (_.isString(o.topOrBottom) ? o.topOrBottom : 'bottom')).edit();
        },

		createNewAfter: function(todo) {
            var t = Todos.create({
				content: '',
				parent: todo.get('parent'),
				indent: todo.get('indent'),
				order: (todo.get('order') + 1)
			});
			var view = new TodoView({model:t});
			this.$('#' + todo.id).after(view.render().el);
			view.edit();
        },

		createNewBefore: function(todo) {
            var t = Todos.create({
				content: '',
				parent: todo.get('parent'),
				indent: todo.get('indent'),
				order: todo.get('order')
			});
			var view = new TodoView({model:t});
			this.$('#' + todo.id).before(view.render().el);
			view.edit();
        },

        addOne: function(todo, topOrBottom) {
            var view = new TodoView({model:todo});
			if (topOrBottom == 'top') {
				this.$("#todoItemsList").prepend(view.render().el);
			} else if (topOrBottom == 'bottom') {
				var lastTodoPosition = _.last(Todos.models).get("order") + 1;
				todo.set({order: lastTodoPosition});
				Todos.sort({silent: true});
				this.$("#todoItemsList").append(view.render().el);
			} else {
				this.$("#todoItemsList").append(view.render().el);
			}
            return view;
        },

        addAll: function() {
            Todos.each(this.addOne);
        },

        resetOrder: function(todo) {
            var order = -1;
            _.each(Todos.models, function(todo) {
                order++;
                todo.set({ order: order});
                todo.save();
            });
            //Todos.refresh();
        }
    });

    window.forgetmenot = new TodoApp;

});<commit_msg>change attr 'order' => 'position' for sqlite3 compaitibility <commit_after>$(document).ready(function() {

    window.Todo = Backbone.Model.extend({
        //Default Attributes
        defaults: {
            content: "new empty todo",
            parent: 0,
            indent: 0,
            position: 0,
            done: false
        },

        initialize: function() {
            if (!this.get("content")) {
              this.set({"content": this.defaults.content});
            }
        },

		done: function() {
			this.save({done: !this.get("done")});
		},

		setParent: function(parentTodo) {
			if(!parentTodo) {
				return false;
			}
			this.save({parent: parentTodo.id});
			return true;
		},

		indentBy: function(number) {
			this.save({indent: (this.get('indent') + (number ? number: 0))});
		}
    });

    window.TodoList = Backbone.Collection.extend({
        model: Todo,
//        localStorage: new Store("forgetmenot"),
		url: "fmn.php",

        nextPosition: function() {
            if (this.length === 0) {
                return 1;
            } else {
                return this.last().get('position') + 1;
            }
        },

		thoseWithParentOf: function(parentId) {
			return _.select(this.models, function(model) {
				return model.get('parent') == parentId;
			});
		},

		thatAreDone: function() {
			return _.select(this.models, function(model) {
				return model.get('done') == true;
			});
		},

        comparator: function(todo) {
          return todo.get('position');
        },

		// Get's passed current todo
		// Returns parent todo
		// Checking to make sure the
		// correct parent todo is returned
		getParentTodo: function(todo, previousTodo) {
			var previousTodo = this.at(Todos.indexOf(previousTodo ? previousTodo : todo) - 1);
			if (!previousTodo) {
				return false;
			} else if (todo.get('indent') == previousTodo.get('indent')) {
				return (previousTodo ? previousTodo : NaN);
			} else {
				return this.getParentTodo(todo, previousTodo);
			}

		},

		maintainChildrenOfParent: function(todo) {
			var childTodo = this.at(Todos.indexOf(childTodo ? childTodo: todo) + 1);
			if (!childTodo) {
				return false;
			} else {
				if(todo.get('indent') == 0 && todo.get('id') == this.getNextTodo(todo).get('parent')) {
					this.getNextTodo(todo).save({parent: todo.get('id'), indent: 1});
				}
				Todos.each(function(model){
					if (todo.get('id') === model.get('parent')) {
						model.save({indent: (todo.get('indent') + 1)});
					}
				});
				return this.maintainChildrenOfParent(childTodo);
			}

		},

		// Gets passed current todo
		// Sets current todo's parent todo Id correctly
		setParentTodo: function(todo) {
			todo.get('position');
			var previousTodo = this.getPreviousTodo(todo);
			if (previousTodo.get('parent') == '0') {
				todo.setParent(previousTodo);
			}
		},

		// Passed in current todo
		// Returns next todo item
		// Based off of todo's 'position' attribute
		getNextTodo: function(todo) {
			return this.at(Todos.indexOf(todo) + 1);
		},

		// Passed in current todo
		// Returns previous todo item
		// Based off of todo's 'position' attribute
		getPreviousTodo: function(todo) {
			return this.at(Todos.indexOf(todo) - 1);
		}

    });

    window.Todos = new TodoList;

    // Each Individual Todo Item View
    window.TodoView = Backbone.View.extend({
        tagName: "li",
        template: _.template($('#item-template').html()),

        events: {
            "dblclick .display"        :      	"edit",
            "click .display"        :      	"edit",
            "keydown .edit input"              :      	"keyboardActions",
			"click input.done"  			    : 		"toggleDone",
            "click .display .delete"					   : 	    "deleteTodo"
        },

        initialize: function() {
            _.bindAll(this, 'render', 'deleteTodo', 'close','save', 'keyboardActions');
            this.model.bind('change', this.render);
            this.el.id = this.model.get("id");
            // Give reverse access to a model's view by setting its 'this'
            // to a new attribute on the model
            this.model.view = this;
        },

        render: function() {
            $(this.el).html(this.template(this.model.toJSON()));
			this.el.className = 'todo indent-' + this.model.get('indent');
            this.input = this.$(".input");
            this.input.bind('blur', this.close);
            return this;
        },

        edit: function() {
            var content = this.model.get('content');
            $(this.el).addClass("editing");
            this.input.val(content);
            this.input.focus();
            //return false;
        },

        save: function(indent) {
			var $inputVal = this.input.val();
            this.model.save({
				content: ($inputVal == '' ? this.model.defaults.content : $inputVal)
			});
			this.model.indentBy(indent);
        },

		close: function() {
			this.save();
			$(this.el).removeClass("editing");
		},

        deleteTodo: function() {
            this.model.destroy();
            this.remove();
        },

        keyboardActions: function(e) {
			/**
				left arrow		37
				up arrow		38
				right arrow		39
				down arrow		40
			**/
			// Enter button
			if (e.keyCode == 13) {
				if(!Todos.getNextTodo(this.model)) {
					// If last todo then close current
					// and create a new todo
					this.close();
					forgetmenot.createNewAfter(this.model);
				} else if (this.model.get('indent') === Todos.getNextTodo(this.model).get('indent')) {
					// If next todo is at same indent
					// Then edit next todo
					this.editNextTodo(e);
				} else if (this.model.get('indent') > Todos.getNextTodo(this.model).get('indent')) {
					// If next todo is closer to indent '0'
					// Then we create a new todo after current
					forgetmenot.createNewAfter(this.model);
				} else {
				// If not last todo then edit next todo
					this.editNextTodo(e);
				}
			}
			// Tab key - move todo to right one
			// And make sub todo of parent (if it exists)
			if (e.keyCode == 9 && !e.shiftKey) {
				this.save();
				if(this.model.setParent(Todos.getParentTodo(this.model))) {
					this.save(1);
					Todos.maintainChildrenOfParent(this.model);
					this.edit();
				}
				e.preventDefault();
			}
			// Shift + Tab key - move todo to left one
			// And un-sub it from parent (if it exists)
			if (e.shiftKey && e.keyCode == 9) {
				this.save();
				if(this.model.get('indent') == 1) {
					this.model.save({
						indent: 0,
						parent: 0
					});
					Todos.maintainChildrenOfParent(this.model);
				} else if (!Todos.getPreviousTodo(this.model) || this.model.get('indent') == 0) {
					return false;
				} else {
					this.model.save({
						parent: Todos.get(this.model.get('parent')).get('parent'),
						indent: Todos.get(this.model.get('parent')).get('indent')
					});
					Todos.maintainChildrenOfParent(this.model);
				}
				this.edit();
				e.preventDefault();
			}
			/**
				Note for Up and Down keys:
				The '- 2' and none increments are
				due to the collection being kept at index 0
				but the position attribute being kept at index 1
			**/
			// Up key - close current todo and open todo above to edit
			if (e.keyCode == 38) {
				this.editPreviousTodo(e);
			}
			// Down key - close current todo and open todo above to edit
			if (e.keyCode == 40) {
				this.editNextTodo(e);
			}
			// Backspace key
			if (e.keyCode == 8) {
				if (this.input.val() == '') {
					this.editPreviousTodo(e);
					this.deleteTodo();
					e.preventDefault();
				}
			}
        },

		editNextTodo: function(e) {
			var todoToOpen = Todos.getNextTodo(this.model);
			// If we're already at the top then preventDefault()
			if (!todoToOpen) {
				e.preventDefault();
			} else {
				this.close();
				todoToOpen.view.edit();
			}
		},

		editPreviousTodo: function(e) {
			var todoToOpen = Todos.getPreviousTodo(this.model);
			// If we're already at the top then preventDefault()
			if (!todoToOpen) {
				e.preventDefault();
			} else {
				this.close();
				todoToOpen.view.edit();
			}
		},

		toggleDone: function() {
			this.model.done();
		}
    });

    window.TodoApp = Backbone.View.extend({
        el: $("#todoApp"),

        events: {
            //"dblclick"          :       "test",
            "click #createNew"  :       "createNew"
        },

        initialize: function() {
//            Backbone.emulateHTTP = true;
//            Backbone.emulateJSON = true;
            _.bindAll(this, 'createNew', 'createNewAfter', 'createNewBefore', 'addOne', 'addAll');
            Todos.bind('reset', this.addAll);
            //Todos.bind('refresh', this.resetPosition);
			Todos.bind('remove', this.resetPosition);
			Todos.bind('add', this.resetPosition);
            Todos.fetch();
			this.resetPosition();
			if (Todos.length == 0) {
				this.createNew({content: 'Start your first Todo!'});
				Todos.at(0).view.edit();
			}
        },

        createNew: function(o) {
            var todo = Todos.create({
				content: o.content ? o.content : ''
			});
            this.addOne(todo, (_.isString(o.topOrBottom) ? o.topOrBottom : 'bottom')).edit();
        },

		createNewAfter: function(todo) {
            var t = Todos.create({
				content: '',
				parent: todo.get('parent'),
				indent: todo.get('indent'),
				position: (todo.get('position') + 1)
			});
			var view = new TodoView({model:t});
			this.$('#' + todo.id).after(view.render().el);
			view.edit();
        },

		createNewBefore: function(todo) {
            var t = Todos.create({
				content: '',
				parent: todo.get('parent'),
				indent: todo.get('indent'),
				position: todo.get('position')
			});
			var view = new TodoView({model:t});
			this.$('#' + todo.id).before(view.render().el);
			view.edit();
        },

        addOne: function(todo, topOrBottom) {
            var view = new TodoView({model:todo});
			if (topOrBottom == 'top') {
				this.$("#todoItemsList").prepend(view.render().el);
			} else if (topOrBottom == 'bottom') {
				var lastTodoPosition = _.last(Todos.models).get("position") + 1;
				todo.set({position: lastTodoPosition});
				Todos.sort({silent: true});
				this.$("#todoItemsList").append(view.render().el);
			} else {
				this.$("#todoItemsList").append(view.render().el);
			}
            return view;
        },

        addAll: function() {
            Todos.each(this.addOne);
        },

        resetPosition: function(todo) {
            var position = -1;
            _.each(Todos.models, function(todo) {
                position++;
                todo.set({ position: position});
                todo.save();
            });
            //Todos.refresh();
        }
    });

    window.forgetmenot = new TodoApp;

});<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

lib.rtdep('lib.f');

/**
 * First draft of the interface between the terminal and a third party dialog.
 *
 * This is rough.  It's just the terminal->dialog layer.  To complete things
 * we'll also need a command->terminal layer.  That will have to facilitate
 * command->terminal->dialog or direct command->dialog communication.
 *
 * I imagine this class will change significantly when that happens.
 */

/**
 * Construct a new frame for the given terminal.
 *
 * @param terminal {hterm.Terminal} The parent terminal object.
 * @param url {String} The url to load in the frame.
 * @param opt_options {Object} Optional options for the frame.  Not implemented.
 */
hterm.Frame = function(terminal, url, opt_options) {
  this.terminal_ = terminal;
  this.div_ = terminal.div_;
  this.url = url;
  this.options = opt_options || {};
  this.iframe_ = null;
  this.container_ = null;
  this.messageChannel_ = null;
};

/**
 * Handle messages from the iframe.
 */
hterm.Frame.prototype.onMessage_ = function(e) {
  switch (e.data.name) {
    case 'ipc-init-ok':
      // We get this response after we send them ipc-init and they finish.
      this.sendTerminalInfo_();
      return;
    case 'terminal-info-ok':
      // We get this response after we send them terminal-info and they finish.
      // Show the finished frame, and then rebind our message handler to the
      // callback below.
      this.container_.style.display = 'flex';
      this.messageChannel_.port1.onmessage = this.onMessage.bind(this);
      this.onLoad();
      return;
    default:
      console.log('Unknown message from frame:', e.data);
      return;
  }
};

/**
 * Clients could override this, I guess.
 *
 * It doesn't support multiple listeners, but I'm not sure that would make sense
 * here.  It's probably better to speak directly to our parents.
 */
hterm.Frame.prototype.onMessage = function() {};

/**
 * Handle iframe onLoad event.
 */
hterm.Frame.prototype.onLoad_ = function() {
  this.messageChannel_ = new MessageChannel();
  this.messageChannel_.port1.onmessage = this.onMessage_.bind(this);
  this.messageChannel_.port1.start();
  this.iframe_.contentWindow.postMessage(
      {name: 'ipc-init', argv: [{messagePort: this.messageChannel_.port2}]},
      this.url, [this.messageChannel_.port2]);
};

/**
 * Clients may override this.
 */
hterm.Frame.prototype.onLoad = function() {};

/**
 * Sends the terminal-info message to the iframe.
 */
hterm.Frame.prototype.sendTerminalInfo_ = function() {
  lib.f.getAcceptLanguages(function(languages) {
      this.postMessage('terminal-info', [{
         acceptLanguages: languages,
         foregroundColor: this.terminal_.getForegroundColor(),
         backgroundColor: this.terminal_.getBackgroundColor(),
         cursorColor: this.terminal_.getCursorColor(),
         fontSize: this.terminal_.getFontSize(),
         fontFamily: this.terminal_.getFontFamily(),
         baseURL: lib.f.getURL('/')
          }]
        );
    }.bind(this));
};

/**
 * User clicked the close button on the frame decoration.
 */
hterm.Frame.prototype.onCloseClicked_ = function() {
  this.close();
};

/**
 * Close this frame.
 */
hterm.Frame.prototype.close = function() {
  if (!this.container_ || !this.container_.parentNode)
      return;

  this.container_.parentNode.removeChild(this.container_);
  this.onClose();
};

/**
 * Clients may override this.
 */
hterm.Frame.prototype.onClose = function() {};

/**
 * Send a message to the iframe.
 */
hterm.Frame.prototype.postMessage = function(name, argv) {
  if (!this.messageChannel_)
    throw new Error('Message channel is not set up.');

  this.messageChannel_.port1.postMessage({name: name, argv: argv});
};

/**
 * Show the UI for this frame.
 *
 * The iframe src is not loaded until this method is called.
 */
hterm.Frame.prototype.show = function() {
  var self = this;

  function opt(name, defaultValue) {
    if (name in self.options)
      return self.options[name];

    return defaultValue;
  }

  var self = this;

  if (this.container_ && this.container_.parentNode) {
    console.error('Frame already visible');
    return;
  }

  var headerHeight = '16px';

  var divSize = hterm.getClientSize(this.div_);

  var width = opt('width', 640);
  var height = opt('height', 480);
  var left = (divSize.width - width) / 2;
  var top = (divSize.height - height) / 2;

  var document = this.terminal_.document_;

  var container = this.container_ = document.createElement('div');
  container.style.cssText = (
      'position: absolute;' +
      'display: none;' +
      'flex-direction: column;' +
      'top: 10%;' +
      'left: 4%;' +
      'width: 90%;' +
      'height: 80%;' +
      'box-shadow: 0 0 2px ' + this.terminal_.getForegroundColor() + ';' +
      'border: 2px ' + this.terminal_.getForegroundColor() + ' solid;');

  if (false) {
    // No use for the close button, so no use for the window header either.
    var header = document.createElement('div');
    header.style.cssText = (
        'display: flex;' +
        'justify-content: flex-end;' +
        'height: ' + headerHeight + ';' +
        'background-color: ' + this.terminal_.getForegroundColor() + ';' +
        'color: ' + this.terminal_.getBackgroundColor() + ';' +
        'font-size: 16px;' +
        'font-family: ' + this.terminal_.getFontFamily());
    container.appendChild(header);

    var button = document.createElement('div');
    button.setAttribute('role', 'button');
    button.style.cssText = (
        'margin-top: -3px;' +
        'margin-right: 3px;' +
        'cursor: pointer;');
    button.textContent = '\u2a2f';
    button.addEventListener('click', this.onCloseClicked_.bind(this));
    header.appendChild(button);
  }

  var iframe = this.iframe_ = document.createElement('iframe');
  iframe.onload = this.onLoad_.bind(this);
  iframe.style.cssText = (
      'display: flex;' +
      'flex: 1;' +
      'width: 100%');
  iframe.setAttribute('src', this.url);
  iframe.setAttribute('seamless', true);
  container.appendChild(iframe);

  this.div_.appendChild(container);
};
<commit_msg>nassh: shrink & shift connection dialog<commit_after>// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

lib.rtdep('lib.f');

/**
 * First draft of the interface between the terminal and a third party dialog.
 *
 * This is rough.  It's just the terminal->dialog layer.  To complete things
 * we'll also need a command->terminal layer.  That will have to facilitate
 * command->terminal->dialog or direct command->dialog communication.
 *
 * I imagine this class will change significantly when that happens.
 */

/**
 * Construct a new frame for the given terminal.
 *
 * @param terminal {hterm.Terminal} The parent terminal object.
 * @param url {String} The url to load in the frame.
 * @param opt_options {Object} Optional options for the frame.  Not implemented.
 */
hterm.Frame = function(terminal, url, opt_options) {
  this.terminal_ = terminal;
  this.div_ = terminal.div_;
  this.url = url;
  this.options = opt_options || {};
  this.iframe_ = null;
  this.container_ = null;
  this.messageChannel_ = null;
};

/**
 * Handle messages from the iframe.
 */
hterm.Frame.prototype.onMessage_ = function(e) {
  switch (e.data.name) {
    case 'ipc-init-ok':
      // We get this response after we send them ipc-init and they finish.
      this.sendTerminalInfo_();
      return;
    case 'terminal-info-ok':
      // We get this response after we send them terminal-info and they finish.
      // Show the finished frame, and then rebind our message handler to the
      // callback below.
      this.container_.style.display = 'flex';
      this.messageChannel_.port1.onmessage = this.onMessage.bind(this);
      this.onLoad();
      return;
    default:
      console.log('Unknown message from frame:', e.data);
      return;
  }
};

/**
 * Clients could override this, I guess.
 *
 * It doesn't support multiple listeners, but I'm not sure that would make sense
 * here.  It's probably better to speak directly to our parents.
 */
hterm.Frame.prototype.onMessage = function() {};

/**
 * Handle iframe onLoad event.
 */
hterm.Frame.prototype.onLoad_ = function() {
  this.messageChannel_ = new MessageChannel();
  this.messageChannel_.port1.onmessage = this.onMessage_.bind(this);
  this.messageChannel_.port1.start();
  this.iframe_.contentWindow.postMessage(
      {name: 'ipc-init', argv: [{messagePort: this.messageChannel_.port2}]},
      this.url, [this.messageChannel_.port2]);
};

/**
 * Clients may override this.
 */
hterm.Frame.prototype.onLoad = function() {};

/**
 * Sends the terminal-info message to the iframe.
 */
hterm.Frame.prototype.sendTerminalInfo_ = function() {
  lib.f.getAcceptLanguages(function(languages) {
      this.postMessage('terminal-info', [{
         acceptLanguages: languages,
         foregroundColor: this.terminal_.getForegroundColor(),
         backgroundColor: this.terminal_.getBackgroundColor(),
         cursorColor: this.terminal_.getCursorColor(),
         fontSize: this.terminal_.getFontSize(),
         fontFamily: this.terminal_.getFontFamily(),
         baseURL: lib.f.getURL('/')
          }]
        );
    }.bind(this));
};

/**
 * User clicked the close button on the frame decoration.
 */
hterm.Frame.prototype.onCloseClicked_ = function() {
  this.close();
};

/**
 * Close this frame.
 */
hterm.Frame.prototype.close = function() {
  if (!this.container_ || !this.container_.parentNode)
      return;

  this.container_.parentNode.removeChild(this.container_);
  this.onClose();
};

/**
 * Clients may override this.
 */
hterm.Frame.prototype.onClose = function() {};

/**
 * Send a message to the iframe.
 */
hterm.Frame.prototype.postMessage = function(name, argv) {
  if (!this.messageChannel_)
    throw new Error('Message channel is not set up.');

  this.messageChannel_.port1.postMessage({name: name, argv: argv});
};

/**
 * Show the UI for this frame.
 *
 * The iframe src is not loaded until this method is called.
 */
hterm.Frame.prototype.show = function() {
  var self = this;

  function opt(name, defaultValue) {
    if (name in self.options)
      return self.options[name];

    return defaultValue;
  }

  var self = this;

  if (this.container_ && this.container_.parentNode) {
    console.error('Frame already visible');
    return;
  }

  var headerHeight = '16px';

  var divSize = hterm.getClientSize(this.div_);

  var width = opt('width', 640);
  var height = opt('height', 480);
  var left = (divSize.width - width) / 2;
  var top = (divSize.height - height) / 2;

  var document = this.terminal_.document_;

  var container = this.container_ = document.createElement('div');
  container.style.cssText = (
      'position: absolute;' +
      'display: none;' +
      'flex-direction: column;' +
      'top: 10%;' +
      'left: 4%;' +
      'width: 90%;' +
      'height: 80%;' +
      'min-height: 20%;' +
      'max-height: 80%;' +
      'box-shadow: 0 0 2px ' + this.terminal_.getForegroundColor() + ';' +
      'border: 2px ' + this.terminal_.getForegroundColor() + ' solid;');

  if (false) {
    // No use for the close button, so no use for the window header either.
    var header = document.createElement('div');
    header.style.cssText = (
        'display: flex;' +
        'justify-content: flex-end;' +
        'height: ' + headerHeight + ';' +
        'background-color: ' + this.terminal_.getForegroundColor() + ';' +
        'color: ' + this.terminal_.getBackgroundColor() + ';' +
        'font-size: 16px;' +
        'font-family: ' + this.terminal_.getFontFamily());
    container.appendChild(header);

    var button = document.createElement('div');
    button.setAttribute('role', 'button');
    button.style.cssText = (
        'margin-top: -3px;' +
        'margin-right: 3px;' +
        'cursor: pointer;');
    button.textContent = '\u2a2f';
    button.addEventListener('click', this.onCloseClicked_.bind(this));
    header.appendChild(button);
  }

  var iframe = this.iframe_ = document.createElement('iframe');
  iframe.onload = this.onLoad_.bind(this);
  iframe.style.cssText = (
      'display: flex;' +
      'flex: 1;' +
      'width: 100%');
  iframe.setAttribute('src', this.url);
  iframe.setAttribute('seamless', true);
  container.appendChild(iframe);

  this.div_.appendChild(container);
};
<|endoftext|>


<commit_before>"use strict";
var ImageLoader;
require('settings', 'data.settings', 'colorifier');

/**
 * Utility for loading images of tiles, buildings and units and providing info
 * about loading progress. If the tiles', buildings' or units' images are not
 * pre-rotated, this utility will auto-rotate them.
 */
ImageLoader = function () {
    var loadBuildingImages, notifyObservers, buildingsIndex, observers,
            unitsIndex, loadUnitImages, tilesIndex, loadTilesImages,
            transformTileImage, pathPrefix, transformBuildingImage, colorifier;

    observers = [];
    pathPrefix = '';
    colorifier = new Colorifier();

    /**
     * Begins the loading procedure.
     *
     * @param {BuildingsDefinition} buildings The BuildingsDefinition class.
     * @param {UnitsDefinition} units The UnitsDefinition class.
     * @param {TilesDefinition} tiles The TilesDefinition class.
     */
    this.load = function (buildings, units, tiles) {
        loadBuildingImages(buildings);
        loadUnitImages(units);
        loadTilesImages(tiles);
    };

    /**
     * Rgisters an observer function that will be notified on each progress
     * of loading.
     *
     * @param {Function} observer The observer function that should be executed
     *        when the loading process progresses. This function receives
     *        single parameter - a Number from the [0,1] interval. The value
     *        will be 1 once the loading process is complete.
     */
    this.addObserver = function (observer) {
        observers.push(observer);
    };

    /**
     * Sets path prefix that will be used with paths to tiles', buildings' and
     * units' images.
     *
     * @param {String} prefix The prefix that should be prepended to all paths.
     */
    this.setPathPrefix = function (prefix) {
        pathPrefix = prefix;
    };

    /**
     * Starts loading of tiles' images.
     *
     * @param {TilesDefinition} tiles The TilesDefinition class.
     */
    loadTilesImages = function (tiles) {
        var tile, currentType;
        tilesIndex = [];
        currentType = 0;
        tile = tiles.getType(currentType);
        while (tile) {
            tilesIndex.push(false);
            (function () {
                var image, type, tileDefinition;
                tileDefinition = tile;
                type = currentType;
                image = new Image();
                image.onload = function () {
                    tilesIndex[type] = true;
                    tileDefinition.imageData = Settings.tileImagesTransformed ?
                            image : transformTileImage(image);
                    notifyObservers();
                };
                image.src = pathPrefix + tile.image;
            }());
            tile = tiles.getType(++currentType);
        }
    };

    /**
     * Starts loading units' images.
     *
     * @param {UnitsDefinition} units The UnitsDefinition class.
     */
    loadUnitImages = function (units) {
        var unit, currentType;
        unitsIndex = [];
        currentType = 0;
        unit = units.getType(currentType);
        while (unit) {
            unitsIndex.push(false);
            (function () {
                var images, image, type, i, loadedImages, unitDefinition;
                unitDefinition = unit;
                type = currentType;
                images = [];
                loadedImages = [];
                for (i = 8; i--;) {
                    loadedImages[i] = false;
                    image = new Image();
                    (function () {
                        var index;
                        index = i;
                        image.onload = function () {
                            var i;
                            loadedImages[index] = true;
                            for (i = 8; i--;) {
                                if (!loadedImages[i]) {
                                    return;
                                }
                            }
                            if (!Settings.unitImagesTransformed) {
                                for (i = 8; i--;) {
                                    images[i] = transformTileImage(images[i]);
                                }
                            }
                            unitsIndex[type] = true;
                            unitDefinition.imageData = images;
                            unitDefinition.playerImages = [];
                            for (i = 8; i--;) {
                                unitDefinition.playerImages[i] =
                                        colorifier.colorifyForPlayers(
                                        images[i],
                                        unitDefinition.colorify,
                                        unitDefinition.colorifyDistance);
                            }
                            notifyObservers();
                        };
                    }());
                    images[i] = image;
                }
                for (i = 8; i--;) {
                    images[i].src = pathPrefix + unit.image.replace('?', i);
                }
            }());
            unit = units.getType(++currentType);
        }
    };

    /**
     * Starts loading building's images.
     *
     * @param {BuildingsDefinition} buildings The BuildingsDefinition class.
     */
    loadBuildingImages = function (buildings) {
        var building, currentType;
        buildingsIndex = [];
        currentType = 0;
        building = buildings.getType(currentType);
        while (building) {
            buildingsIndex.push(false);
            (function () {
                var image, type, buildingDefinition;
                buildingDefinition = building;
                type = currentType;
                image = new Image();
                image.onload = function () {
                    buildingsIndex[type] = true;
                    buildingDefinition.imageData =
                            Settings.buildingImagesTransformed ?
                            image : transformBuildingImage(image,
                            buildingDefinition.width,
                            buildingDefinition.height);
                    buildingDefinition.playerImages =
                            colorifier.colorifyForPlayers(
                            buildingDefinition.imageData,
                            buildingDefinition.colorify,
                            buildingDefinition.colorifyDistance);
                    notifyObservers();
                };
                image.src = pathPrefix + building.image;
            }());
            building = buildings.getType(++currentType);
        }
    };

    /**
     * Executes all registered observers, passing them the current progress
     * through single parameter in form of a Number from range [0,1], where 1
     * means that all images has been loaded.
     */
    notifyObservers = function () {
        var i, done;
        done = 0;
        for (i = buildingsIndex.length; i--;) {
            if (buildingsIndex[i]) {
                done++;
            }
        }
        for (i = unitsIndex.length; i--;) {
            if (unitsIndex[i]) {
                done++;
            }
        }
        for (i = tilesIndex.length; i--;) {
            if (tilesIndex[i]) {
                done++;
            }
        }
        done /= buildingsIndex.length + unitsIndex.length + tilesIndex.length;
        for (i = observers.length; i--;) {
            observers[i](done);
        }
    };

    /**
     * Transforms raw building's image by rotating it by 25 degrees clockwise.
     *
     * @param {Image} source The raw image to transform.
     * @param {Number} width The width of the building in tiles.
     * @param {Number} height The height of the building in tiles.
     * @return {Image} A transformed image.
     */
    transformBuildingImage = function (source, width, height) {
        var canvas, context, data;
        canvas = document.createElement('canvas');
        canvas.width = 14 + Math.ceil(Settings.tileWidth * width);
        canvas.height = 50 + Math.ceil(Settings.tileHeight * height);
        context = canvas.getContext('2d');
        context.scale(1, Settings.heightScale);
        context.rotate(45 * Math.PI / 180);
        context.drawImage(source, 10 + Settings.tileSize * width, 0);
        data = context.getImageData(7, 48 * Settings.heightScale,
                Settings.tileWidth * width, Settings.tileHeight * height);
        canvas = document.createElement('canvas');
        canvas.width = data.width;
        canvas.height = data.height;
        context = canvas.getContext('2d');
        context.putImageData(data, 0, 0);
        data = new Image();
        data.src = canvas.toDataURL();
        return data;
    };

    /**
     * Transforms raw tiles's / unit's image by rotating it by 25 degrees
     * clockwise.
     *
     * @param {Image} source The raw image to transform.
     * @return {Image} A transformed image.
     */
    transformTileImage = function (source) {
        var canvas, context, data;
        canvas = document.createElement('canvas');
        canvas.width = 7 + Math.ceil(Settings.tileWidth * 2);
        canvas.height = 22 + Math.ceil(Settings.tileHeight * 2);
        context = canvas.getContext('2d');
        context.scale(1, Settings.heightScale);
        context.rotate(45 * Math.PI / 180);
        context.drawImage(source, 30, 0);
        data = context.getImageData(7, 20 * Settings.heightScale,
                Settings.tileWidth, Settings.tileHeight);
        canvas = document.createElement('canvas');
        canvas.width = data.width;
        canvas.height = data.height;
        context = canvas.getContext('2d');
        context.putImageData(data, 0, 0);
        data = new Image();
        data.src = canvas.toDataURL();
        return data;
    };
};<commit_msg>updated imageloader: improved building image transformation, but this feature really shouldn't be used<commit_after>"use strict";
var ImageLoader;
require('settings', 'data.settings', 'colorifier');

/**
 * Utility for loading images of tiles, buildings and units and providing info
 * about loading progress. If the tiles', buildings' or units' images are not
 * pre-rotated, this utility will auto-rotate them.
 */
ImageLoader = function () {
    var loadBuildingImages, notifyObservers, buildingsIndex, observers,
            unitsIndex, loadUnitImages, tilesIndex, loadTilesImages,
            transformTileImage, pathPrefix, transformBuildingImage, colorifier;

    observers = [];
    pathPrefix = '';
    colorifier = new Colorifier();

    /**
     * Begins the loading procedure.
     *
     * @param {BuildingsDefinition} buildings The BuildingsDefinition class.
     * @param {UnitsDefinition} units The UnitsDefinition class.
     * @param {TilesDefinition} tiles The TilesDefinition class.
     */
    this.load = function (buildings, units, tiles) {
        loadBuildingImages(buildings);
        loadUnitImages(units);
        loadTilesImages(tiles);
    };

    /**
     * Rgisters an observer function that will be notified on each progress
     * of loading.
     *
     * @param {Function} observer The observer function that should be executed
     *        when the loading process progresses. This function receives
     *        single parameter - a Number from the [0,1] interval. The value
     *        will be 1 once the loading process is complete.
     */
    this.addObserver = function (observer) {
        observers.push(observer);
    };

    /**
     * Sets path prefix that will be used with paths to tiles', buildings' and
     * units' images.
     *
     * @param {String} prefix The prefix that should be prepended to all paths.
     */
    this.setPathPrefix = function (prefix) {
        pathPrefix = prefix;
    };

    /**
     * Starts loading of tiles' images.
     *
     * @param {TilesDefinition} tiles The TilesDefinition class.
     */
    loadTilesImages = function (tiles) {
        var tile, currentType;
        tilesIndex = [];
        currentType = 0;
        tile = tiles.getType(currentType);
        while (tile) {
            tilesIndex.push(false);
            (function () {
                var image, type, tileDefinition;
                tileDefinition = tile;
                type = currentType;
                image = new Image();
                image.onload = function () {
                    tilesIndex[type] = true;
                    tileDefinition.imageData = Settings.tileImagesTransformed ?
                            image : transformTileImage(image);
                    notifyObservers();
                };
                image.src = pathPrefix + tile.image;
            }());
            tile = tiles.getType(++currentType);
        }
    };

    /**
     * Starts loading units' images.
     *
     * @param {UnitsDefinition} units The UnitsDefinition class.
     */
    loadUnitImages = function (units) {
        var unit, currentType;
        unitsIndex = [];
        currentType = 0;
        unit = units.getType(currentType);
        while (unit) {
            unitsIndex.push(false);
            (function () {
                var images, image, type, i, loadedImages, unitDefinition;
                unitDefinition = unit;
                type = currentType;
                images = [];
                loadedImages = [];
                for (i = 8; i--;) {
                    loadedImages[i] = false;
                    image = new Image();
                    (function () {
                        var index;
                        index = i;
                        image.onload = function () {
                            var i;
                            loadedImages[index] = true;
                            for (i = 8; i--;) {
                                if (!loadedImages[i]) {
                                    return;
                                }
                            }
                            if (!Settings.unitImagesTransformed) {
                                for (i = 8; i--;) {
                                    images[i] = transformTileImage(images[i]);
                                }
                            }
                            unitsIndex[type] = true;
                            unitDefinition.imageData = images;
                            unitDefinition.playerImages = [];
                            for (i = 8; i--;) {
                                unitDefinition.playerImages[i] =
                                        colorifier.colorifyForPlayers(
                                        images[i],
                                        unitDefinition.colorify,
                                        unitDefinition.colorifyDistance);
                            }
                            notifyObservers();
                        };
                    }());
                    images[i] = image;
                }
                for (i = 8; i--;) {
                    images[i].src = pathPrefix + unit.image.replace('?', i);
                }
            }());
            unit = units.getType(++currentType);
        }
    };

    /**
     * Starts loading building's images.
     *
     * @param {BuildingsDefinition} buildings The BuildingsDefinition class.
     */
    loadBuildingImages = function (buildings) {
        var building, currentType;
        buildingsIndex = [];
        currentType = 0;
        building = buildings.getType(currentType);
        while (building) {
            buildingsIndex.push(false);
            (function () {
                var image, type, buildingDefinition;
                buildingDefinition = building;
                type = currentType;
                image = new Image();
                image.onload = function () {
                    buildingsIndex[type] = true;
                    buildingDefinition.imageData =
                            Settings.buildingImagesTransformed ?
                            image : transformBuildingImage(image,
                            buildingDefinition.width,
                            buildingDefinition.height);
                    buildingDefinition.playerImages =
                            colorifier.colorifyForPlayers(
                            buildingDefinition.imageData,
                            buildingDefinition.colorify,
                            buildingDefinition.colorifyDistance);
                    notifyObservers();
                };
                image.src = pathPrefix + building.image;
            }());
            building = buildings.getType(++currentType);
        }
    };

    /**
     * Executes all registered observers, passing them the current progress
     * through single parameter in form of a Number from range [0,1], where 1
     * means that all images has been loaded.
     */
    notifyObservers = function () {
        var i, done;
        done = 0;
        for (i = buildingsIndex.length; i--;) {
            if (buildingsIndex[i]) {
                done++;
            }
        }
        for (i = unitsIndex.length; i--;) {
            if (unitsIndex[i]) {
                done++;
            }
        }
        for (i = tilesIndex.length; i--;) {
            if (tilesIndex[i]) {
                done++;
            }
        }
        done /= buildingsIndex.length + unitsIndex.length + tilesIndex.length;
        for (i = observers.length; i--;) {
            observers[i](done);
        }
    };

    /**
     * Transforms raw building's image by rotating it by 45 degrees clockwise.
     *
     * @param {Image} source The raw image to transform.
     * @param {Number} width The width of the building in tiles.
     * @param {Number} height The height of the building in tiles.
     * @return {Image} A transformed image.
     */
    transformBuildingImage = function (source, width, height) {
        var canvas, context, data, offset;
        canvas = document.createElement('canvas');
        canvas.width = 140 + Math.ceil(Settings.tileWidth * width);
        canvas.height = 500 + Math.ceil(Settings.tileHeight * height);
        context = canvas.getContext('2d');
        context.scale(1, Settings.heightScale);
        context.rotate(45 * Math.PI / 180);
        context.drawImage(source, 7 * Settings.tileSize, 0);
        // don't ask... untransformed images shouldn't be used anyways
        offset = (Math.SQRT2 / 2) *
                (Math.ceil((width - 1) / 2) * (Settings.tileWidth + 10));
        data = context.getImageData(84 - offset, 99 * Settings.heightScale,
                Settings.tileWidth * width, Settings.tileHeight * height);
        canvas = document.createElement('canvas');
        canvas.width = data.width;
        canvas.height = data.height;
        context = canvas.getContext('2d');
        context.putImageData(data, 0, 0);
        data = new Image();
        data.src = canvas.toDataURL();
        return data;
    };

    /**
     * Transforms raw tiles's / unit's image by rotating it by 25 degrees
     * clockwise.
     *
     * @param {Image} source The raw image to transform.
     * @return {Image} A transformed image.
     */
    transformTileImage = function (source) {
        var canvas, context, data;
        canvas = document.createElement('canvas');
        canvas.width = 7 + Math.ceil(Settings.tileWidth * 2);
        canvas.height = 22 + Math.ceil(Settings.tileHeight * 2);
        context = canvas.getContext('2d');
        context.scale(1, Settings.heightScale);
        context.rotate(45 * Math.PI / 180);
        context.drawImage(source, 30, 0);
        data = context.getImageData(7, 20 * Settings.heightScale,
                Settings.tileWidth, Settings.tileHeight);
        canvas = document.createElement('canvas');
        canvas.width = data.width;
        canvas.height = data.height;
        context = canvas.getContext('2d');
        context.putImageData(data, 0, 0);
        data = new Image();
        data.src = canvas.toDataURL();
        return data;
    };
};<|endoftext|>


<commit_before>/*
**************************************
******jFormsliderv 1.0.5**************
******jFormslider.js******************
******Created by Harish U Warrier*****
******Created on 08-06-2014***********
******Modified on 04-10-2014**********
******jfs@jformslider.com*************
******www.jformslider.com*************
**************************************
*/
if("undefined"==typeof jQuery)
{
    if('undefined'!==typeof console)
        console.log('%c Sorry!!There is no jquery please get jquery ','color: red');
    else
        throw new Error("Sorry!!There is no jquery please get jquery");
}
$.fn.jFormslider=function(options)
{
	var version="1.0.5";
	var $this=$(this);
	var lilength=$this.find('li').length;
	var randomid='jformslider'+new Date().valueOf();
	var ajaxprocessing=false;
	var defaults=
	{
            width:600,
            height:300,
            animation:'horizontal',
            next_button:true,
            prev_button:true,
            button_placement:'bottom',
            submit_btn:true,
            submit_class:'',
            next_class:'',
            prev_class:'',
            nav_class:'',
            error_class:'error',
            error_element:true,
            error_position:'',
            mobile:false,
            texts:{
                    next:'next',
                    prev:'prev',
                    submit:'submit'
                  },
            ajax_repeat:false,
            speed:400,
            bootstrap:false,
            full_navigation:true,
            validation:true,
            disabletab:true,
            submit_handler:"",
	}
	if(arguments.length>0)
	{
            var text=$.extend(defaults.texts,options.texts);
            options=$.extend(defaults,options);
            options.texts=text;
	}else
            options=defaults;
        if(options.height!='auto')
            options.height=get_height(options.height);
        options.width=get_width(options.width);

	var msgspan='

';
	var next_button=''+options.texts.next+'';
	var prev_button=''+options.texts.prev+'';
	var width=options.width;
	var height=options.height=="auto"?'auto':options.height+'px';
	var widthpc=width*lilength;
	var errorspan="";
	var errorclasses=splitclass($.trim(options.error_class));
	var error_selector='.'+errorclasses.join('.');
	var submit_element="";
	if(options.submit_btn)
		submit_element='<button submit type="submit" class="'+options.submit_class+'"  style="float:right">'+options.texts.submit+'</button>';
	if(options.error_element)
	{
            if(options.error_position=="inside")
                errorspan="";
            else
                $(this).after(msgspan);
	}else
	errorspan="";
	var navigation_div='
'+prev_button+errorspan+next_button+'
';
	var jformslider_style="";
          // jformslider_style="";
				if($('style[tag="jformslider"]').length<=0)
					$('head').append(jformslider_style);
	$(this).addClass('jformslider');
	if($(this).find('li:first').hasAttr('call-before'))
	{
            var func=$(this).find('li:first').attr('call-before');
            eval(func);
	}
        $(this).find('li').each(function(index,element){
            set_nav($(this),index);
        });

	$(this).find('li[hide]').hide();
	$(this).find('li').each(function(index,element){
		$(this).find('input,select').last().keydown(function(e) {
			if(e.which==9 )
			{	if(options.disabletab)
				return false;
			}
		});
	});
	$(this).find('[number]').keydown(function(e){
		var numberarray=[96,97,98,99,100,101,102,103,104,105,109,189,8,46,48,49,50,51,52,53,54,55,56,57,9,16];
		if($.inArray(e.keyCode,numberarray)==-1)
		{
			if(options.validation)
				e.preventDefault();
		}
		if(e.keyCode>=65 && e.keyCode<=90)
		{
			if(options.validation)
				e.preventDefault();
		}
	});
	$('[ajax-url]').each(function(index,element){
		var target="";
		target=$(this).hasAttr('ajax-target')?$(this).attr('ajax-target')!=""?$(this).attr('ajax-target'):target:target;
		if(target=="")
		{
			if($(this).find('[next],[prev]').length!=0)
			{
				if($(this).find('.jformslider_ajax_target').length==0)
				$(this).find('[next],[prev]').parent().before("

");
			}else
			{
				if($(this).find('.jformslider_ajax_target').length==0)
				$(this).append("

");
			}
		}
	});
	$this.find('li').each(function(index, element) {
		var rand=randomid+index;
		if(!$(this).hasAttr('data-id'))
			$(this).attr('data-id',rand);
		else if($(this).attr('data-id')=="")
			$(this).attr('data-id',rand);
	});
	$("body").keydown(function(e){
		if(e.which==9 && e.shiftKey)
		{
			if(e.target.nodeName=="INPUT")
			{
				var id=e.target.id;
				$(e.target).parents('li').find('input').each(function(index, element) {
				    if($(this).attr('id')==id)
					{	$(e.target).parents('li').find('input:eq('+(index-1)+')').focus();
						return false;
					}
				});
			}
			return false;
		}
	});
	$('[prev]').click(function(e){
		e.preventDefault();
		$this.prevSlide();
	});
	$('[next]').click(function(e){
		e.preventDefault();
		$this.nextSlide();
	});
	$('[submit]').click(function(e){
		e.preventDefault();
		var current_slide=$this.get_current_slide();
		var slidestart=false;
		if(options.validation)
		{
			$this.find('input[required],select[required],input[email]').each(function(index,element){
				var err_slide=$(this).parents('li');
				var $thisid=err_slide.hasAttr('data-id')?err_slide.attr('data-id'):"";
				if($(this).hasAttr('required'))
				{	if($.trim($(this).val())=='')
					{
						var msg=$(this).hasAttr('data-msg')?$(this).attr('data-msg'):'Please fill this field';
						if(options.error_position=="inside")
							err_slide.find(error_selector).html(msg).show();
						else
							$('#'+randomid).html(msg).show();
						if($('[data-id="'+$thisid+'"]').is(':visible'))
						{
							$this.gotoSlide($thisid);
							$(this).focus();
							slidestart=false;
							return false;
						}

					}
				}
				if($(this).hasAttr('email'))
				{
					if(!emailvalid($.trim($(this).val())))
					{
						if(options.error_position=="inside")
							err_slide.find(error_selector).html('Please Enter a valid email').show();
						else
							$('#'+randomid).html('Please Enter a valid email').show();
						if($('[data-id="'+$thisid+'"]').is(':visible'))
						{
							$this.gotoSlide($thisid);
							$(this).focus();
							slidestart=false;
							return false;
						}
					}
				}
				if($(this).is('select'))
				{
					if($.trim($(this).val())=='-1')
					{
						var msg=$(this).hasAttr('data-msg')?$(this).attr('data-msg'):'Please fill this field';
						if(options.error_position=="inside")
							err_slide.find(error_selector).html(msg).show();
						else
							$('#'+randomid).html(msg).show();
						if($('[data-id="'+$thisid+'"]').is(':visible'))
						{
							$this.gotoSlide($thisid);
							$(this).focus();
							slidestart=false;
							return false;
						}
					}
				}

			});
			current_slide.find('input[required],select[required],input[email]').each(function(index,element){
				if($(this).hasAttr('required'))
				{	if($.trim($(this).val())=='')
					{
						var msg=$(this).hasAttr('data-msg')?$(this).attr('data-msg'):'Please fill this field';
						if(options.error_position=="inside")
							current_slide.find(error_selector).html(msg).show();
						else
							$('#'+randomid).html(msg).show();
						$(this).focus();
						slidestart=false;
						return false;
					}
				}
				if($(this).hasAttr('email'))
				{
					if(!emailvalid($.trim($(this).val())))
					{
						if(options.error_position=="inside")
							current_slide.find(error_selector).html('Please Enter a valid email').show();
						else
							$('#'+randomid).html('Please Enter a valid email').show();
						$(this).focus();
						slidestart=false;
						return false;
					}
				}
				if($(this).is('select'))
				{
					if($.trim($(this).val())=='-1')
					{
						var msg=$(this).hasAttr('data-msg')?$(this).attr('data-msg'):'Please fill this field';
						if(options.error_position=="inside")
							current_slide.find(error_selector).html(msg).show();
						else
							$('#'+randomid).html(msg).show();
						$(this).focus();
						slidestart=false;
						return false;
					}
				}
				if(options.error_position=="inside")
					current_slide.find(error_selector).html('').hide();
				else
					$('#'+randomid).html('').hide();
				slidestart=true;
			});
		}else
			slidestart=true;
		if(current_slide.find('input[required],select[required],input[email]').length<=0)
			slidestart=true;
		if(slidestart && options.submit_handler!="")
			options.submit_handler();
	});
	if(!$.mobile)
	{
		if(options.mobile)
		{
			message('nomobilejq');
		}
		options.mobile=false
	}

	if(options.mobile)
	{
		$this.on("swiperight",function(){
			$this.prevSlide();
		});
		$this.on("swipeleft",function(){

			$this.nextSlide();
		});
	}

	$.fn.nextSlide=function(){
		var current_slide=$(this).get_current_slide();
		var next_slide=$(this).get_next_slide();
		var slidestart=false;
		if(options.validation)
		{
			current_slide.find('input[required],select[required],input[email]').each(function(index,element){
				if($(this).hasAttr('required'))
				{
					if($.trim($(this).val())=='')
					{
						var msg=$(this).hasAttr('data-msg')?$(this).attr('data-msg'):'Please fill this field';
						if(options.error_position=="inside")
							current_slide.find(error_selector).html(msg).show();
						else
							$('#'+randomid).html(msg).show();

						$(this).focus();
						slidestart=false;
						return false;
					}
				}

				if($(this).hasAttr('email'))
				{
					if(!emailvalid($.trim($(this).val())))
					{
						if(options.error_position=="inside")
							current_slide.find(error_selector).html('Please Enter a valid email').show();
						else
							$('#'+randomid).html('Please Enter a valid email').show();

						$(this).focus();
						slidestart=false;
						return false;
					}
				}
				if($(this).is('select'))
				{
					if($.trim($(this).val())=='-1')
					{
						var msg=$(this).hasAttr('data-msg')?$(this).attr('data-msg'):'Please fill this field';
						if(options.error_position=="inside")
							current_slide.find(error_selector).html(msg).show();
						else
							$('#'+randomid).html(msg).show();

						$(this).focus();
						slidestart=false;
						return false;
					}
				}
				if(options.error_position=="inside")
					current_slide.find(error_selector).html('').hide();
				else
					$('#'+randomid).html('').hide();

				slidestart=true;
			});
		}else
			slidestart=true;
		if(current_slide.find('input[required],select[required],input[email]').length<=0)
			slidestart=true;

		if(slidestart)
		{
			if(current_slide.hasAttr('call-after'))
				{
					var func=current_slide.attr('call-after');
					if(!eval(func))
					{
						slidestart=false;
						return false;
					}else
						slidestart=true;
				}else
					slidestart=true;
		}
		next_slide=$(this).get_next_slide();
		if(slidestart)
		{
			if(next_slide.hasAttr('call-before'))
			{
				var func=next_slide.attr('call-before');
				if(!eval(func))
				{
					slidestart=false;
					return false;
				}else
					slidestart=true;
			}else
				slidestart=true;
		}
		if(next_slide.hasAttr('ajax-url') && slidestart && !next_slide.hasAttr('ajax-done'))
		{
			if($.trim(next_slide.attr('ajax-url'))!="")
			{
				slidestart=false;
				if(next_slide.hasAttr('ajax-beforesubmit'))
					{
						if(next_slide.attr('ajax-beforesubmit')!="")
							eval(next_slide.attr('ajax-beforesubmit'));
					}
				$.ajax({
					url:next_slide.attr('ajax-url'),
					data:next_slide.hasAttr('ajax-data')? JSON.parse(next_slide.attr('ajax-data')):{},
					type:next_slide.hasAttr('ajax-type')?next_slide.attr('ajax-type'):'POST',
					success:function(data)
						 {
							var target="";
							target=next_slide.hasAttr('ajax-target')?next_slide.attr('ajax-target')!=""?next_slide.attr('ajax-target'):target:target;
							if(target!="")
							{
								 target.html(data);
								 if(!options.ajax_repeat)
								 next_slide.attr('ajax-done','');
							}else if(next_slide.find('[next],[prev]').length!=0)
							{
								next_slide.find('.jformslider_ajax_target').html(data);
								if(!options.ajax_repeat)
								next_slide.attr('ajax-done','');
							}else
							{
								next_slide.append(data);
								if(!options.ajax_repeat)
								next_slide.attr('ajax-done','');
							};
							ajaxprocessing=false;
							slidestart=true;
							var px=Number($this.find('ul').css('margin-left').replace("px",""));
							px-=width;
							$this.find('ul').animate({ marginLeft: px+'px' }, options.speed);
							if(next_slide.hasAttr('ajax-success'))
							{
								if(next_slide.attr('ajax-success')!="")
									eval(next_slide.attr('ajax-success'));
							}
						 },
				  error:function(x,y,z)
				  {
					  ajaxprocessing=false;
					  console.log(x,y,z);
				  }
			  });
			}
		}
		if(slidestart)
		{
			var px=Number($(this).find('ul').css('margin-left').replace("px",""));
			px-=width;
                        jf_animate($(this),px+'px');
			//$(this).find('ul').animate({ marginLeft: px+'px' }, options.speed);
		}
	};

	$.fn.prevSlide=function(){
		var slideback=true;
		var pre_slide=$(this).get_prev_slide();
		if(pre_slide.hasAttr('call-prev'))
				{
					var func=pre_slide.attr('call-prev');
					if(!eval(func))
					{
						slideback=false;
						return false;
					}else
						slideback=true;
				}else
					slideback=true;
		if(slideback)
		{
			var px=Number($(this).find('ul').css('margin-left').replace("px",""));
			px+=width;
			$(this).find('ul').animate({ marginLeft: px+'px' }, options.speed);
		}
	};
	$.fn.gotoSlide= function(slideid){
		var count=0;
		var found=false;
		var slidethis=$(this);
		$('[data-id="'+slideid+'"]').show();
		$(this).find('li').filter(':visible').each(function(index, element) {
			count++;
			if($(this).hasAttr('data-id'))
			{	if($(this).attr('data-id')==$.trim(slideid))
				{	found=true;
					return false;
				}
			}
		});
		var go_to=(count-1)*width;
		var px='-'+go_to+'px';
		if(found)
		{
			var gslide=$('[data-id="'+slideid+'"]');

			if(gslide.hasAttr('ajax-url'))
			{	if(gslide.attr('ajax-url')!="")
				{
					if(gslide.hasAttr('ajax-beforesubmit'))
					{
						if(gslide.attr('ajax-beforesubmit')!="")
							eval(gslide.attr('ajax-beforesubmit'));
					}
					$.ajax({
						url:gslide.attr('ajax-url'),
						data:gslide.hasAttr('ajax-data')? JSON.parse(gslide.attr('ajax-data')):{},
						type:gslide.hasAttr('ajax-type')?gslide.attr('ajax-type'):'POST',
						success:function(data)
						 {
							var target=gslide.hasAttr('ajax-target')?gslide.attr('ajax-target')!=""?gslide.attr('ajax-target'):"":"";
							if(target!="")
							{	target.html(data);
								if(!options.ajax_repeat)
									gslide.attr('ajax-done','');
							}else if(gslide.find('[next],[prev]').length!=0)
							{	gslide.find('.jformslider_ajax_target').html(data);
								if(!options.ajax_repeat)
									gslide.attr('ajax-done','');
							}else
							{	gslide.append(data);
								if(!options.ajax_repeat)
									gslide.attr('ajax-done','');
							};
							ajaxprocessing=false;
							slidestart=true;
							var px=Number($this.find('ul').css('margin-left').replace("px",""));
							px-=width;
							slidethis.find('ul').animate({ marginLeft:px }, options.speed);
							if(gslide.hasAttr('ajax-success'))
							{
								if(gslide.attr('ajax-success')!="")
									eval(gslide.attr('ajax-success'));
							}
						 },
						 error:function(x,y,z)
						 {	  ajaxprocessing=false;
							  console.log(x,y,z);
							  slidethis.find('ul').animate({ marginLeft:px }, options.speed);
						  }
					  });
				}
			}else
				slidethis.find('ul').animate({ marginLeft:px }, options.speed);
		}else
			message('nodataid');
	};
	message('startup');
	$.fn.get_slide_data=function(id){
	    var opjson=Object();
            if(arguments.length<=0)
                id="";
            var $ele=$this;
            if(!$.trim(id)=="")
                $ele=$('[data-id="'+id+'"]')

            $ele.find('input,select,textarea').each(function(index,element){
                if($(this).is(':radio'))
                {
                    if($(this).hasAttr('name'))
                    {
                        var rad_name=$(this).attr('name');
                        opjson[rad_name]=$('[name='+rad_name+']:checked').val();
                    }
                }else if($(this).is(':checkbox'))
                {
                    if($(this).hasAttr('name'))
                    {
                        var check_name=$(this).attr('name');
                        var carray=Array();
                        $('[name='+check_name+']:checked').each(function(index,element){
                            carray.push($(this).val());
                        });
                        opjson[check_name]=carray;
                    }
                }else
                {
                    if($(this).hasAttr('name'))
                        opjson[$(this).attr('name')]=$(this).val();
                    else
                        opjson[$(this).attr('id')]=$(this).val();
                }
             });
            return opjson;
	};
	$.fn.get_current_slide= function(){
            var px=Number($this.find('ul').css('margin-left').replace("px",""));
            var slide=-px/width;
            var slcount=-1;
            var current='';
            $this.find('li').filter(':visible').each(function(index, element) {
                    slcount++;
                    if(slcount==slide)
                    {
                            current=$(this);
                            return false;
                    }
            });
            if(current=="")
                message('no_cs');
            else
                return current;
	}
	$.fn.get_next_slide= function(){
            var px=Number($this.find('ul').css('margin-left').replace("px",""));
            var slide=-px/width;
            var slcount=-2;
            var current='';
            $this.find('li').filter(':visible').each(function(index, element) {
                    slcount++;
                    if(slcount==slide)
                    {
                            current=$(this);
                            return false;
                    }
            });
            if(current=="")
                message('no_ns');
            else
                return current;
	}
	$.fn.get_prev_slide= function(){
		var px=Number($this.find('ul').css('margin-left').replace("px",""));
		var slide=-px/width;
		var slcount=0;
		var current='';
		$this.find('li').filter(':visible').each(function(index, element) {
			slcount++;
			if(slcount==slide)
			{
                            current=$(this);
                            return false;
			}
		});
		if(current=="")
			message('no_ps');
		else
			return current;
	};
	$.fn.get_slide_details=function()
	{
		var px=Number($this.css('margin-left').replace("px",""));
                var w=options.width;
		var slide_nos=(-px/w)+1;
		var count=1;
		var did='';
		count=lilength;
		var pages={current:slide_nos,total:count};
		return pages;
	};
        function set_nav($this,index)
        {
            var n=next_button;
            var p=prev_button;
            var er=errorspan;
            var sub="";
            if(!options.next_button){n="";}
            if(!options.prev_button){p="";}
            if($this.hasAttr('no-next') || $this.hasAttr('data-no-next')){n="";}
            if($this.hasAttr('no-prev') || $this.hasAttr('data-no-prev')){p="";}
            if($this.hasAttr('no-next-prev') || $this.hasAttr('data-no-next-prev')){n=p="";}
            if($this.find(error_selector).length>=1){er="";}
            if(index==0){p="";}
            if(index==lilength-1){n="";sub=submit_element;}
            var nv='
'+p+er+n+sub+'
';
            if($this.hasAttr('data-button-placement') || $this.hasAttr('button-placement'))
            {
                $pl=$this.hasAttr('data-button-placement')?$this.attr('data-button-placement'):'';
                $pl=$this.hasAttr('button-placement')?$this.attr('button-placement'):'';
                if($.trim($pl)=="top")
                    $this.prepend(nv);
                else
                    $this.append(nv);
            }else if($.trim(options.button_placement)=="top")
                $this.prepend(nv);
            else
                $this.append(nv);
        }
        function jf_animate(el,px)
        {
            if(options.animation=="vertical")
                el.find('ul').animate({ marginTop:px }, options.speed);
            else
                el.find('ul').animate({ marginLeft:px }, options.speed);
        }
	function message(type)
	{
		var msg='';
		var style=""
		switch(type)
		{
			case 'startup':msg='%c Congratulations!!!  You are using %cjFormslider '+version;
						  style='color: green';
						  if('undefined'!==typeof console)
							{
								console.log(msg,style,'font-style:italic;font-size:15px;font-weight:bold;'+style);
							}
						  break;
			case 'nodataid':msg='%c No %c"data-id" %cdefined; Please define a %c"data-id" %cin a li to use function %c"gotoSlide()" ';
						  style='color: red';
						  style1=style+';font-style:italic;font-size:15px;font-weight:bold;';
						  if('undefined'!==typeof console)
							{
								console.log(msg,style,style1,style,style1,style,style1);
							}
						  break;
			case "nojquery":
						  msg='%c Sorry!!There is no jquery please get jquery ';
						  style='color: red';
						    if('undefined'!==typeof console)
							{
								console.log(msg,style);
							}else
							{
								throw new Error("Sorry!!There is no jquery please get jquery");
							}
						break;
			case "nomobilejq":
						  msg='%c Sorry!!There is no jquery mobile please get jquery mobile';
						  style='color: red';
						    if('undefined'!==typeof console)
							{
								console.log(msg,style);
							}else
							{
								throw new Error("Sorry!!There is no jquery mobile please get jquery mobile");
							}
						break;
			case 'no_cs':msg='%c Sorry!! There is no current slide Some Unknown Error Occured.Please try again ';
						  style='color: red';
						  style1=style+';font-style:italic;font-size:15px;font-weight:bold;';
						  if('undefined'!==typeof console)
							{
								console.log(msg,style);
							}
						  break;
			case 'no_ns':msg='%c Sorry!! There is no next slide ';
						  style='color: red';
						  style1=style+';font-style:italic;font-size:15px;font-weight:bold;';
						  if('undefined'!==typeof console)
							{
								console.log(msg,style);
							}
						  break;
			case 'no_ps':msg='%c Sorry!! There is no previous slide';
						  style='color: red';
						  style1=style+';font-style:italic;font-size:15px;font-weight:bold;';
						  if('undefined'!==typeof console)
							{
								console.log(msg,style);
							}
						  break;

			case 'unknown':msg='%c Sorry!! Some Unknown Error Occured.Please try again ';
						  style='color: red';
						  style1=style+';font-style:italic;font-size:15px;font-weight:bold;';
						  if('undefined'!==typeof console)
							{
								console.log(msg,style);
							}
						  break;
		}
	}
	function emailvalid(email)
	{
		var rexp = /\S+@\S+\.\S+/;
		return rexp.test(email);
	}
	function splitclass(str)
	{
		return str.split(/\s+/);
	}
        function get_width(w)
        {
            w=Number(w);
            var screen=$(window).width();
            if(screen>361 && screen<640)
            {
                return w*40/100;
            }else if(screen>641 && screen<767)
            {
                return w*65/100;
            }else if(screen>768 && screen<991)
            {
                 return w*75/100;
            }else if(screen>992 && screen<1199)
            {
                return w*100/100;
            }else
            {
                 return w*100/100;
            }
        }
        function get_height(w)
        {
            w=Number(w);
            var screen=$(window).width();
            if(screen>361 && screen<640)
            {
                return w*70/100;
            }else if(screen>641 && screen<767)
            {
                return w*70/100;
            }else if(screen>768 && screen<991)
            {
                 return w*75/100;
            }else if(screen>992 && screen<1199)
            {
                return w*100/100;
            }else
            {
                 return w*100/100;
            }
        }

};
$.fn.hasAttr = function(name)
{
   	return this.attr(name) !== undefined;
};<commit_msg>Delete jFormslider.js<commit_after><|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
exports.index = function(req, res) {
	res.render('index', {
		user: req.user || null
	});
};

exports.landing = function(req, res) {
	res.render('landing', {
    user: req.user || null
  ]);

exports.about = function(req, res) {
	res.render('about', {
		user: req.user || null
	});
};
<commit_msg>silly typos<commit_after>'use strict';

/**
 * Module dependencies.
 */
exports.index = function(req, res) {
	res.render('index', {
		user: req.user || null
	});
};

exports.landing = function(req, res) {
	res.render('landing', {
    user: req.user || null
  });
};

exports.about = function(req, res) {
	res.render('about', {
		user: req.user || null
	});
};
<|endoftext|>