<commit_before>// This [jQuery](http://jquery.com/) plugin implements an `<iframe>`
// [transport](http://api.jquery.com/extending-ajax/#Transports) so that
// `$.ajax()` calls support the uploading of files using standard HTML file
// input fields. This is done by switching the exchange from `XMLHttpRequest`
// to a hidden `iframe` element containing a form that is submitted.

// The [source for the plugin](http://github.com/cmlenz/jquery-iframe-transport)
// is available on [Github](http://github.com/) and dual licensed under the MIT
// or GPL Version 2 licenses.

// ## Usage

// To use this plugin, you simply add an `iframe` option with the value `true`
// to the Ajax settings an `$.ajax()` call, and specify the file fields to
// include in the submssion using the `files` option, which can be a selector,
// jQuery object, or a list of DOM elements containing one or more
// `<input type="file">` elements:

//     $("#myform").submit(function() {
//         $.ajax(this.action, {
//             files: $(":file", this),
//             iframe: true
//         }).complete(function(data) {
//             console.log(data);
//         });
//     });

// The plugin will construct a hidden `<iframe>` element containing a copy of
// the form the file field belongs to, will disable any form fields not
// explicitly included, submit that form, and process the response.

// If you want to include other form fields in the form submission, include
// them in the `data` option, and set the `processData` option to `false`:

//     $("#myform").submit(function() {
//         $.ajax(this.action, {
//             data: $(":text", this).serializeArray(),
//             files: $(":file", this),
//             iframe: true,
//             processData: false
//         }).complete(function(data) {
//             console.log(data);
//         });
//     });

// ### Response Data Types

// As the transport does not have access to the HTTP headers of the server
// response, it is not as simple to make use of the automatic content type
// detection provided by jQuery as with regular XHR. If you can't set the
// expected response data type (for example because it may vary), you will
// need to employ a workaround on the server side: Send back an HTML document
// containing just a `<textarea>` element with a `data-type` attribute that
// specifies the MIME type, and put the actual payload in the textarea:

//     <textarea data-type="application/json">
//       {"ok": true, "message": "Thanks so much"}
//     </textarea>

// The iframe transport plugin will detect this and pass the value of the
// `data-type` attribute on to jQuery as if it was the "Content-Type" response
// header, thereby enabling the same kind of conversions that jQuery applies
// to regular responses. For the example above you should get a Javascript
// object as the `data` parameter of the `complete` callback, with the
// properties `ok: true` and `message: "Thanks so much"`.

// ### Handling Server Errors

// Another problem with using an `iframe` for file uploads is that it is
// impossible for the javascript code to determine the HTTP status code of the
// servers response. Effectively, all of the calls you make will look like they
// are getting successful responses, and thus invoke the `done()` or
// `complete()` callbacks. You can only determine communicate problems using
// the content of the response payload. For example, consider using a JSON
// response such as the following to indicate a problem with an uploaded file:

//     <textarea data-type="application/json">
//       {"ok": false, "message": "Please only upload reasonably sized files."}
//     </textarea>

// ### Compatibility

// This plugin has primarily been tested on Safari 5 (or later), Firefox 4 (or
// later), and Internet Explorer (all the way back to version 6). While I
// haven't found any issues with it so far, I'm fairly sure it still doesn't
// work around all the quirks in all different browsers. But the code is still
// pretty simple overall, so you should be able to fix it and contribute a
// patch :)

// ## Annotated Source

(function($, undefined) {
  "use strict";

  // Register a prefilter that checks whether the `iframe` option is set, and
  // switches to the "iframe" data type if it is `true`.
  $.ajaxPrefilter(function(options, origOptions, jqXHR) {
    if (options.iframe) {
      return "iframe";
    }
  });

  // Register a transport for the "iframe" data type. It will only activate
  // when the "files" option has been set to a non-empty list of enabled file
  // inputs.
  $.ajaxTransport("iframe", function(options, origOptions, jqXHR) {
    var form = null,
        iframe = null,
        name = "iframe-" + $.now(),
        files = $(options.files).filter(":file:enabled"),
        markers = null;

    // This function gets called after a successful submission or an abortion
    // and should revert all changes made to the page to enable the
    // submission via this transport.
    function cleanUp() {
      markers.replaceWith(function(idx) {
        return files.get(idx);
      });
      form.remove();
      iframe.attr("src", "javascript:false;").remove();
    }

    // Remove "iframe" from the data types list so that further processing is
    // based on the content type returned by the server, without attempting an
    // (unsupported) conversion from "iframe" to the actual type.
    options.dataTypes.shift();

    if (files.length) {
      form = $("<form enctype='multipart/form-data' method='post'></form>").
        hide().attr({action: options.url, target: name});

      // If there is any additional data specified via the `data` option,
      // we add it as hidden fields to the form. This (currently) requires
      // the `processData` option to be set to false so that the data doesn't
      // get serialized to a string.
      if (typeof(options.data) === "string" && options.data.length > 0) {
        $.error("data must not be serialized");
      }
      $.each(options.data || {}, function(name, value) {
        if ($.isPlainObject(value)) {
          name = value.name;
          value = value.value;
        }
        $("<input type='hidden'>").attr({name:  name, value: value}).
          appendTo(form);
      });

      // Add a hidden `X-Requested-With` field with the value `IFrame` to the
      // field, to help server-side code to determine that the upload happened
      // through this transport.
      $("<input type='hidden' value='IFrame' name='X-Requested-With'>").
        appendTo(form);

      // Move the file fields into the hidden form, but first remember their
      // original locations in the document by replacing them with disabled
      // clones. This should also avoid introducing unwanted changes to the
      // page layout during submission.
      markers = files.after(function(idx) {
        return $(this).clone().prop("disabled", true);
      }).next();
      files.appendTo(form);

      return {

        // The `send` function is called by jQuery when the request should be
        // sent.
        send: function(headers, completeCallback) {
          iframe = $("");

          // The first load event gets fired after the iframe has been injected
          // into the DOM, and is used to prepare the actual submission.
          iframe.bind("load", function() {

            // The second load event gets fired when the response to the form
            // submission is received. The implementation detects whether the
            // actual payload is embedded in a `<textarea>` element, and
            // prepares the required conversions to be made in that case.
            iframe.unbind("load").bind("load", function() {
              var doc = this.contentWindow ? this.contentWindow.document :
                (this.contentDocument ? this.contentDocument : this.document),
                root = doc.documentElement ? doc.documentElement : doc.body,
                textarea = root.getElementsByTagName("textarea")[0],
                type = textarea ? textarea.getAttribute("data-type") : null,
                content = {
                  html: root.innerHTML,
                  text: type ?
                    textarea.value :
                    root ? (root.textContent || root.innerText) : null
                };
              cleanUp();
              completeCallback(200, "OK", content, type ?
                ("Content-Type: " + type) :
                null);
            });

            // Now that the load handler has been set up, submit the form.
            form[0].submit();
          });

          // After everything has been set up correctly, the form and iframe
          // get injected into the DOM so that the submission can be
          // initiated.
          $("body").append(form, iframe);
        },

        // The `abort` function is called by jQuery when the request should be
        // aborted.
        abort: function() {
          if (iframe !== null) {
            iframe.unbind("load").attr("src", "javascript:false;");
            cleanUp();
          }
        }

      };
    }
  });

})(jQuery);
<commit_msg>Documentation tweaks.<commit_after>// This [jQuery](http://jquery.com/) plugin implements an `<iframe>`
// [transport](http://api.jquery.com/extending-ajax/#Transports) so that
// `$.ajax()` calls support the uploading of files using standard HTML file
// input fields. This is done by switching the exchange from `XMLHttpRequest`
// to a hidden `iframe` element containing a form that is submitted.

// The [source for the plugin](http://github.com/cmlenz/jquery-iframe-transport)
// is available on [Github](http://github.com/) and dual licensed under the MIT
// or GPL Version 2 licenses.

// ## Usage

// To use this plugin, you simply add an `iframe` option with the value `true`
// to the Ajax settings an `$.ajax()` call, and specify the file fields to
// include in the submssion using the `files` option, which can be a selector,
// jQuery object, or a list of DOM elements containing one or more
// `<input type="file">` elements:

//     $("#myform").submit(function() {
//         $.ajax(this.action, {
//             files: $(":file", this),
//             iframe: true
//         }).complete(function(data) {
//             console.log(data);
//         });
//     });

// The plugin will construct hidden `<iframe>` and `<form>` elements, add the
// file field(s) to that form, submit the form, and process the response.

// If you want to include other form fields in the form submission, include
// them in the `data` option, and set the `processData` option to `false`:

//     $("#myform").submit(function() {
//         $.ajax(this.action, {
//             data: $(":text", this).serializeArray(),
//             files: $(":file", this),
//             iframe: true,
//             processData: false
//         }).complete(function(data) {
//             console.log(data);
//         });
//     });

// ### Response Data Types

// As the transport does not have access to the HTTP headers of the server
// response, it is not as simple to make use of the automatic content type
// detection provided by jQuery as with regular XHR. If you can't set the
// expected response data type (for example because it may vary depending on
// the outcome of processing by the server), you will need to employ a
// workaround on the server side: Send back an HTML document containing just a
// `<textarea>` element with a `data-type` attribute that specifies the MIME
// type, and put the actual payload in the textarea:

//     <textarea data-type="application/json">
//       {"ok": true, "message": "Thanks so much"}
//     </textarea>

// The iframe transport plugin will detect this and pass the value of the
// `data-type` attribute on to jQuery as if it was the "Content-Type" response
// header, thereby enabling the same kind of conversions that jQuery applies
// to regular responses. For the example above you should get a Javascript
// object as the `data` parameter of the `complete` callback, with the
// properties `ok: true` and `message: "Thanks so much"`.

// ### Handling Server Errors

// Another problem with using an `iframe` for file uploads is that it is
// impossible for the javascript code to determine the HTTP status code of the
// servers response. Effectively, all of the calls you make will look like they
// are getting successful responses, and thus invoke the `done()` or
// `complete()` callbacks. You can only determine communicate problems using
// the content of the response payload. For example, consider using a JSON
// response such as the following to indicate a problem with an uploaded file:

//     <textarea data-type="application/json">
//       {"ok": false, "message": "Please only upload reasonably sized files."}
//     </textarea>

// ### Compatibility

// This plugin has primarily been tested on Safari 5 (or later), Firefox 4 (or
// later), and Internet Explorer (all the way back to version 6). While I
// haven't found any issues with it so far, I'm fairly sure it still doesn't
// work around all the quirks in all different browsers. But the code is still
// pretty simple overall, so you should be able to fix it and contribute a
// patch :)

// ## Annotated Source

(function($, undefined) {
  "use strict";

  // Register a prefilter that checks whether the `iframe` option is set, and
  // switches to the "iframe" data type if it is `true`.
  $.ajaxPrefilter(function(options, origOptions, jqXHR) {
    if (options.iframe) {
      return "iframe";
    }
  });

  // Register a transport for the "iframe" data type. It will only activate
  // when the "files" option has been set to a non-empty list of enabled file
  // inputs.
  $.ajaxTransport("iframe", function(options, origOptions, jqXHR) {
    var form = null,
        iframe = null,
        name = "iframe-" + $.now(),
        files = $(options.files).filter(":file:enabled"),
        markers = null;

    // This function gets called after a successful submission or an abortion
    // and should revert all changes made to the page to enable the
    // submission via this transport.
    function cleanUp() {
      markers.replaceWith(function(idx) {
        return files.get(idx);
      });
      form.remove();
      iframe.attr("src", "javascript:false;").remove();
    }

    // Remove "iframe" from the data types list so that further processing is
    // based on the content type returned by the server, without attempting an
    // (unsupported) conversion from "iframe" to the actual type.
    options.dataTypes.shift();

    if (files.length) {
      form = $("<form enctype='multipart/form-data' method='post'></form>").
        hide().attr({action: options.url, target: name});

      // If there is any additional data specified via the `data` option,
      // we add it as hidden fields to the form. This (currently) requires
      // the `processData` option to be set to false so that the data doesn't
      // get serialized to a string.
      if (typeof(options.data) === "string" && options.data.length > 0) {
        $.error("data must not be serialized");
      }
      $.each(options.data || {}, function(name, value) {
        if ($.isPlainObject(value)) {
          name = value.name;
          value = value.value;
        }
        $("<input type='hidden'>").attr({name:  name, value: value}).
          appendTo(form);
      });

      // Add a hidden `X-Requested-With` field with the value `IFrame` to the
      // field, to help server-side code to determine that the upload happened
      // through this transport.
      $("<input type='hidden' value='IFrame' name='X-Requested-With'>").
        appendTo(form);

      // Move the file fields into the hidden form, but first remember their
      // original locations in the document by replacing them with disabled
      // clones. This should also avoid introducing unwanted changes to the
      // page layout during submission.
      markers = files.after(function(idx) {
        return $(this).clone().prop("disabled", true);
      }).next();
      files.appendTo(form);

      return {

        // The `send` function is called by jQuery when the request should be
        // sent.
        send: function(headers, completeCallback) {
          iframe = $("");

          // The first load event gets fired after the iframe has been injected
          // into the DOM, and is used to prepare the actual submission.
          iframe.bind("load", function() {

            // The second load event gets fired when the response to the form
            // submission is received. The implementation detects whether the
            // actual payload is embedded in a `<textarea>` element, and
            // prepares the required conversions to be made in that case.
            iframe.unbind("load").bind("load", function() {
              var doc = this.contentWindow ? this.contentWindow.document :
                (this.contentDocument ? this.contentDocument : this.document),
                root = doc.documentElement ? doc.documentElement : doc.body,
                textarea = root.getElementsByTagName("textarea")[0],
                type = textarea ? textarea.getAttribute("data-type") : null,
                content = {
                  html: root.innerHTML,
                  text: type ?
                    textarea.value :
                    root ? (root.textContent || root.innerText) : null
                };
              cleanUp();
              completeCallback(200, "OK", content, type ?
                ("Content-Type: " + type) :
                null);
            });

            // Now that the load handler has been set up, submit the form.
            form[0].submit();
          });

          // After everything has been set up correctly, the form and iframe
          // get injected into the DOM so that the submission can be
          // initiated.
          $("body").append(form, iframe);
        },

        // The `abort` function is called by jQuery when the request should be
        // aborted.
        abort: function() {
          if (iframe !== null) {
            iframe.unbind("load").attr("src", "javascript:false;");
            cleanUp();
          }
        }

      };
    }
  });

})(jQuery);
<|endoftext|>


<commit_before>/**
* simplePagination.js v1.6
* A simple jQuery pagination plugin.
* http://flaviusmatis.github.com/simplePagination.js/
*
* Copyright 2012, Flavius Matis
* Released under the MIT license.
* http://flaviusmatis.github.com/license.html
*/

(function($){

	var methods = {
		init: function(options) {
			var o = $.extend({
				items: 1,
				itemsOnPage: 1,
				pages: 0,
				displayedPages: 5,
				edges: 2,
				currentPage: 1,
				hrefTextPrefix: '#page-',
				hrefTextSuffix: '',
				prevText: 'Prev',
				nextText: 'Next',
				ellipseText: '…',
				cssStyle: 'light-theme',
                labelMap:null,
				selectOnClick: true,
				onPageClick: function(pageNumber, event) {
					// Callback triggered when a page is clicked
					// Page number is given as an optional parameter
				},
				onInit: function() {
					// Callback triggered immediately after initialization
				}
			}, options || {});

			var self = this;

			o.pages = o.pages ? o.pages : Math.ceil(o.items / o.itemsOnPage) ? Math.ceil(o.items / o.itemsOnPage) : 1;
			o.currentPage = o.currentPage - 1;
			o.halfDisplayed = o.displayedPages / 2;

			this.each(function() {
				self.addClass(o.cssStyle + ' simple-pagination').data('pagination', o);
				methods._draw.call(self);
			});

			o.onInit();

			return this;
		},

		selectPage: function(page) {
			methods._selectPage.call(this, page - 1);
			return this;
		},

		prevPage: function() {
			var o = this.data('pagination');
			if (o.currentPage > 0) {
				methods._selectPage.call(this, o.currentPage - 1);
			}
			return this;
		},

		nextPage: function() {
			var o = this.data('pagination');
			if (o.currentPage < o.pages - 1) {
				methods._selectPage.call(this, o.currentPage + 1);
			}
			return this;
		},

		getPagesCount: function() {
			return this.data('pagination').pages;
		},

		getCurrentPage: function () {
			return this.data('pagination').currentPage + 1;
		},

		destroy: function(){
			this.empty();
			return this;
		},

		drawPage: function (page) {
			var o = this.data('pagination');
			o.currentPage = page - 1;
			this.data('pagination', o);
			methods._draw.call(this);
			return this;
		},

		redraw: function(){
			methods._draw.call(this);
			return this;
		},

		disable: function(){
			var o = this.data('pagination');
			o.disabled = true;
			this.data('pagination', o);
			methods._draw.call(this);
			return this;
		},

		enable: function(){
			var o = this.data('pagination');
			o.disabled = false;
			this.data('pagination', o);
			methods._draw.call(this);
			return this;
		},

		updateItems: function (newItems) {
			var o = this.data('pagination');
			o.items = newItems;
			o.pages = Math.ceil(o.items / o.itemsOnPage) ? Math.ceil(o.items / o.itemsOnPage) : 1;
			this.data('pagination', o);
			methods._draw.call(this);
		},

		updateItemsOnPage: function (itemsOnPage) {
			var o = this.data('pagination');
			o.itemsOnPage = itemsOnPage;
			this.data('pagination', o);
			methods._selectPage.call(this, 0);
			return this;
		},

		_draw: function() {
			var	o = this.data('pagination'),
				interval = methods._getInterval(o),
				i;

			methods.destroy.call(this);

			var $panel = this.prop("tagName") === "UL" ? this : $('

').appendTo(this);

			// Generate Prev link
			if (o.prevText) {
				methods._appendItem.call(this, o.currentPage - 1, {text: o.prevText, classes: 'prev'});
			}

			// Generate start edges
			if (interval.start > 0 && o.edges > 0) {
				var end = Math.min(o.edges, interval.start);
				for (i = 0; i < end; i++) {
					methods._appendItem.call(this, i);
				}
				if (o.edges < interval.start && (interval.start - o.edges != 1)) {
					$panel.append('
' + o.ellipseText + '
');
				} else if (interval.start - o.edges == 1) {
					methods._appendItem.call(this, o.edges);
				}
			}

			// Generate interval links
			for (i = interval.start; i < interval.end; i++) {
				methods._appendItem.call(this, i);
			}

			// Generate end edges
			if (interval.end < o.pages && o.edges > 0) {
				if (o.pages - o.edges > interval.end && (o.pages - o.edges - interval.end != 1)) {
					$panel.append('
' + o.ellipseText + '
');
				} else if (o.pages - o.edges - interval.end == 1) {
					methods._appendItem.call(this, interval.end++);
				}
				var begin = Math.max(o.pages - o.edges, interval.end);
				for (i = begin; i < o.pages; i++) {
					methods._appendItem.call(this, i);
				}
			}

			// Generate Next link
			if (o.nextText) {
				methods._appendItem.call(this, o.currentPage + 1, {text: o.nextText, classes: 'next'});
			}
		},

		_getInterval: function(o) {
			return {
				start: Math.ceil(o.currentPage > o.halfDisplayed ? Math.max(Math.min(o.currentPage - o.halfDisplayed, (o.pages - o.displayedPages)), 0) : 0),
				end: Math.ceil(o.currentPage > o.halfDisplayed ? Math.min(o.currentPage + o.halfDisplayed, o.pages) : Math.min(o.displayedPages, o.pages))
			};
		},

		_appendItem: function(pageIndex, opts) {
			var self = this, options, $link, o = self.data('pagination'), $linkWrapper = $('

'), $ul = self.find('ul');

			pageIndex = pageIndex < 0 ? 0 : (pageIndex < o.pages ? pageIndex : o.pages - 1);

            options = {
                text: pageIndex + 1,
                classes: ''
            };

            if(o.labelMap != null && typeof o.labelMap[pageIndex] != 'undefined') {
                options.text = o.labelMap[pageIndex];
            }

            options = $.extend(options, opts || {});

			if (pageIndex == o.currentPage || o.disabled) {
				if (o.disabled) {
					$linkWrapper.addClass('disabled');
				} else {
					$linkWrapper.addClass('active');
				}
				$link = $('' + (options.text) + '');
			} else {
				$link = $('' + (options.text) + '');
				$link.click(function(event){
					return methods._selectPage.call(self, pageIndex, event);
				});
			}

			if (options.classes) {
				$link.addClass(options.classes);
			}

			$linkWrapper.append($link);

			if ($ul.length) {
				$ul.append($linkWrapper);
			} else {
				self.append($linkWrapper);
			}
		},

		_selectPage: function(pageIndex, event) {
			var o = this.data('pagination');
			o.currentPage = pageIndex;
			if (o.selectOnClick) {
				methods._draw.call(this);
			}
			return o.onPageClick(pageIndex + 1, event);
		}

	};

	$.fn.pagination = function(method) {

		// Method calling logic
		if (methods[method] && method.charAt(0) != '_') {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' +  method + ' does not exist on jQuery.pagination');
		}

	};

})(jQuery);
<commit_msg>Small refactoring<commit_after>/**
* simplePagination.js v1.6
* A simple jQuery pagination plugin.
* http://flaviusmatis.github.com/simplePagination.js/
*
* Copyright 2012, Flavius Matis
* Released under the MIT license.
* http://flaviusmatis.github.com/license.html
*/

(function($){

	var methods = {
		init: function(options) {
			var o = $.extend({
				items: 1,
				itemsOnPage: 1,
				pages: 0,
				displayedPages: 5,
				edges: 2,
				currentPage: 1,
				hrefTextPrefix: '#page-',
				hrefTextSuffix: '',
				prevText: 'Prev',
				nextText: 'Next',
				ellipseText: '…',
				cssStyle: 'light-theme',
				labelMap: [],
				selectOnClick: true,
				onPageClick: function(pageNumber, event) {
					// Callback triggered when a page is clicked
					// Page number is given as an optional parameter
				},
				onInit: function() {
					// Callback triggered immediately after initialization
				}
			}, options || {});

			var self = this;

			o.pages = o.pages ? o.pages : Math.ceil(o.items / o.itemsOnPage) ? Math.ceil(o.items / o.itemsOnPage) : 1;
			o.currentPage = o.currentPage - 1;
			o.halfDisplayed = o.displayedPages / 2;

			this.each(function() {
				self.addClass(o.cssStyle + ' simple-pagination').data('pagination', o);
				methods._draw.call(self);
			});

			o.onInit();

			return this;
		},

		selectPage: function(page) {
			methods._selectPage.call(this, page - 1);
			return this;
		},

		prevPage: function() {
			var o = this.data('pagination');
			if (o.currentPage > 0) {
				methods._selectPage.call(this, o.currentPage - 1);
			}
			return this;
		},

		nextPage: function() {
			var o = this.data('pagination');
			if (o.currentPage < o.pages - 1) {
				methods._selectPage.call(this, o.currentPage + 1);
			}
			return this;
		},

		getPagesCount: function() {
			return this.data('pagination').pages;
		},

		getCurrentPage: function () {
			return this.data('pagination').currentPage + 1;
		},

		destroy: function(){
			this.empty();
			return this;
		},

		drawPage: function (page) {
			var o = this.data('pagination');
			o.currentPage = page - 1;
			this.data('pagination', o);
			methods._draw.call(this);
			return this;
		},

		redraw: function(){
			methods._draw.call(this);
			return this;
		},

		disable: function(){
			var o = this.data('pagination');
			o.disabled = true;
			this.data('pagination', o);
			methods._draw.call(this);
			return this;
		},

		enable: function(){
			var o = this.data('pagination');
			o.disabled = false;
			this.data('pagination', o);
			methods._draw.call(this);
			return this;
		},

		updateItems: function (newItems) {
			var o = this.data('pagination');
			o.items = newItems;
			o.pages = Math.ceil(o.items / o.itemsOnPage) ? Math.ceil(o.items / o.itemsOnPage) : 1;
			this.data('pagination', o);
			methods._draw.call(this);
		},

		updateItemsOnPage: function (itemsOnPage) {
			var o = this.data('pagination');
			o.itemsOnPage = itemsOnPage;
			this.data('pagination', o);
			methods._selectPage.call(this, 0);
			return this;
		},

		_draw: function() {
			var	o = this.data('pagination'),
				interval = methods._getInterval(o),
				i;

			methods.destroy.call(this);

			var $panel = this.prop("tagName") === "UL" ? this : $('

').appendTo(this);

			// Generate Prev link
			if (o.prevText) {
				methods._appendItem.call(this, o.currentPage - 1, {text: o.prevText, classes: 'prev'});
			}

			// Generate start edges
			if (interval.start > 0 && o.edges > 0) {
				var end = Math.min(o.edges, interval.start);
				for (i = 0; i < end; i++) {
					methods._appendItem.call(this, i);
				}
				if (o.edges < interval.start && (interval.start - o.edges != 1)) {
					$panel.append('
' + o.ellipseText + '
');
				} else if (interval.start - o.edges == 1) {
					methods._appendItem.call(this, o.edges);
				}
			}

			// Generate interval links
			for (i = interval.start; i < interval.end; i++) {
				methods._appendItem.call(this, i);
			}

			// Generate end edges
			if (interval.end < o.pages && o.edges > 0) {
				if (o.pages - o.edges > interval.end && (o.pages - o.edges - interval.end != 1)) {
					$panel.append('
' + o.ellipseText + '
');
				} else if (o.pages - o.edges - interval.end == 1) {
					methods._appendItem.call(this, interval.end++);
				}
				var begin = Math.max(o.pages - o.edges, interval.end);
				for (i = begin; i < o.pages; i++) {
					methods._appendItem.call(this, i);
				}
			}

			// Generate Next link
			if (o.nextText) {
				methods._appendItem.call(this, o.currentPage + 1, {text: o.nextText, classes: 'next'});
			}
		},

		_getInterval: function(o) {
			return {
				start: Math.ceil(o.currentPage > o.halfDisplayed ? Math.max(Math.min(o.currentPage - o.halfDisplayed, (o.pages - o.displayedPages)), 0) : 0),
				end: Math.ceil(o.currentPage > o.halfDisplayed ? Math.min(o.currentPage + o.halfDisplayed, o.pages) : Math.min(o.displayedPages, o.pages))
			};
		},

		_appendItem: function(pageIndex, opts) {
			var self = this, options, $link, o = self.data('pagination'), $linkWrapper = $('

'), $ul = self.find('ul');

			pageIndex = pageIndex < 0 ? 0 : (pageIndex < o.pages ? pageIndex : o.pages - 1);

			options = {
				text: pageIndex + 1,
				classes: ''
			};

			if (o.labelMap.length && o.labelMap[pageIndex]) {
				options.text = o.labelMap[pageIndex];
			}

			options = $.extend(options, opts || {});

			if (pageIndex == o.currentPage || o.disabled) {
				if (o.disabled) {
					$linkWrapper.addClass('disabled');
				} else {
					$linkWrapper.addClass('active');
				}
				$link = $('' + (options.text) + '');
			} else {
				$link = $('' + (options.text) + '');
				$link.click(function(event){
					return methods._selectPage.call(self, pageIndex, event);
				});
			}

			if (options.classes) {
				$link.addClass(options.classes);
			}

			$linkWrapper.append($link);

			if ($ul.length) {
				$ul.append($linkWrapper);
			} else {
				self.append($linkWrapper);
			}
		},

		_selectPage: function(pageIndex, event) {
			var o = this.data('pagination');
			o.currentPage = pageIndex;
			if (o.selectOnClick) {
				methods._draw.call(this);
			}
			return o.onPageClick(pageIndex + 1, event);
		}

	};

	$.fn.pagination = function(method) {

		// Method calling logic
		if (methods[method] && method.charAt(0) != '_') {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' +  method + ' does not exist on jQuery.pagination');
		}

	};

})(jQuery);
<|endoftext|>


<commit_before>/*global define, exports*/
/*jshint maxlen:false*/
(function (root, factory) {
    "use strict";

    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
    // Rhino, and plain browser loading.
    if (typeof define === "function" && define.amd) {
        define(["exports"], factory);
    } else if (typeof exports !== "undefined") {
        factory(exports);
    } else {
        factory((root.gpf = {}));
    }
}(this, function (gpf) {
    "use strict";

    __gpf__;
}));<commit_msg>Fixed gpf naming in release boot<commit_after>/*global define, exports*/
/*jshint maxlen:false*/
(function (root, factory) {
    "use strict";

    // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
    // Rhino, and plain browser loading.
    if (typeof define === "function" && define.amd) {
        define(["exports"], factory);
    } else if (typeof exports !== "undefined") {
        factory(exports);
    } else {
        factory((root.gpf = {}));
    }
}(this, function (/*gpf:no-reduce*/gpf) {
    "use strict";

    __gpf__;
}));<|endoftext|>


<commit_before>(function( Factlink ) {

Factlink.showInfo = function( el ) {
    Factlink.remote.showFactlink( el.getAttribute("data-factid") );
    Factlink.modal.showFrame.method();
    Factlink.modal.showOverlay.method();
};

// Handle a user click
$( 'span.factlink' ).live('click', function() {
    Factlink.showInfo( this );
});

// Object which holds the methods that can be called from the intermediate iframe
// These methods are also used by the internal scripts and can be called through
// Factlink.modal.FUNCTION.method() because easyXDM changes the object structure
Factlink.modal = {
    positionFrame: function( top, left ) {
        Factlink.$frame.css({
            top: top,
            left: left
        });
    },
    resetStyle: function() {
        Factlink.$frame.attr('style','');
    },
    setFrameBounds: function( width, height ) {
        var $frame = Factlink.$frame;

        $frame.css({
            height: height,
            width: width
        });

        if ( $frame.hasClass("show") ) {
            $frame.css({
                margin: "-" + height / 2 + "px 0 0 -" + width / 2 + "px"
            });
        }
    },
    hideFrame: function() {
        unbindClick();
        Factlink.$frame.hide();
    },
    showFrame: function() {
        bindClick();
        Factlink.$frame.show();
    },
    setFrameType: function( type ) {
        Factlink.$frame
            .attr('class', type)
            .show();
    },
    showOverlay: function() {
        Factlink.overlay.show();
    },
    hideOverlay: function() {
        Factlink.overlay.hide();
    },
    highlightNewFactlink: function( fact, id ) {
        Factlink.selectRanges( Factlink.search(fact), id );
    }
};

var bindClick = function() {
        $( document ).bind('click', clickHandler);
    },
    unbindClick = function() {
        $( document ).unbind('click', clickHandler)
    },
    clickHandler = function() {
        Factlink.modal.hideOverlay.method();
        Factlink.modal.hideFrame.method();
    };

// INDICATOR

// Indicator object which will manage the indicator which shows some basic info
// of each Factlink
Factlink.Indicator = (function() {
    // By default the element object is undefined
    var el,
        // Is the indicator currently visible?
        visible = false,
        // This object will store the timeout id
        timeout,
        // Current shown Factlink
        currentId,
        // Position of the indication
        x, y;

    return {
        // Makes the indicator show for the Factlink with id ID
        showFor: function( id, mouseX, mouseY ) {
            // Get the Factlink-object
            var fl = $( 'span.factlink[data-factid=' + id + ']');

            if ( id !== currentId ) {
                x = mouseX + 10,
                y = mouseY - el.outerHeight(true) - 10;
            }

            window.clearTimeout( timeout );

            // Store the currentId;
            currentId = id;

            timeout = window.setTimeout(function(){
                if ( el === undefined )
                    return;

                el
                    .css({
                        top: y,
                        left: x
                    })
                    .show();
            }, 10);
        },
        // Makes the indicator hide itself
        hide: function() {
            // Make sure there isn't an timeout running
            window.clearTimeout( timeout );

            // Put the hiding in a timeout, so it can be stopped when a user
            // hovers the indication
            timeout = window.setTimeout(function(){
                // Simple hiding
                el.hide();

                // Reset currentId
                currentId = undefined;
            }, 500);
        },
        // Stop the timeout, used to stop hiding the indication
        stop: function() {
            window.clearTimeout(timeout);
        },
        // Set the element object when it's set.
        // Typically this will only be called from the initial ajax-call made
        // in init.js
        setElement: function( newEl ) {
            var self = this;

            el = newEl;

            el  .bind('mouseenter', function() {
                    self.stop();
                })
                .bind('mouseleave', function() {
                    self.hide();
                })
                .bind('click', function() {
                    self.hide();
                    $( 'span.factlink[data-factid=' + currentId + ']').click();
                });
        },
        // Set the opinions
        setOpinions: function(believe, doubt, disbelieve) {
            el.find('li.fl-bar-proves').height( ( believe.percentage / 100 ) * 45);
            el.find('li.fl-bar-proves>div').width( believe.authority * 15);
            el.find('li.fl-bar-maybe').height( ( doubt.percentage / 100 ) * 45);
            el.find('li.fl-bar-maybe>div').width( doubt.authority * 15);
            el.find('li.fl-bar-denies').height( ( disbelieve.percentage / 100 ) * 45);
            el.find('li.fl-bar-denies>div').width( disbelieve.authority * 15);
        }
    };
})();

// Make sure the hover on an element works on all the paired span elements
$( 'span.factlink' ).live( 'mouseenter', function( e ) {
    var fctID = $( this ).attr( 'data-factid' );

    $( '[data-factid=' + fctID + ']' )
        .addClass('fl-active');

    // Show the Factlink indication
    Factlink.Indicator.setOpinions(
        {
            percentage: $( this ).attr('data-fact-believe-percentage'),
            authority: $( this ).attr('data-fact-believe-authority')
        },
        {
            percentage: $( this ).attr('data-fact-doubt-percentage'),
            authority: $( this ).attr('data-fact-doubt-authority')
        },
        {
            percentage: $( this ).attr('data-fact-disbelieve-percentage'),
            authority: $( this ).attr('data-fact-disbelieve-authority')
        });
    Factlink.Indicator.showFor(fctID, e.pageX - 10, $(e.target).offset().top + 10 );
})
.live('mouseleave', function() {
    $( '[data-factid=' + $( this ).attr( 'data-factid' ) + ']' )
        .removeClass('fl-active');

    // Hide the indication element
    Factlink.Indicator.hide();
});
})( window.Factlink );<commit_msg>Changed the hover of an indication so that the Factlink stays highlighted<commit_after>(function( Factlink ) {

Factlink.showInfo = function( el ) {
    Factlink.remote.showFactlink( el.getAttribute("data-factid") );
    Factlink.modal.showFrame.method();
    Factlink.modal.showOverlay.method();
};

// Handle a user click
$( 'span.factlink' ).live('click', function() {
    Factlink.showInfo( this );
});

// Object which holds the methods that can be called from the intermediate iframe
// These methods are also used by the internal scripts and can be called through
// Factlink.modal.FUNCTION.method() because easyXDM changes the object structure
Factlink.modal = {
    positionFrame: function( top, left ) {
        Factlink.$frame.css({
            top: top,
            left: left
        });
    },
    resetStyle: function() {
        Factlink.$frame.attr('style','');
    },
    setFrameBounds: function( width, height ) {
        var $frame = Factlink.$frame;

        $frame.css({
            height: height,
            width: width
        });

        if ( $frame.hasClass("show") ) {
            $frame.css({
                margin: "-" + height / 2 + "px 0 0 -" + width / 2 + "px"
            });
        }
    },
    hideFrame: function() {
        unbindClick();
        Factlink.$frame.hide();
    },
    showFrame: function() {
        bindClick();
        Factlink.$frame.show();
    },
    setFrameType: function( type ) {
        Factlink.$frame
            .attr('class', type)
            .show();
    },
    showOverlay: function() {
        Factlink.overlay.show();
    },
    hideOverlay: function() {
        Factlink.overlay.hide();
    },
    highlightNewFactlink: function( fact, id ) {
        Factlink.selectRanges( Factlink.search(fact), id );
    }
};

var bindClick = function() {
        $( document ).bind('click', clickHandler);
    },
    unbindClick = function() {
        $( document ).unbind('click', clickHandler)
    },
    clickHandler = function() {
        Factlink.modal.hideOverlay.method();
        Factlink.modal.hideFrame.method();
    };

// INDICATOR

// Indicator object which will manage the indicator which shows some basic info
// of each Factlink
Factlink.Indicator = (function() {
    // By default the element object is undefined
    var el,
        // Is the indicator currently visible?
        visible = false,
        // This object will store the timeout id
        timeout,
        // Current shown Factlink
        currentId,
        // Position of the indication
        x, y;

    return {
        // Makes the indicator show for the Factlink with id ID
        showFor: function( id, mouseX, mouseY ) {
            // Get the Factlink-object
            var fl = $( 'span.factlink[data-factid=' + id + ']');

            if ( id !== currentId ) {
                x = mouseX + 10,
                y = mouseY - el.outerHeight(true) - 10;
            }

            window.clearTimeout( timeout );

            // Store the currentId;
            currentId = id;

            timeout = window.setTimeout(function(){
                if ( el === undefined )
                    return;

                el
                    .css({
                        top: y,
                        left: x
                    })
                    .show();
            }, 10);
        },
        // Makes the indicator hide itself
        hide: function() {
            // Make sure there isn't an timeout running
            window.clearTimeout( timeout );

            // Put the hiding in a timeout, so it can be stopped when a user
            // hovers the indication
            timeout = window.setTimeout(function(){
                // Simple hiding
                el.hide();

                // Reset currentId
                currentId = undefined;
            }, 500);
        },
        // Stop the timeout, used to stop hiding the indication
        stop: function() {
            window.clearTimeout(timeout);
        },
        // Set the element object when it's set.
        // Typically this will only be called from the initial ajax-call made
        // in init.js
        setElement: function( newEl ) {
            var self = this;

            el = newEl;

            el  .bind('mouseenter', function() {
                    self.stop();

                    // Keep the Factlink highlighted
                    $( '[data-factid=' + currentId + ']' )
                        .addClass('fl-active');
                })
                .bind('mouseleave', function() {
                    self.hide();

                    // Stop hightlighting the Faclink
                    $( '[data-factid=' + currentId + ']' )
                        .removeClass('fl-active');
                })
                .bind('click', function() {
                    self.hide();
                    $( 'span.factlink[data-factid=' + currentId + ']').click();
                });
        },
        // Set the opinions
        setOpinions: function(believe, doubt, disbelieve) {
            el.find('li.fl-bar-proves').height( ( believe.percentage / 100 ) * 45);
            el.find('li.fl-bar-proves>div').width( believe.authority * 15);
            el.find('li.fl-bar-maybe').height( ( doubt.percentage / 100 ) * 45);
            el.find('li.fl-bar-maybe>div').width( doubt.authority * 15);
            el.find('li.fl-bar-denies').height( ( disbelieve.percentage / 100 ) * 45);
            el.find('li.fl-bar-denies>div').width( disbelieve.authority * 15);
        }
    };
})();

// Make sure the hover on an element works on all the paired span elements
$( 'span.factlink' ).live( 'mouseenter', function( e ) {
    var fctID = $( this ).attr( 'data-factid' );

    $( '[data-factid=' + fctID + ']' )
        .addClass('fl-active');

    // Show the Factlink indication
    Factlink.Indicator.setOpinions(
        {
            percentage: $( this ).attr('data-fact-believe-percentage'),
            authority: $( this ).attr('data-fact-believe-authority')
        },
        {
            percentage: $( this ).attr('data-fact-doubt-percentage'),
            authority: $( this ).attr('data-fact-doubt-authority')
        },
        {
            percentage: $( this ).attr('data-fact-disbelieve-percentage'),
            authority: $( this ).attr('data-fact-disbelieve-authority')
        });
    Factlink.Indicator.showFor(fctID, e.pageX - 10, $(e.target).offset().top + 10 );
})
.live('mouseleave', function() {
    $( '[data-factid=' + $( this ).attr( 'data-factid' ) + ']' )
        .removeClass('fl-active');

    // Hide the indication element
    Factlink.Indicator.hide();
});
})( window.Factlink );<|endoftext|>


<commit_before>/*
 * Interactions in the Game are governed by Cards and their managers: Prompt, Response, and Feedback objects.
 *
 */

/* FAILSAFE */
Game = Game || function () {};

/*
 * Cards
 * Cards represent interactions with the player. They are represented by some DOM element(s).
 * The generic Card prototype specifies a generic 'deal' function,
 * but that can be overridden by 'deal' function passed in a card spec.
 * Alternately, other Card prototypes can be defined on the Game object,
 * specifying animations, interactivity, even peer-to-peer communications through "cards."
 */
Game.Card = function(spec) {
	if (spec === null) {
		return; // this is when we are creating a Card to be a prototype for another type of object.
	} else if (spec instanceof String) {
		spec = spec.toString();
	}

	// some card-related constants.
	Game.Card.SEND_TO_BACK = -1;

  // save any custom style passed in.
  var css_class;
  if (spec.hasOwnProperty("css_class")) {
    css_class = spec.css_class;
    delete spec.css_class
  }

  // handle ref's to our media_url.
  spec = Util.replaceAll(spec, /MEDIA_URL\+/g, MEDIA_URL);

	// save the spec, in case we need to manipulate the card contents later on.
	this.spec = spec;

	// make space to save any dealer I'm associated with.
	this.dealer = {};

	// we want to always have a single HTML element to represent each Card.
	if ( ((spec instanceof HTMLElement) || (spec instanceof jQuery))
		&& ($(spec).attr("data-keep-in-dom") === "true")) {
		this.element = $(spec);
	} else {
		// remove 'type' from spec
		var card_type = spec.type || "";
		delete spec.type

		in_production_try(this, function () {
			var card_scaffold = $(document.createElement("div"));
            if (spec instanceof String) {
                spec = spec.toString()
            }
			var rendered_element = card_scaffold.render(spec.content || spec);
			this.load_promise = rendered_element.data().promise;

			// we want to always have a single HTML element to represent each Card.
			// so if the spec has generated siblings, we wrap them in a div.
			var nodes_in_card = card_scaffold.get(0).childNodes;
			switch (nodes_in_card.length) {
				case 0:
					throw new Error("Failed to create Card.");
					break;

				case 1:
					// if it is a text node, use card_scaffold as the Card element.
					// otherwise, use the child node.
					var node = nodes_in_card[0];
					this.element = (node.nodeType == 3) ? card_scaffold : $(node);
					break;

				default:
					this.element = card_scaffold;
					break;
			}
		});
	}

	// add the generic card class.
	// keep track of this Card via the jQuery data for the element.
	// this will work, even if we use another jQuery selector to select this one element.
	this.element.addClass("card").data("card", this);
	if (card_type) {
		this.element.addClass(card_type);
	}

	// add any other saved css_classes.
	if (css_class || false) {
		this.element.addClass(css_class);
	}

	// respond to user and game actions and track what will get reported to the db.
	this.history = [];

	// will have to list out all types of Card events.
	var _this = this;
	this.element.on("Card.userInput", function (evt, data) {
		if (_this.element.is(this)) {
			var answer;
			try {
				data = data.answer;
			} catch (e) {
				data = JSON.stringify(data);
			}
			_this.history.push({ event: evt.namespace, data: data, timestamp: evt.timeStamp });
		}
	});
}

// default values for cards.
Game.Card.DEFAULTS = {
	timeout: null
};

Game.Card.prototype.style = function (css_classes) {
	// remove card class and then add back those specified.
	// this is done so we can keep cards out the 'clearCards' function.
	// TODO: *** Look into a better way to do this. cards should remain '.card's ***
	this.element.removeClass("card").addClass(css_classes);
	return this; // for daisy-chaining.
}

Game.Card.prototype.find = function (selector) {
	// just pass to element.
	return this.element.find(selector);
}

// default way to activate/deactivate card is to set disabled attr on any input(s) and/or link(s) in the card.
// we also set disabled on the card, in case it IS the interactive element, or if we want to do css on the card.
Game.Card.prototype.setActive = function (flag) {
	$(this.element).find("input, a").addBack().prop( "disabled", !flag );
}

Game.Card.prototype.dealTo = function (container) {
	// find or create a place in the game in which to put the cards.
	var container_spec = container || this.spec.container || this.dealer.container;
	this.container = $(container_spec);
	if (this.container.length == 0) {
		this.container = $("#game");
	}
	$(this.container).append(this.element);
}

Game.Card.prototype.unbindEvents = function (in_event_names) {
	// remove passed-in (or any) events bound to the card element, or any nested input or link elements.
	var interactive_elements = this.element.find("input, a").addBack();
	$(interactive_elements).each(function () {
		var event_names = in_event_names || ( Object.keys($._data(this, "events") || {}).join(" ") );
		$(this).off(event_names);
	});
}

Game.Card.prototype.remove = function () {
	this.unbindEvents();
	this.element.remove();
}

// what I tell the Reporter about myself.
Game.Card.prototype.getHistory = function () {
	return this.history;
}

// return a descriptor string from the spec or create a jQuery descriptor for my element.
Game.Card.prototype.getDescriptor = function () {
	if (typeof this.spec === "string") {
		return this.spec;
	} else {
		return Util.createDescriptor(this.element.get(0));
	}
}

// a create method for basic Card types (as opposed to those controlled by Dealers).
Game.Card.create = function (spec) {
	var card_class = spec["type"] || "Card";
	var card;
	if (card_class === "Card"){
		card = new Game.Card(spec);
	} else {
		card = new Game.Card[card_class](spec);
	}
	return card;
}

/*
 * Game.Card.Modal
 * Cards which 'stop the action' & require a user response.
 */
Game.Card.Modal = Util.extendClass(Game.Card, function (spec) {
  Game.Card.call(this, spec);
	// add the bit where we wait for the user.
	this.user_input_dfd = $.Deferred();
	this.user_input_promise = this.user_input_dfd.promise();
},
{
  dealTo: function (container) {
  	Game.Card.prototype.dealTo.call(this, container);
  	this.addOKButton();
  	return true;
  },

  addOKButton: function () {
  	// once the user clicks to continue, we can move onto the game.
  	// for now, we"re going to stick to the notion that all intros require a click to continue.
  	if (this.element.find("button.continue").length > 0) {
  		return;
  	}
  	var _this = this;
  	var ok_button = $(document.createElement("button"))
  										.attr("href", "#")
  										.addClass("continue")
  										.html("Continue").click(function () {
  		_this.user_input_dfd.resolve();
  		_this.remove();
  	});
  	ok_button.appendTo(this.element);
  }
});<commit_msg>make Card.js agree w format of other objects.<commit_after>/*
 * Interactions in the Game are governed by Cards and their managers: Prompt, Response, and Feedback objects.
 *
 */

/* FAILSAFE */
Game = Game || function () {};

/*
 * Cards
 * Cards represent interactions with the player. They are represented by some DOM element(s).
 * The generic Card prototype specifies a generic 'deal' function,
 * but that can be overridden by 'deal' function passed in a card spec.
 * Alternately, other Card prototypes can be defined on the Game object,
 * specifying animations, interactivity, even peer-to-peer communications through "cards."
 */
Game.Card = function(spec) {
	if (spec === null) {
		return; // this is when we are creating a Card to be a prototype for another type of object.
	} else if (spec instanceof String) {
		spec = spec.toString();
	}

	// some card-related constants.
	Game.Card.SEND_TO_BACK = -1;

  // save any custom style passed in.
  var css_class;
  if (spec.hasOwnProperty("css_class")) {
    css_class = spec.css_class;
    delete spec.css_class
  }

  // handle ref's to our media_url.
  spec = Util.replaceAll(spec, /MEDIA_URL\+/g, MEDIA_URL);

	// save the spec, in case we need to manipulate the card contents later on.
	this.spec = spec;

	// make space to save any dealer I'm associated with.
	this.dealer = {};

	// we want to always have a single HTML element to represent each Card.
	if ( ((spec instanceof HTMLElement) || (spec instanceof jQuery))
		&& ($(spec).attr("data-keep-in-dom") === "true")) {
		this.element = $(spec);
	} else {
		// remove 'type' from spec
		var card_type = spec.type || "";
		delete spec.type

		in_production_try(this, function () {
			var card_scaffold = $(document.createElement("div"));
            if (spec instanceof String) {
                spec = spec.toString()
            }
			var rendered_element = card_scaffold.render(spec.content || spec);
			this.load_promise = rendered_element.data().promise;

			// we want to always have a single HTML element to represent each Card.
			// so if the spec has generated siblings, we wrap them in a div.
			var nodes_in_card = card_scaffold.get(0).childNodes;
			switch (nodes_in_card.length) {
				case 0:
					throw new Error("Failed to create Card.");
					break;

				case 1:
					// if it is a text node, use card_scaffold as the Card element.
					// otherwise, use the child node.
					var node = nodes_in_card[0];
					this.element = (node.nodeType == 3) ? card_scaffold : $(node);
					break;

				default:
					this.element = card_scaffold;
					break;
			}
		});
	}

	// add the generic card class.
	// keep track of this Card via the jQuery data for the element.
	// this will work, even if we use another jQuery selector to select this one element.
	this.element.addClass("card").data("card", this);
	if (card_type) {
		this.element.addClass(card_type);
	}

	// add any other saved css_classes.
	if (css_class || false) {
		this.element.addClass(css_class);
	}

	// respond to user and game actions and track what will get reported to the db.
	this.history = [];

	// will have to list out all types of Card events.
	var _this = this;
	this.element.on("Card.userInput", function (evt, data) {
		if (_this.element.is(this)) {
			var answer;
			try {
				data = data.answer;
			} catch (e) {
				data = JSON.stringify(data);
			}
			_this.history.push({ event: evt.namespace, data: data, timestamp: evt.timeStamp });
		}
	});
}

// default values for cards.
Game.Card.DEFAULTS = {
	timeout: null
};

Game.Card.prototype = {

  style: function (css_classes) {
  	// remove card class and then add back those specified.
  	// this is done so we can keep cards out the 'clearCards' function.
  	// TODO: *** Look into a better way to do this. cards should remain '.card's ***
  	this.element.removeClass("card").addClass(css_classes);
  	return this; // for daisy-chaining.
  },

  find: function (selector) {
  	// just pass to element.
  	return this.element.find(selector);
  },

  // default way to activate/deactivate card is to set disabled attr on any input(s) and/or link(s) in the card.
  // we also set disabled on the card, in case it IS the interactive element, or if we want to do css on the card.
  setActive: function (flag) {
  	$(this.element).find("input, a").addBack().prop( "disabled", !flag );
  },

  dealTo: function (container) {
  	// find or create a place in the game in which to put the cards.
  	var container_spec = container || this.spec.container || this.dealer.container;
  	this.container = $(container_spec);
  	if (this.container.length == 0) {
  		this.container = $("#game");
  	}
  	$(this.container).append(this.element);
  },

  unbindEvents: function (in_event_names) {
  	// remove passed-in (or any) events bound to the card element, or any nested input or link elements.
  	var interactive_elements = this.element.find("input, a").addBack();
  	$(interactive_elements).each(function () {
  		var event_names = in_event_names || ( Object.keys($._data(this, "events") || {}).join(" ") );
  		$(this).off(event_names);
  	});
  },

  remove: function () {
  	this.unbindEvents();
  	this.element.remove();
  },

  // what I tell the Reporter about myself.
  getHistory: function () {
  	return this.history;
  },

  // return a descriptor string from the spec or create a jQuery descriptor for my element.
  getDescriptor: function () {
  	if (typeof this.spec === "string") {
  		return this.spec;
  	} else {
  		return Util.createDescriptor(this.element.get(0));
  	}
  }
}

// a create method for basic Card types (as opposed to those controlled by Dealers).
Game.Card.create = function (spec) {
	var card_class = spec["type"] || "Card";
	var card;
	if (card_class === "Card"){
		card = new Game.Card(spec);
	} else {
		card = new Game.Card[card_class](spec);
	}
	return card;
}

/*
 * Game.Card.Modal
 * Cards which 'stop the action' & require a user response.
 */
Game.Card.Modal = Util.extendClass(Game.Card, function (spec) {
  Game.Card.call(this, spec);
	// add the bit where we wait for the user.
	this.user_input_dfd = $.Deferred();
	this.user_input_promise = this.user_input_dfd.promise();
},
{
  dealTo: function (container) {
  	Game.Card.prototype.dealTo.call(this, container);
  	this.addOKButton();
  	return true;
  },

  addOKButton: function () {
  	// once the user clicks to continue, we can move onto the game.
  	// for now, we"re going to stick to the notion that all intros require a click to continue.
  	if (this.element.find("button.continue").length > 0) {
  		return;
  	}
  	var _this = this;
  	var ok_button = $(document.createElement("button"))
  										.attr("href", "#")
  										.addClass("continue")
  										.html("Continue").click(function () {
  		_this.user_input_dfd.resolve();
  		_this.remove();
  	});
  	ok_button.appendTo(this.element);
  }
});<|endoftext|>


<commit_before>'use strict';

$(() => {

    const socket = io.connect('http://localhost:3005');
    $.ajax({
        url: 'http://localhost:3005/user',
        dataType: 'json',
        success: (res) => {
            result(res);
        },
        error: (err) => {
            error(err);
        },
        type: 'GET',
    });

    const me = {};
    const you = {};
    you.avatar = '../pictures/img/default-user.png';

    function result(user) {
        me.avatar = '/static/pictures/img/' + user.avatar;
        me.fromUserId = user.id;
        me.toUserId = user.id;
    }

    $(".message-text").on("keyup", (e) => {
        debugger;
        const $input = $(".message-text");
        if (e.which === 13) {
            let $text = $input.val();
            if ($text !== "") {
                me.message = $text;
                socket.emit('add-message', me);
                insertChat("me", $text);
                $input.val('');
            }
        }
    });
    // result();

    function formatAMPM(date) {
        let hours = date.getHours();
        let minutes = date.getMinutes();
        let ampm = hours >= 12 ? 'PM' : 'AM';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0' + minutes : minutes;
        let strTime = hours + ':' + minutes + ' ' + ampm;

        return strTime;
    }

    //-- No use time. It is a javaScript effect.
    function insertChat(who, text, time = 0) {
        let control = "";
        let date = formatAMPM(new Date());

        if (who == "me") {

            control = '
' +
                '
' +
                '

' +
                '
' +
                '
' + text + '
' +
                '
' + date + '
' +
                '
' +
                '
' +
                '
';
        } else {
            control = '
' +
                '
' +
                '
' +
                '
' + text + '
' +
                '
' + date + '
' +
                '
' +
                '

' +
                '
';
        }
        setTimeout(
            function() {
                debugger;
                $("ul.list-messages").append(control);
            }, time);

    }

    function resetChat() {
        $("ul").empty();
    }

    //-- Clear Chat
    // resetChat();

    // //-- Print Messages
    // insertChat("me", "Hello Tom...", 0);
    // insertChat("you", "Hi, Pablo", 1500);

});
<commit_msg>Fix chat request<commit_after>'use strict';

$(() => {

    const socket = io.connect('http://localhost:3005');
    $.ajax({
        url: 'http://localhost:3005/user',
        dataType: 'json',
        success: (res) => {
            console.log(res.user);
            result(res.user);
        },
        error: (err) => {
            error(err);
        },
        type: 'GET',
    });

    const me = {};
    const you = {};
    you.avatar = '../pictures/img/default-user.png';

    function result(user) {
        me.avatar = '/static/pictures/img/' + user.avatar;
        me.fromUserId = user.id;
        me.toUserId = user.id;
    }

    $(".message-text").on("keyup", (e) => {
        const $input = $(".message-text");
        if (e.which === 13) {
            let $text = $input.val();
            if ($text !== "") {
                me.message = $text;
                socket.emit('add-message', me);
                insertChat("me", $text);
                $input.val('');
            }
        }
    });
    // result();

    function formatAMPM(date) {
        let hours = date.getHours();
        let minutes = date.getMinutes();
        let ampm = hours >= 12 ? 'PM' : 'AM';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0' + minutes : minutes;
        let strTime = hours + ':' + minutes + ' ' + ampm;

        return strTime;
    }

    //-- No use time. It is a javaScript effect.
    function insertChat(who, text, time = 0) {
        let control = "";
        let date = formatAMPM(new Date());

        if (who == "me") {

            control = '
' +
                '
' +
                '

' +
                '
' +
                '
' + text + '
' +
                '
' + date + '
' +
                '
' +
                '
' +
                '
';
        } else {
            control = '
' +
                '
' +
                '
' +
                '
' + text + '
' +
                '
' + date + '
' +
                '
' +
                '

' +
                '
';
        }
        setTimeout(
            function() {
                $("ul.list-messages").append(control);
            }, time);

    }

    function resetChat() {
        $("ul").empty();
    }

    //-- Clear Chat
    // resetChat();

    // //-- Print Messages
    // insertChat("me", "Hello Tom...", 0);
    // insertChat("you", "Hi, Pablo", 1500);

});
<|endoftext|>


<commit_before>"use strict";

System.register("flagrow/upload/addUploadPane", ["flarum/extend", "flarum/components/AdminNav", "flarum/components/AdminLinkButton", "flagrow/upload/components/UploadPage"], function (_export, _context) {
    "use strict";

    var extend, AdminNav, AdminLinkButton, UploadPage;

    _export("default", function () {
        // create the route
        app.routes['flagrow-upload'] = {path: '/flagrow/upload', component: UploadPage.component()};

        // bind the route we created to the three dots settings button
        app.extensionSettings['flagrow-upload'] = function () {
            return m.route(app.route('flagrow-upload'));
        };

        extend(AdminNav.prototype, 'items', function (items) {
            // add the Image Upload tab to the admin navigation menu
            items.add('flagrow-upload', AdminLinkButton.component({
                href: app.route('flagrow-upload'),
                icon: 'file-o',
                children: 'File Upload',
                description: app.translator.trans('flagrow-upload.admin.help_texts.description')
            }));
        });
    });

    return {
        setters: [function (_flarumExtend) {
            extend = _flarumExtend.extend;
        }, function (_flarumComponentsAdminNav) {
            AdminNav = _flarumComponentsAdminNav.default;
        }, function (_flarumComponentsAdminLinkButton) {
            AdminLinkButton = _flarumComponentsAdminLinkButton.default;
        }, function (_flagrowUploadComponentsUploadPage) {
            UploadPage = _flagrowUploadComponentsUploadPage.default;
        }],
        execute: function () {
        }
    };
});
;
"use strict";

System.register("flagrow/upload/components/UploadPage", ["flarum/Component", "flarum/components/Button", "flarum/utils/saveSettings", "flarum/components/Alert", "flarum/components/FieldSet", "flarum/components/Select", "flarum/components/Switch"], function (_export, _context) {
    "use strict";

    var Component, Button, saveSettings, Alert, FieldSet, Select, Switch, UploadPage;
    return {
        setters: [function (_flarumComponent) {
            Component = _flarumComponent.default;
        }, function (_flarumComponentsButton) {
            Button = _flarumComponentsButton.default;
        }, function (_flarumUtilsSaveSettings) {
            saveSettings = _flarumUtilsSaveSettings.default;
        }, function (_flarumComponentsAlert) {
            Alert = _flarumComponentsAlert.default;
        }, function (_flarumComponentsFieldSet) {
            FieldSet = _flarumComponentsFieldSet.default;
        }, function (_flarumComponentsSelect) {
            Select = _flarumComponentsSelect.default;
        }, function (_flarumComponentsSwitch) {
            Switch = _flarumComponentsSwitch.default;
        }],
        execute: function () {
            UploadPage = function (_Component) {
                babelHelpers.inherits(UploadPage, _Component);

                function UploadPage() {
                    babelHelpers.classCallCheck(this, UploadPage);
                    return babelHelpers.possibleConstructorReturn(this, (UploadPage.__proto__ || Object.getPrototypeOf(UploadPage)).apply(this, arguments));
                }

                babelHelpers.createClass(UploadPage, [{
                    key: "init",
                    value: function init() {
                        var _this2 = this;

                        // whether we are saving the settings or not right now
                        this.loading = false;

                        // the fields we need to watch and to save
                        this.fields = ['availableUploadMethods', 'uploadMethod', 'resizeMaxWidth', 'resizeMaxHeight', 'cdnUrl', 'maxFileSize'];

                        // the checkboxes we need to watch and to save.
                        this.checkboxes = ['mustResize'];

                        // options for the dropdown menu
                        this.uploadMethodOptions = {};

                        this.values = {};

                        // our package prefix (to be added to every field and checkbox in the setting table)
                        this.settingsPrefix = 'flagrow.upload';

                        // get the saved settings from the database
                        var settings = app.data.settings;

                        // set the upload methods
                        this.uploadMethodOptions = settings[this.addPrefix('availableUploadMethods')];
                        // bind the values of the fields and checkboxes to the getter/setter functions
                        this.fields.forEach(function (key) {
                            return _this2.values[key] = m.prop(settings[_this2.addPrefix(key)]);
                        });
                        this.checkboxes.forEach(function (key) {
                            return _this2.values[key] = m.prop(settings[_this2.addPrefix(key)] === '1');
                        });
                    }
                }, {
                    key: "view",
                    value: function view() {
                        return [m('div', {className: 'ImageUploadPage'}, [m('div', {className: 'container'}, [m('form', {onsubmit: this.onsubmit.bind(this)}, [FieldSet.component({
                            label: app.translator.trans('flagrow.upload.admin.labels.upload_method'),
                            children: [m('div', {className: 'helpText'}, app.translator.trans('flagrow.upload.admin.help_texts.upload_method')), Select.component({
                                options: this.uploadMethodOptions,
                                onchange: this.values.uploadMethod,
                                value: this.values.uploadMethod() || 'local'
                            })]
                        }), m('div', {className: 'ImageUploadPage-preferences'}, [FieldSet.component({
                            label: app.translator.trans('flagrow.upload.admin.labels.preferences.title'),
                            children: [m('label', {}, app.translator.trans('flagrow.upload.admin.labels.preferences.max_file_size')), m('input', {
                                className: 'FormControl',
                                value: this.values.maxFileSize() || 2048,
                                oninput: m.withAttr('value', this.values.maxFileSize)
                            })]
                        })]), m('div', {className: 'ImageUploadPage-resize'}, [FieldSet.component({
                            label: app.translator.trans('flagrow.upload.admin.labels.resize.title'),
                            children: [m('div', {className: 'helpText'}, app.translator.trans('flagrow.upload.admin.help_texts.resize')), Switch.component({
                                state: this.values.mustResize() || false,
                                children: app.translator.trans('flagrow.upload.admin.labels.resize.toggle'),
                                onchange: this.values.mustResize
                            }), m('label', {}, app.translator.trans('flagrow.upload.admin.labels.resize.max_width')), m('input', {
                                className: 'FormControl',
                                value: this.values.resizeMaxWidth() || 100,
                                oninput: m.withAttr('value', this.values.resizeMaxWidth),
                                disabled: !this.values.mustResize()
                            }), m('label', {}, app.translator.trans('flagrow.upload.admin.labels.resize.max_height')), m('input', {
                                className: 'FormControl',
                                value: this.values.resizeMaxHeight() || 100,
                                oninput: m.withAttr('value', this.values.resizeMaxHeight),
                                disabled: !this.values.mustResize()
                            })]
                        })]), m('div', {
                            className: 'ImageUploadPage-local',
                            style: {display: this.values.uploadMethod() === 'local' ? "block" : "none"}
                        }, [FieldSet.component({
                            label: app.translator.trans('flagrow.upload.admin.labels.local.title'),
                            children: [m('label', {}, app.translator.trans('flagrow.upload.admin.labels.local.cdn_url')), m('input', {
                                className: 'FormControl',
                                value: this.values.cdnUrl() || '',
                                oninput: m.withAttr('value', this.values.cdnUrl)
                            })]
                        })]), Button.component({
                            type: 'submit',
                            className: 'Button Button--primary',
                            children: app.translator.trans('flagrow.upload.admin.buttons.save'),
                            loading: this.loading,
                            disabled: !this.changed()
                        })])])])];
                    }
                }, {
                    key: "changed",
                    value: function changed() {
                        var _this3 = this;

                        var fieldsCheck = this.fields.some(function (key) {
                            return _this3.values[key]() !== app.data.settings[_this3.addPrefix(key)];
                        });
                        var checkboxesCheck = this.checkboxes.some(function (key) {
                            return _this3.values[key]() !== (app.data.settings[_this3.addPrefix(key)] == '1');
                        });
                        return fieldsCheck || checkboxesCheck;
                    }
                }, {
                    key: "onsubmit",
                    value: function onsubmit(e) {
                        var _this4 = this;

                        // prevent the usual form submit behaviour
                        e.preventDefault();

                        // if the page is already saving, do nothing
                        if (this.loading) return;

                        // prevents multiple savings
                        this.loading = true;
                        app.alerts.dismiss(this.successAlert);

                        var settings = {};

                        // gets all the values from the form
                        this.fields.forEach(function (key) {
                            return settings[_this4.addPrefix(key)] = _this4.values[key]();
                        });
                        this.checkboxes.forEach(function (key) {
                            return settings[_this4.addPrefix(key)] = _this4.values[key]();
                        });

                        // actually saves everything in the database
                        saveSettings(settings).then(function () {
                            // on succes, show an alert
                            app.alerts.show(_this4.successAlert = new Alert({
                                type: 'success',
                                children: app.translator.trans('core.admin.basics.saved_message')
                            }));
                        }).catch(function () {
                        }).then(function () {
                            // return to the initial state and redraw the page
                            _this4.loading = false;
                            m.redraw();
                        });
                    }
                }, {
                    key: "addPrefix",
                    value: function addPrefix(key) {
                        return this.settingsPrefix + '.' + key;
                    }
                }]);
                return UploadPage;
            }(Component);

            _export("default", UploadPage);
        }
    };
});
;
"use strict";

System.register("flagrow/upload/main", ["flarum/extend", "flarum/app", "flarum/components/PermissionGrid", "flagrow/upload/addUploadPane"], function (_export, _context) {
    "use strict";

    var extend, app, PermissionGrid, addUploadPane;
    return {
        setters: [function (_flarumExtend) {
            extend = _flarumExtend.extend;
        }, function (_flarumApp) {
            app = _flarumApp.default;
        }, function (_flarumComponentsPermissionGrid) {
            PermissionGrid = _flarumComponentsPermissionGrid.default;
        }, function (_flagrowUploadAddUploadPane) {
            addUploadPane = _flagrowUploadAddUploadPane.default;
        }],
        execute: function () {

            app.initializers.add('flagrow-upload', function (app) {
                // add the admin pane
                addUploadPane();

                // add the permission option to the relative pane
                extend(PermissionGrid.prototype, 'startItems', function (items) {
                    items.add('upload', {
                        icon: 'file-o',
                        label: app.translator.trans('flagrow-upload.admin.permissions.upload_images_label'),
                        permission: 'flagrow.upload'
                    });
                });
            });
        }
    };
});<commit_msg>compiled ext due to label trans<commit_after>"use strict";

System.register("flagrow/upload/addUploadPane", ["flarum/extend", "flarum/components/AdminNav", "flarum/components/AdminLinkButton", "flagrow/upload/components/UploadPage"], function (_export, _context) {
    "use strict";

    var extend, AdminNav, AdminLinkButton, UploadPage;

    _export("default", function () {
        // create the route
        app.routes['flagrow-upload'] = {path: '/flagrow/upload', component: UploadPage.component()};

        // bind the route we created to the three dots settings button
        app.extensionSettings['flagrow-upload'] = function () {
            return m.route(app.route('flagrow-upload'));
        };

        extend(AdminNav.prototype, 'items', function (items) {
            // add the Image Upload tab to the admin navigation menu
            items.add('flagrow-upload', AdminLinkButton.component({
                href: app.route('flagrow-upload'),
                icon: 'file-o',
                children: 'File Upload',
                description: app.translator.trans('flagrow-upload.admin.help_texts.description')
            }));
        });
    });

    return {
        setters: [function (_flarumExtend) {
            extend = _flarumExtend.extend;
        }, function (_flarumComponentsAdminNav) {
            AdminNav = _flarumComponentsAdminNav.default;
        }, function (_flarumComponentsAdminLinkButton) {
            AdminLinkButton = _flarumComponentsAdminLinkButton.default;
        }, function (_flagrowUploadComponentsUploadPage) {
            UploadPage = _flagrowUploadComponentsUploadPage.default;
        }],
        execute: function () {
        }
    };
});
;
"use strict";

System.register("flagrow/upload/components/UploadPage", ["flarum/Component", "flarum/components/Button", "flarum/utils/saveSettings", "flarum/components/Alert", "flarum/components/FieldSet", "flarum/components/Select", "flarum/components/Switch"], function (_export, _context) {
    "use strict";

    var Component, Button, saveSettings, Alert, FieldSet, Select, Switch, UploadPage;
    return {
        setters: [function (_flarumComponent) {
            Component = _flarumComponent.default;
        }, function (_flarumComponentsButton) {
            Button = _flarumComponentsButton.default;
        }, function (_flarumUtilsSaveSettings) {
            saveSettings = _flarumUtilsSaveSettings.default;
        }, function (_flarumComponentsAlert) {
            Alert = _flarumComponentsAlert.default;
        }, function (_flarumComponentsFieldSet) {
            FieldSet = _flarumComponentsFieldSet.default;
        }, function (_flarumComponentsSelect) {
            Select = _flarumComponentsSelect.default;
        }, function (_flarumComponentsSwitch) {
            Switch = _flarumComponentsSwitch.default;
        }],
        execute: function () {
            UploadPage = function (_Component) {
                babelHelpers.inherits(UploadPage, _Component);

                function UploadPage() {
                    babelHelpers.classCallCheck(this, UploadPage);
                    return babelHelpers.possibleConstructorReturn(this, (UploadPage.__proto__ || Object.getPrototypeOf(UploadPage)).apply(this, arguments));
                }

                babelHelpers.createClass(UploadPage, [{
                    key: "init",
                    value: function init() {
                        var _this2 = this;

                        // whether we are saving the settings or not right now
                        this.loading = false;

                        // the fields we need to watch and to save
                        this.fields = ['availableUploadMethods', 'uploadMethod', 'resizeMaxWidth', 'resizeMaxHeight', 'cdnUrl', 'maxFileSize'];

                        // the checkboxes we need to watch and to save.
                        this.checkboxes = ['mustResize'];

                        // options for the dropdown menu
                        this.uploadMethodOptions = {};

                        this.values = {};

                        // our package prefix (to be added to every field and checkbox in the setting table)
                        this.settingsPrefix = 'flagrow.upload';

                        // get the saved settings from the database
                        var settings = app.data.settings;

                        // set the upload methods
                        this.uploadMethodOptions = settings[this.addPrefix('availableUploadMethods')];
                        // bind the values of the fields and checkboxes to the getter/setter functions
                        this.fields.forEach(function (key) {
                            return _this2.values[key] = m.prop(settings[_this2.addPrefix(key)]);
                        });
                        this.checkboxes.forEach(function (key) {
                            return _this2.values[key] = m.prop(settings[_this2.addPrefix(key)] === '1');
                        });
                    }
                }, {
                    key: "view",
                    value: function view() {
                        return [m('div', {className: 'ImageUploadPage'}, [m('div', {className: 'container'}, [m('form', {onsubmit: this.onsubmit.bind(this)}, [FieldSet.component({
                            label: app.translator.trans('flagrow-upload.admin.labels.upload_method'),
                            children: [m('div', {className: 'helpText'}, app.translator.trans('flagrow-upload.admin.help_texts.upload_method')), Select.component({
                                options: this.uploadMethodOptions,
                                onchange: this.values.uploadMethod,
                                value: this.values.uploadMethod() || 'local'
                            })]
                        }), m('div', {className: 'ImageUploadPage-preferences'}, [FieldSet.component({
                            label: app.translator.trans('flagrow-upload.admin.labels.preferences.title'),
                            children: [m('label', {}, app.translator.trans('flagrow-upload.admin.labels.preferences.max_file_size')), m('input', {
                                className: 'FormControl',
                                value: this.values.maxFileSize() || 2048,
                                oninput: m.withAttr('value', this.values.maxFileSize)
                            })]
                        })]), m('div', {className: 'ImageUploadPage-resize'}, [FieldSet.component({
                            label: app.translator.trans('flagrow-upload.admin.labels.resize.title'),
                            children: [m('div', {className: 'helpText'}, app.translator.trans('flagrow-upload.admin.help_texts.resize')), Switch.component({
                                state: this.values.mustResize() || false,
                                children: app.translator.trans('flagrow-upload.admin.labels.resize.toggle'),
                                onchange: this.values.mustResize
                            }), m('label', {}, app.translator.trans('flagrow-upload.admin.labels.resize.max_width')), m('input', {
                                className: 'FormControl',
                                value: this.values.resizeMaxWidth() || 100,
                                oninput: m.withAttr('value', this.values.resizeMaxWidth),
                                disabled: !this.values.mustResize()
                            }), m('label', {}, app.translator.trans('flagrow-upload.admin.labels.resize.max_height')), m('input', {
                                className: 'FormControl',
                                value: this.values.resizeMaxHeight() || 100,
                                oninput: m.withAttr('value', this.values.resizeMaxHeight),
                                disabled: !this.values.mustResize()
                            })]
                        })]), m('div', {
                            className: 'ImageUploadPage-local',
                            style: {display: this.values.uploadMethod() === 'local' ? "block" : "none"}
                        }, [FieldSet.component({
                            label: app.translator.trans('flagrow-upload.admin.labels.local.title'),
                            children: [m('label', {}, app.translator.trans('flagrow-upload.admin.labels.local.cdn_url')), m('input', {
                                className: 'FormControl',
                                value: this.values.cdnUrl() || '',
                                oninput: m.withAttr('value', this.values.cdnUrl)
                            })]
                        })]), Button.component({
                            type: 'submit',
                            className: 'Button Button--primary',
                            children: app.translator.trans('flagrow-upload.admin.buttons.save'),
                            loading: this.loading,
                            disabled: !this.changed()
                        })])])])];
                    }
                }, {
                    key: "changed",
                    value: function changed() {
                        var _this3 = this;

                        var fieldsCheck = this.fields.some(function (key) {
                            return _this3.values[key]() !== app.data.settings[_this3.addPrefix(key)];
                        });
                        var checkboxesCheck = this.checkboxes.some(function (key) {
                            return _this3.values[key]() !== (app.data.settings[_this3.addPrefix(key)] == '1');
                        });
                        return fieldsCheck || checkboxesCheck;
                    }
                }, {
                    key: "onsubmit",
                    value: function onsubmit(e) {
                        var _this4 = this;

                        // prevent the usual form submit behaviour
                        e.preventDefault();

                        // if the page is already saving, do nothing
                        if (this.loading) return;

                        // prevents multiple savings
                        this.loading = true;
                        app.alerts.dismiss(this.successAlert);

                        var settings = {};

                        // gets all the values from the form
                        this.fields.forEach(function (key) {
                            return settings[_this4.addPrefix(key)] = _this4.values[key]();
                        });
                        this.checkboxes.forEach(function (key) {
                            return settings[_this4.addPrefix(key)] = _this4.values[key]();
                        });

                        // actually saves everything in the database
                        saveSettings(settings).then(function () {
                            // on succes, show an alert
                            app.alerts.show(_this4.successAlert = new Alert({
                                type: 'success',
                                children: app.translator.trans('core.admin.basics.saved_message')
                            }));
                        }).catch(function () {
                        }).then(function () {
                            // return to the initial state and redraw the page
                            _this4.loading = false;
                            m.redraw();
                        });
                    }
                }, {
                    key: "addPrefix",
                    value: function addPrefix(key) {
                        return this.settingsPrefix + '.' + key;
                    }
                }]);
                return UploadPage;
            }(Component);

            _export("default", UploadPage);
        }
    };
});
;
"use strict";

System.register("flagrow/upload/main", ["flarum/extend", "flarum/app", "flarum/components/PermissionGrid", "flagrow/upload/addUploadPane"], function (_export, _context) {
    "use strict";

    var extend, app, PermissionGrid, addUploadPane;
    return {
        setters: [function (_flarumExtend) {
            extend = _flarumExtend.extend;
        }, function (_flarumApp) {
            app = _flarumApp.default;
        }, function (_flarumComponentsPermissionGrid) {
            PermissionGrid = _flarumComponentsPermissionGrid.default;
        }, function (_flagrowUploadAddUploadPane) {
            addUploadPane = _flagrowUploadAddUploadPane.default;
        }],
        execute: function () {

            app.initializers.add('flagrow-upload', function (app) {
                // add the admin pane
                addUploadPane();

                // add the permission option to the relative pane
                extend(PermissionGrid.prototype, 'startItems', function (items) {
                    items.add('upload', {
                        icon: 'file-o',
                        label: app.translator.trans('flagrow-upload.admin.permissions.upload_label'),
                        permission: 'flagrow.upload'
                    });
                });
            });
        }
    };
});<|endoftext|>


<commit_before>$(document).ready(function() {
      $("#submit").submit(function(event) {
        event.preventDefault();

        var $form = $(this),
          key = $form.find("input[name='key']").val(),
          value = $form.find("input[name='value']").val(),
          url = '/api/set/shoutbox/'

        var posting = $.post(url, {
          Key: key,
          Value: value,
          Page: 0,
          App: "Shoutbox",
          User: "Demo"
        });

        posting.done(function(data) {
          $("#result").empty().append(data);
        });
      });
      $("#request").submit(function(event) {
        event.preventDefault();
        var $form = $(this),
          url = '/api/get/shoutbox/',
          term = $form.find("input[name='skey']").val(),
          posting = $.post(url, {
            Key: term,
            App: "Shoutbox",
            User: "Demo"
          });

        posting.done(function(data) {
		if (data === "") {
		  var returnString = "Not found!"
		} else {
          var returnString = "GET for " + JSON.stringify(data);
		}
          $("#result").empty().append(returnString);
        });
      });
});
<commit_msg>removing inline<commit_after>$(document).ready(function() {
  $("#submit").submit(function(event) {
    event.preventDefault();
    var $form = $(this),
      key = $form.find("input[name='key']").val(),
      value = $form.find("input[name='value']").val(),
      url = '/api/set/shoutbox/',
      posting = $.post(url, {
        Key: key,
        Value: value,
        Page: 0,
        App: "Shoutbox",
        User: "Demo"
      });

    posting.done(function(data) {
      $("#result").empty().append(data);
    });
  });
  $("#request").submit(function(event) {
    event.preventDefault();
    var $form = $(this),
      url = '/api/get/shoutbox/',
      term = $form.find("input[name='skey']").val(),
      posting = $.post(url, {
        Key: term,
        App: "Shoutbox",
        User: "Demo"
      });

    posting.done(function(data) {
      if (data === "") {
        var returnString = "Not found!"
      } else {
        var returnString = "GET for " + JSON.stringify(data);
      }
      $("#result").empty().append(returnString);
    });
  });
});
<|endoftext|>