<commit_before>
	app_page.features.push(function(app){
		tc.util.log('Give A Minute: User Account oAuth');

		if(app.app_page.data.facebook_connected){
			$(".connect-facebook").closest(".social-networking").addClass("facebook-connected");
			$(".disconnect-facebook").click(function(event){
				event.preventDefault();
				$.getJSON("/disconnect_facebook", function(data){
					if(data.success) {
						$(".connect-facebook").closest(".social-networking").removeClass("facebook-connected");
					}
				});
			});
		} else {
			$(".connect-facebook").click(function(event){
				event.preventDefault();
				F.connect();
			});
		}

		if(app.app_page.data.twitter_connected){
			$(".connect-twitter").closest(".social-networking").addClass("twitter-connected");
			$(".disconnect-twitter").click(function(event){
				event.preventDefault();
				$.getJSON("/disconnect_twitter", function(data){
					if(data.success) {
						$(".connect-twitter").closest(".social-networking").removeClass("twitter-connected");
					}
				});
			});
		}

	});

	app_page.features.push(function(app){
		tc.util.log('Give A Minute: User Account');

		app.components.user_page_merlin = new tc.merlin(app,{
			name: "user-account",
			dom:tc.jQ('.midlands.merlin'),
			first_step:'activity',
			steps:{
				'activity':{
					selector:'.activity-view',
					init:function(merlin,dom){
						tc.jQ('ul.tabs li').removeClass('active').filter(".activity").addClass("active");
						tc.jQ('.addphoto').hide();

						dom.find('a.remove-idea').unbind("click").bind('click', {app:app}, function(e){
							e.preventDefault();
							e.data.app.components.modal.show({
								app:e.data.app,
								source_element:tc.jQ('.modal-content.remove-idea'),
								submit:function(){
									tc.jQ.ajax({
										type:'POST',
										url:'/idea/remove',
										data:{
											idea_id: e.target.hash.split(',')[1]
										},
										context: tc.jQ(e.target),
										dataType:'text',
										success:function(data,ts,xhr){
											var item;
											if(data == 'False'){
												return false;
											}
											item = this.parents("li").eq(0);

											(function(counter, n) {
												counter.text(n);
											}(this.parents(".box").eq(0).children(".hd").find(".counter"), item.siblings().length));

											item.remove();

											tc.jQ('ul.idea-cards > li').removeClass('every-third').filter(function(index) {
									 			return index % 3 == 2;
											}).addClass('every-third');
										}
									});
								}
							});
						});
						// add official resource tags
						tc.addOfficialResourceTags(tc.jQ('table.resources-list'));
					}
				},
				'messages':{
					selector:'.messages-view',
					current_offset: app.app_page.data.user_activity.messages.length-1,
					n_to_fetch:5,
					has_run_init: false,
					init:function(merlin,dom){
						tc.jQ('ul.tabs li').removeClass('active').filter(".messages").addClass("active");
						tc.jQ('.addphoto').hide();

						if (!merlin.current_step.has_run_init) {
							(function() {
								var checklist, pref;
								checklist = tc.jQ(".messages-view .preferences .checklist");
								pref = app.app_page.user.email_notification;
								switch (pref) {
									case "digest":
										checklist.find("label[for='pref-emails-daily']").click();
										break;
									case "none":
										checklist.find("label[for='pref-no-emails']").click();
								}
							}());
							merlin.current_step.has_run_init = true;
						}

						//Click event to handle "prettyCheckbox" custom check boxes
						//This event is namespaced to avoid collisions with the click events bound by $.fn.prettyCheckboxes()
						dom.find(".preferences .checklist .prettyCheckbox.radio").unbind("click.message_prefs")
						   .bind("click.message_prefs", {merlin:merlin}, function(e, d) {
								var pref;
								switch (tc.jQ(this).attr("for")) {
									case "pref-emails-daily":
										pref = "digest";
										break;
									case "pref-no-emails":
										pref = "none";
										break;
								}
								if (!pref) {
									tc.util.log("error parsing email pref", "warn");
									return false;
								}
								tc.jQ.ajax({
									type:"POST",
									url:"/useraccount/messageprefs",
									data:{
										pref: pref
									},
									context:e.data.merlin,
									dataType:"text",
									success: function(data, ts, xhr) {
										if (data == "False") {
											return false;
										}
									}
								});
							});

						dom.find(".load-more a").unbind("click").bind("click", {merlin:merlin, dom:dom}, function(e, d) {
							var $t;
							$t = tc.jQ(e.target);
							$t.parent().addClass("loading");
							e.preventDefault();
							tc.jQ.ajax({
								type:"POST",
								url:"/useraccount/messages",
								data:{
									n_messages: e.data.merlin.current_step.n_to_fetch,
									offset: e.data.merlin.current_step.current_offset
								},
								context:merlin,
								dataType:"text",
								success: function(data, ts, xhr) {
									var d, dom_stack;
									$t.parent().removeClass("loading");
									try {
										d = tc.jQ.parseJSON(data);
									} catch(e) {
										tc.util.log("/useraccount/messages: json parsing error", "warn");
										return;
									}
									if (!d.length) {
										$t.hide();
										return;
									}
									dom_stack = e.data.dom.find("ol.message-stack");
									tc.jQ.each(d, function(i, message) {
										var template;
										switch (message.message_type) {
											case "member_comment":
												template = tc.jQ(".template-content.message-item.member-comment").clone().removeClass("template-content");
												if (message.owner.image_id) {
													template.find(".thumb img").attr("src", "/images/"+ message.owner.image_id % 10 +"/"+ message.owner.image_id +".png").attr("alt", message.owner.name);
												} else {
													template.find(".thumb img").attr("src", "/static/images/thumb_genAvatar50.png").attr("alt", message.owner.name);
												}
												template.find(".sender").html(""+ message.owner.name+ "").next().text(message.created).time_since();
												template.find(".excerpt p").text(message.body);
												break;
											case "join":
												template = tc.jQ(".template-content.message-item.join-notification").clone().removeClass("template-content");
												template.find(".title").text(message.body);
												template.find(".controls > a").attr("href", "/project/"+ message.project_id +"#show,members");
												break;
											case "invite":
												template = tc.jQ(".template-content.message-item.user-notification").clone().removeClass("template-content");
												template.find(".title").text(message.body);
												template.find(".controls > a").attr("href", ("/project/"+ message.project_id + ""));
												break;
											default:
												break;
										}
										if (template) {
											dom_stack.append(template);
										}
									});
									this.current_step.current_offset += d.length;
								}
							});
						});
					}
				},
				'account':{
					selector:'.account-view',
					init:function(merlin,dom){
						tc.jQ('ul.tabs li').removeClass('active').filter(".account").addClass("active");
						window.location.hash = "account-info,edit-account-details";
						tc.jQ('.addphoto').show();
					}
				},
				'resources':{
					selector:'.resources-view',
					init:function(merlin,dom){
						tc.jQ('ul.tabs li').removeClass('active').filter(".resources").addClass("active");
						window.location.hash = "resources-info";
						tc.jQ('.addphoto').hide();
					}
				}
			}
		});

		//commented out because it is breaking the page.
		//tc.gam.ideas_invite(app);

		// random note-card backgrounds
		var ideasList = tc.jQ('.idea-cards li');
		for (i=0; i < ideasList.length; i++) {
			ideasList.eq(i).children('.note-card').addClass('card' + (Math.floor(Math.random()*4) + 1));
		}

	});
	<commit_msg>fixed small problem on useraccount<commit_after>
	app_page.features.push(function(app){
		tc.util.log('Give A Minute: User Account oAuth');

		if(app.app_page.data.facebook_connected){
			$(".connect-facebook").closest(".social-networking").addClass("facebook-connected");
			$(".disconnect-facebook").click(function(event){
				event.preventDefault();
				$.getJSON("/disconnect_facebook", function(data){
					if(data.success) {
						$(".connect-facebook").closest(".social-networking").removeClass("facebook-connected");
					}
				});
			});
		} else {
			$(".connect-facebook").click(function(event){
				event.preventDefault();
				F.connect();
			});
		}

		if(app.app_page.data.twitter_connected){
			$(".connect-twitter").closest(".social-networking").addClass("twitter-connected");
			$(".disconnect-twitter").click(function(event){
				event.preventDefault();
				$.getJSON("/disconnect_twitter", function(data){
					if(data.success) {
						$(".connect-twitter").closest(".social-networking").removeClass("twitter-connected");
					}
				});
			});
		}

	});

	app_page.features.push(function(app){
		tc.util.log('Give A Minute: User Account');
		var offset;

		offset = 0;
		if(app.app_page.data.user_activity && app.app_page.data.user_activity.messages){
			offset = app.app_page.data.user_activity.messages.length - 1;
		}

		app.components.user_page_merlin = new tc.merlin(app,{
			name: "user-account",
			dom:tc.jQ('.midlands.merlin'),
			first_step:'activity',
			steps:{
				'activity':{
					selector:'.activity-view',
					init:function(merlin,dom){
						tc.jQ('ul.tabs li').removeClass('active').filter(".activity").addClass("active");
						tc.jQ('.addphoto').hide();

						dom.find('a.remove-idea').unbind("click").bind('click', {app:app}, function(e){
							e.preventDefault();
							e.data.app.components.modal.show({
								app:e.data.app,
								source_element:tc.jQ('.modal-content.remove-idea'),
								submit:function(){
									tc.jQ.ajax({
										type:'POST',
										url:'/idea/remove',
										data:{
											idea_id: e.target.hash.split(',')[1]
										},
										context: tc.jQ(e.target),
										dataType:'text',
										success:function(data,ts,xhr){
											var item;
											if(data == 'False'){
												return false;
											}
											item = this.parents("li").eq(0);

											(function(counter, n) {
												counter.text(n);
											}(this.parents(".box").eq(0).children(".hd").find(".counter"), item.siblings().length));

											item.remove();

											tc.jQ('ul.idea-cards > li').removeClass('every-third').filter(function(index) {
									 			return index % 3 == 2;
											}).addClass('every-third');
										}
									});
								}
							});
						});
						// add official resource tags
						tc.addOfficialResourceTags(tc.jQ('table.resources-list'));
					}
				},
				'messages':{
					selector:'.messages-view',
					current_offset: offset,
					n_to_fetch:5,
					has_run_init: false,
					init:function(merlin,dom){
						tc.jQ('ul.tabs li').removeClass('active').filter(".messages").addClass("active");
						tc.jQ('.addphoto').hide();

						if (!merlin.current_step.has_run_init) {
							(function() {
								var checklist, pref;
								checklist = tc.jQ(".messages-view .preferences .checklist");
								pref = app.app_page.user.email_notification;
								switch (pref) {
									case "digest":
										checklist.find("label[for='pref-emails-daily']").click();
										break;
									case "none":
										checklist.find("label[for='pref-no-emails']").click();
								}
							}());
							merlin.current_step.has_run_init = true;
						}

						//Click event to handle "prettyCheckbox" custom check boxes
						//This event is namespaced to avoid collisions with the click events bound by $.fn.prettyCheckboxes()
						dom.find(".preferences .checklist .prettyCheckbox.radio").unbind("click.message_prefs")
						   .bind("click.message_prefs", {merlin:merlin}, function(e, d) {
								var pref;
								switch (tc.jQ(this).attr("for")) {
									case "pref-emails-daily":
										pref = "digest";
										break;
									case "pref-no-emails":
										pref = "none";
										break;
								}
								if (!pref) {
									tc.util.log("error parsing email pref", "warn");
									return false;
								}
								tc.jQ.ajax({
									type:"POST",
									url:"/useraccount/messageprefs",
									data:{
										pref: pref
									},
									context:e.data.merlin,
									dataType:"text",
									success: function(data, ts, xhr) {
										if (data == "False") {
											return false;
										}
									}
								});
							});

						dom.find(".load-more a").unbind("click").bind("click", {merlin:merlin, dom:dom}, function(e, d) {
							var $t;
							$t = tc.jQ(e.target);
							$t.parent().addClass("loading");
							e.preventDefault();
							tc.jQ.ajax({
								type:"POST",
								url:"/useraccount/messages",
								data:{
									n_messages: e.data.merlin.current_step.n_to_fetch,
									offset: e.data.merlin.current_step.current_offset
								},
								context:merlin,
								dataType:"text",
								success: function(data, ts, xhr) {
									var d, dom_stack;
									$t.parent().removeClass("loading");
									try {
										d = tc.jQ.parseJSON(data);
									} catch(e) {
										tc.util.log("/useraccount/messages: json parsing error", "warn");
										return;
									}
									if (!d.length) {
										$t.hide();
										return;
									}
									dom_stack = e.data.dom.find("ol.message-stack");
									tc.jQ.each(d, function(i, message) {
										var template;
										switch (message.message_type) {
											case "member_comment":
												template = tc.jQ(".template-content.message-item.member-comment").clone().removeClass("template-content");
												if (message.owner.image_id) {
													template.find(".thumb img").attr("src", "/images/"+ message.owner.image_id % 10 +"/"+ message.owner.image_id +".png").attr("alt", message.owner.name);
												} else {
													template.find(".thumb img").attr("src", "/static/images/thumb_genAvatar50.png").attr("alt", message.owner.name);
												}
												template.find(".sender").html(""+ message.owner.name+ "").next().text(message.created).time_since();
												template.find(".excerpt p").text(message.body);
												break;
											case "join":
												template = tc.jQ(".template-content.message-item.join-notification").clone().removeClass("template-content");
												template.find(".title").text(message.body);
												template.find(".controls > a").attr("href", "/project/"+ message.project_id +"#show,members");
												break;
											case "invite":
												template = tc.jQ(".template-content.message-item.user-notification").clone().removeClass("template-content");
												template.find(".title").text(message.body);
												template.find(".controls > a").attr("href", ("/project/"+ message.project_id + ""));
												break;
											default:
												break;
										}
										if (template) {
											dom_stack.append(template);
										}
									});
									this.current_step.current_offset += d.length;
								}
							});
						});
					}
				},
				'account':{
					selector:'.account-view',
					init:function(merlin,dom){
						tc.jQ('ul.tabs li').removeClass('active').filter(".account").addClass("active");
						window.location.hash = "account-info,edit-account-details";
						tc.jQ('.addphoto').show();
					}
				},
				'resources':{
					selector:'.resources-view',
					init:function(merlin,dom){
						tc.jQ('ul.tabs li').removeClass('active').filter(".resources").addClass("active");
						window.location.hash = "resources-info";
						tc.jQ('.addphoto').hide();
					}
				}
			}
		});

		//commented out because it is breaking the page.
		//tc.gam.ideas_invite(app);

		// random note-card backgrounds
		var ideasList = tc.jQ('.idea-cards li');
		for (i=0; i < ideasList.length; i++) {
			ideasList.eq(i).children('.note-card').addClass('card' + (Math.floor(Math.random()*4) + 1));
		}

	});
	<|endoftext|>


<commit_before>/**
 * @name index.js<beez-touch/s>
 * @author Masaki Sueda <s.masaki07@gmail.com>
 * @overview Touch event plug-in for Beez (browser)
 * @license MIT
 */

var BEEZ_TOUCH_VERSION = '0.3.1';

if (typeof module !== 'undefined' && module.exports) { // node.js: main

    exports.VERSION = BEEZ_TOUCH_VERSION;

} else {

    (function (global) {

        define(function (require, exports, module) {

            var beez = require('beez'),
                logger = beez.getLogger('beez.touch');

            if (beez.touch) {
                logger.warn('beez.touch is already loaded.');
                return beez.touch;
            }

            // vendor
            var _ = beez.vendor._,
                $ = beez.vendor.$;

            // device flag
            var hasTouch = 'ontouchstart' in window,
                EVENT = {
                start: {
                    name: hasTouch ? 'touchstart' : 'mousedown',
                    callback: 'onBztchTapStart'
                },
                move: {
                    name: hasTouch ? 'touchmove' : 'mousemove',
                    callback: 'onBztchTapMove'
                },
                end: {
                    name: hasTouch ? 'touchend' : 'mouseup',
                    callback: 'onBztchTapEnd'
                }
            };

            /**
             * normalize position
             * @param  {Events} e event object
             */
            var normalizePosition = function normalizePosition(e) {
                var position = {};

                if (hasTouch) {
                    if (e.originalEvent) {
                        position = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
                        position = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
                    } else {
                        position = e.changedTouches[0] && e.changedTouches[0];
                    }
                } else {
                    position = e;
                }

                return position;
            };

            var Inheritance = (function (global) {
                Inheritance = function () {};
                Inheritance.prototype = {
                    /**
                     * initialize
                     */
                    initialize: function initialize(options) {
                        TouchView.__super__.initialize.apply(this, arguments);

                        options = options || {};
                        options.bztch = options.bztch || {};

                        /**
                         * Tap event data
                         * @type {Object}
                         */
                        this._bztchTaps = null;

                        /**
                         * Flag of enable to tap
                         * @type {Boolean}
                         */
                        this._bztchIsTappable = false;

                        /**
                         * Flag of unable to touch
                         * @type {Boolean}
                         */
                        this._bztchIsDisable = false;

                        /**
                         * Flag of mouse down
                         * @type {Boolean}
                         */
                        this._bztchIsTapMouseDown = false;

                        /**
                         * Base prefix
                         * @type {String}
                         */
                        this._bztchPrefix = _.isString(options.bztch.prefix) ? options.bztch.prefix : 'bztch';

                        /**
                         * Prefix for tap
                         * @type {String}
                         */
                        this._bztchTapPrefix = this._bztchPrefix + '-tap';

                        /**
                         * ClassName of hover
                         * @type {String}
                         */
                        this._bztchHoverClassName = _.isString(options.bztch.hoverClassName) ? options.bztch.hoverClassName : 'hover';

                        /**
                         * ClassName of disable
                         * @type {String}
                         */
                        this._bztchDisableClassName = _.isString(options.bztch.disableClassName) ? options.bztch.disableClassName : 'disable';

                        /**
                         * Position of touchstart
                         * @type {Object}
                         */
                        this._bztchStartPosition = {};

                        /**
                         * time manager of beez
                         * @type {Timer}
                         */
                        this._bztchTimer = new beez.utils.Timers();

                        /**
                         * Threshold of touch cancel
                         * @type {Number}
                         */
                        this._bztchThreshold = options.bztch.threshold || 10;
                    },

                    /**
                     * Add tap events to the elements
                     * @param {Element} $elm
                     * @param {Function} callback
                     * @param {beez.View} context
                     * @param {Object} options
                     */
                    tap: function tap($elm, callback, context, options) {
                        var self = this,
                            tap,
                            uid;

                        options = _.defaults(options || {}, {
                            tapStart: beez.none,
                            tapMove: beez.none,
                            tapEnd: beez.none,
                            tapHold: beez.none,
                            context: self
                        });

                        // multiple selector
                        if (beez.utils.isArray($elm) && $elm.length > 1) {
                            _.each($elm, function (list, i) {
                                self.tap($elm.eq(i), callback, context, options);
                            });
                            return;
                        }

                        if (!self._atached || (!self._atachedSelf && $elm === self.$el)) {
                            // register events to tap
                            _.each(EVENT, function (evt) {
                                var eventName = evt.name + '.delegateEvents' + self.cid,
                                    callback = evt.callback;

                                if ($elm === self.$el) {
                                    self.$el.on(eventName, _.bind(self[callback], self) || beez.none);
                                    self._atachedSelf = true;
                                } else {
                                    self.$el.on(eventName, '.' + self._bztchTapPrefix, _.bind(self[callback], self) || beez.none);
                                    self._atached = true;
                                }
                            });
                        }

                        self._bztchTaps = self._bztchTaps || {};

                        tap = {
                            callback : callback || beez.none,
                            callbackStart : options.tapStart,
                            callbackMove : options.tapMove,
                            callbackEnd : options.tapEnd,
                            callbackHold: options.tapHold,
                            holdDuration: options.holdDuration,
                            once: options.once || false,
                            $elm: $elm,
                            context : context
                        };

                        if ($elm.hasClass(self._bztchTapPrefix)) {
                            uid = $elm.attr('data-' + self._bztchTapPrefix + 'Uid');
                            if (_.isEmpty(self._bztchTaps[uid])) {
                                self._bztchTaps[uid] = [];
                            }
                            self._bztchTaps[uid].push(tap);
                        } else {
                            uid = _.uniqueId(self._bztchTapPrefix + '-');
                            self._bztchTaps[uid] = [tap];
                            // enable to tap
                            $elm.addClass(self._bztchTapPrefix);
                            $elm.attr('data-' + self._bztchTapPrefix + 'Uid', uid);
                        }

                        if (tap.holdDuration) {
                            $elm.css({
                                '-webkit-touch-callout': 'none'
                            });
                        }

                        return self;

                    },

                    /**
                     * longTap
                     *
                     * @param {Element} $elm
                     * @param {Function} callback
                     * @param {beez.View} context
                     * @param {Object} options
                     */
                    longTap: function longTap($elm, callback, context, options) {
                        return this.tap($elm, null, context, {
                            tapHold: callback,
                            holdDuration: options.holdDuration || 1000
                        });
                    },

                    /**
                     * tapOnce
                     *
                     * @param {Element} $elm
                     * @param {Function} callback
                     * @param {beez.View} context
                     * @param {Object} options
                     */
                    tapOnce: function tapOnce($elm, callback, context, options) {
                        options = _.extend(options || {}, {
                            once: true
                        });
                        return this.tap($elm, callback, context, options);
                    },

                    /**
                     * touchstart start
                     * @param {Object} e
                     */
                    onBztchTapStart: function onBztchTapStart(e) {
                        var self = this,
                            target = $(e.currentTarget),
                            uid,
                            taps;

                        uid = self._bztchGetId(target);

                        if (!uid || !self._bztchHasTap(uid)) {
                            return;
                        }

                        taps = self._bztchTaps[uid];

                        var position = normalizePosition(e);
                        self._bztchStartPosition = {
                            x: position.pageX,
                            y: position.pageY
                        };

                        // check lock
                        if (!target.data('disable')) {
                            self._bztchIsTappable = true;
                            target.addClass(self._bztchHoverClassName);

                            // execute callback!!
                            _.each(taps, function (tap) {
                                if (tap.holdDuration) {
                                    tap.timerId && self._bztchTimer.clearTimeout(tap.timerId);
                                    tap.timerId = self._bztchTimer.addTimeout(function () {
                                        if (!self._bztchIsTappable) {
                                            self._bztchCancel(e);
                                            return;
                                        }
                                        tap.callbackHold.call(tap.context, e);
                                        self._bztchCancel(e);
                                    }, tap.holdDuration);
                                }
                                tap.callbackStart.call(tap.context, e);
                            });
                        }

                    },

                    /**
                     * touch move
                     * @param {Object} e
                     */
                    onBztchTapMove: function onBztchTapMove(e) {
                        var self = this,
                            target = $(e.currentTarget),
                            uid,
                            taps;

                        if (!self._bztchIsTappable) {
                            self._bztchCancel(e);
                            return;
                        }

                        uid = self._bztchGetId(target);

                        if (!uid || !self._bztchHasTap(uid)) {
                            return;
                        }

                        taps = self._bztchTaps[uid];

                        var position = normalizePosition(e);
                        // execute callback
                        _.each(taps, function (tap) {
                            tap.callbackMove.call(tap.context, e);
                        });

                        // threshold
                        if (
                            Math.abs(position.pageX - self._bztchStartPosition.x) > self._bztchThreshold ||
                            Math.abs(position.pageY - self._bztchStartPosition.y) > self._bztchThreshold
                        ) {
                            self._bztchCancel(e);
                            self._bztchIsTappable = false;
                            target.removeClass(self._bztchHoverClassName);
                        }
                    },

                    /**
                     * touch end
                     * @param {Object} e
                     */
                    onBztchTapEnd: function onBztchTapEnd(e) {
                        var self = this,
                            target = $(e.currentTarget),
                            uid,
                            taps;

                        e.preventDefault();
                        if (!self._bztchIsTappable) {
                            this._bztchCancel(e);
                            return;
                        }
                        self._bztchIsTappable = false;

                        uid = self._bztchGetId(target);
                        if (!uid || !self._bztchHasTap(uid)) {
                            return;
                        }

                        taps = self._bztchTaps[uid];

                        if (!target.data('disable')) {
                            _.each(taps, function (tap, i) {
                                tap.callbackEnd.call(tap.context, e);
                                tap.callback.call(tap.context, e);
                                if (tap.once) {
                                    self._disposeTap(uid, i);
                                }
                            });
                        }

                        // reset
                        target.removeClass(self._bztchHoverClassName);
                        self._bztchCancel(e);
                    },

                    /**
                     * cancel
                     */
                    _bztchCancel: function _bztchCancel(e) {
                        this._bztchTimer.stop();
                        this._bztchIsTappable = false;
                        $(e.currentTarget).removeClass(this._bztchHoverClassName);
                    },

                    /**
                     * get tap event data
                     */
                    _bztchGetId: function _bztchGetId(target) {
                        return target.attr('data-' + this._bztchTapPrefix + 'Uid');
                    },

                    /**
                     * has tap data
                     */
                    _bztchHasTap: function _bztchHasTap(id) {
                        return _.has((this._bztchTaps ? this._bztchTaps : {}), id);
                    },

                    enable: function enable($el) {
                        if ($el) {
                            $el.removeClass(this._bztchDisableClassName);
                            $el.data('disable', false);
                        } else {
                            _.each(this._bztchTaps, function (taps) {
                                _.each(taps, function (tap) {
                                    if (tap.$elm) {
                                        tap.$elm.data('disable', false);
                                        tap.$elm.removeClass(this._bztchDisableClassName);
                                    }
                                }, this);
                            }, this);
                        }
                    },

                    disable: function disable($el) {
                        if ($el) {
                            $el.data('disable', true);
                            $el.addClass(this._bztchDisableClassName);
                        } else {
                            _.each(this._bztchTaps, function (taps) {
                                _.each(taps, function (tap) {
                                    if (tap.$elm) {
                                        tap.$elm.data('disable', true);
                                        tap.$elm.addClass(this._bztchDisableClassName);
                                    }
                                }, this);
                            }, this);
                        }
                    },

                    _disposeTap: function _disposeTap(id, index) {
                        if (!this._bztchTaps || !this._bztchTaps[id] || !this._bztchTaps[id][index]) {
                            return;
                        }
                        delete this._bztchTaps[id][index].callback;
                        delete this._bztchTaps[id][index].callbackStart;
                        delete this._bztchTaps[id][index].callbackMove;
                        delete this._bztchTaps[id][index].callbackHold;
                        delete this._bztchTaps[id][index].context;
                        delete this._bztchTaps[id][index].$elm;
                        delete this._bztchTaps[id][index];

                        this._bztchTaps[id].splice(index, 1);

                    },

                    /**
                     * dispose
                     */
                    dispose: function dispose() {

                        _.each(this._bztchTaps, function (taps, id) {
                            _.each(taps, function (tap, i) {
                                this._disposeTap(id, i);
                            }, this);
                            delete this._bztchTaps[id];
                        }, this);

                        delete this._bztchTaps;
                        delete this._bztchIsTappable;
                        delete this._bztchIsTapMouseDown;
                        delete this._bztchPrefix;
                        delete this._bztchTapPrefix;
                        delete this._bztchHoverClassName;
                        delete this._bztchStartPosition;

                        // super
                        TouchView.__super__.dispose.apply(this, arguments);
                    }
                };

                return Inheritance;

            })(this);

            /**
             * Touch View class
             *
             * @class
             * @extends beez.View
             */
            var TouchView = beez.View.extend(
                'beez.Touch',
                Inheritance.prototype
            );

            beez.touch = {
                View: TouchView,
                __inheritance__: Inheritance
            };

            return beez.touch;
        });
    })(this);
}
<commit_msg>Fixed bug next callback is ignored when using tapOnce<commit_after>/**
 * @name index.js<beez-touch/s>
 * @author Masaki Sueda <s.masaki07@gmail.com>
 * @overview Touch event plug-in for Beez (browser)
 * @license MIT
 */

var BEEZ_TOUCH_VERSION = '0.3.1';

if (typeof module !== 'undefined' && module.exports) { // node.js: main

    exports.VERSION = BEEZ_TOUCH_VERSION;

} else {

    (function (global) {

        define(function (require, exports, module) {

            var beez = require('beez'),
                logger = beez.getLogger('beez.touch');

            if (beez.touch) {
                logger.warn('beez.touch is already loaded.');
                return beez.touch;
            }

            // vendor
            var _ = beez.vendor._,
                $ = beez.vendor.$;

            // device flag
            var hasTouch = 'ontouchstart' in window,
                EVENT = {
                start: {
                    name: hasTouch ? 'touchstart' : 'mousedown',
                    callback: 'onBztchTapStart'
                },
                move: {
                    name: hasTouch ? 'touchmove' : 'mousemove',
                    callback: 'onBztchTapMove'
                },
                end: {
                    name: hasTouch ? 'touchend' : 'mouseup',
                    callback: 'onBztchTapEnd'
                }
            };

            /**
             * normalize position
             * @param  {Events} e event object
             */
            var normalizePosition = function normalizePosition(e) {
                var position = {};

                if (hasTouch) {
                    if (e.originalEvent) {
                        position = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
                        position = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
                    } else {
                        position = e.changedTouches[0] && e.changedTouches[0];
                    }
                } else {
                    position = e;
                }

                return position;
            };

            var Inheritance = (function (global) {
                Inheritance = function () {};
                Inheritance.prototype = {
                    /**
                     * initialize
                     */
                    initialize: function initialize(options) {
                        TouchView.__super__.initialize.apply(this, arguments);

                        options = options || {};
                        options.bztch = options.bztch || {};

                        /**
                         * Tap event data
                         * @type {Object}
                         */
                        this._bztchTaps = null;

                        /**
                         * Flag of enable to tap
                         * @type {Boolean}
                         */
                        this._bztchIsTappable = false;

                        /**
                         * Flag of unable to touch
                         * @type {Boolean}
                         */
                        this._bztchIsDisable = false;

                        /**
                         * Flag of mouse down
                         * @type {Boolean}
                         */
                        this._bztchIsTapMouseDown = false;

                        /**
                         * Base prefix
                         * @type {String}
                         */
                        this._bztchPrefix = _.isString(options.bztch.prefix) ? options.bztch.prefix : 'bztch';

                        /**
                         * Prefix for tap
                         * @type {String}
                         */
                        this._bztchTapPrefix = this._bztchPrefix + '-tap';

                        /**
                         * ClassName of hover
                         * @type {String}
                         */
                        this._bztchHoverClassName = _.isString(options.bztch.hoverClassName) ? options.bztch.hoverClassName : 'hover';

                        /**
                         * ClassName of disable
                         * @type {String}
                         */
                        this._bztchDisableClassName = _.isString(options.bztch.disableClassName) ? options.bztch.disableClassName : 'disable';

                        /**
                         * Position of touchstart
                         * @type {Object}
                         */
                        this._bztchStartPosition = {};

                        /**
                         * time manager of beez
                         * @type {Timer}
                         */
                        this._bztchTimer = new beez.utils.Timers();

                        /**
                         * Threshold of touch cancel
                         * @type {Number}
                         */
                        this._bztchThreshold = options.bztch.threshold || 10;
                    },

                    /**
                     * Add tap events to the elements
                     * @param {Element} $elm
                     * @param {Function} callback
                     * @param {beez.View} context
                     * @param {Object} options
                     */
                    tap: function tap($elm, callback, context, options) {
                        var self = this,
                            tap,
                            uid;

                        options = _.defaults(options || {}, {
                            tapStart: beez.none,
                            tapMove: beez.none,
                            tapEnd: beez.none,
                            tapHold: beez.none,
                            context: self
                        });

                        // multiple selector
                        if (beez.utils.isArray($elm) && $elm.length > 1) {
                            _.each($elm, function (list, i) {
                                self.tap($elm.eq(i), callback, context, options);
                            });
                            return;
                        }

                        if (!self._atached || (!self._atachedSelf && $elm === self.$el)) {
                            // register events to tap
                            _.each(EVENT, function (evt) {
                                var eventName = evt.name + '.delegateEvents' + self.cid,
                                    callback = evt.callback;

                                if ($elm === self.$el) {
                                    self.$el.on(eventName, _.bind(self[callback], self) || beez.none);
                                    self._atachedSelf = true;
                                } else {
                                    self.$el.on(eventName, '.' + self._bztchTapPrefix, _.bind(self[callback], self) || beez.none);
                                    self._atached = true;
                                }
                            });
                        }

                        self._bztchTaps = self._bztchTaps || {};

                        tap = {
                            callback : callback || beez.none,
                            callbackStart : options.tapStart,
                            callbackMove : options.tapMove,
                            callbackEnd : options.tapEnd,
                            callbackHold: options.tapHold,
                            holdDuration: options.holdDuration,
                            once: options.once || false,
                            $elm: $elm,
                            context : context
                        };

                        if ($elm.hasClass(self._bztchTapPrefix)) {
                            uid = $elm.attr('data-' + self._bztchTapPrefix + 'Uid');
                            if (_.isEmpty(self._bztchTaps[uid])) {
                                self._bztchTaps[uid] = [];
                            }
                            self._bztchTaps[uid].push(tap);
                        } else {
                            uid = _.uniqueId(self._bztchTapPrefix + '-');
                            self._bztchTaps[uid] = [tap];
                            // enable to tap
                            $elm.addClass(self._bztchTapPrefix);
                            $elm.attr('data-' + self._bztchTapPrefix + 'Uid', uid);
                        }

                        if (tap.holdDuration) {
                            $elm.css({
                                '-webkit-touch-callout': 'none'
                            });
                        }

                        return self;

                    },

                    /**
                     * longTap
                     *
                     * @param {Element} $elm
                     * @param {Function} callback
                     * @param {beez.View} context
                     * @param {Object} options
                     */
                    longTap: function longTap($elm, callback, context, options) {
                        return this.tap($elm, null, context, {
                            tapHold: callback,
                            holdDuration: options.holdDuration || 1000
                        });
                    },

                    /**
                     * tapOnce
                     *
                     * @param {Element} $elm
                     * @param {Function} callback
                     * @param {beez.View} context
                     * @param {Object} options
                     */
                    tapOnce: function tapOnce($elm, callback, context, options) {
                        options = _.extend(options || {}, {
                            once: true
                        });
                        return this.tap($elm, callback, context, options);
                    },

                    /**
                     * touchstart start
                     * @param {Object} e
                     */
                    onBztchTapStart: function onBztchTapStart(e) {
                        var self = this,
                            target = $(e.currentTarget),
                            uid,
                            taps;

                        uid = self._bztchGetId(target);

                        if (!uid || !self._bztchHasTap(uid)) {
                            return;
                        }

                        taps = self._bztchTaps[uid];

                        var position = normalizePosition(e);
                        self._bztchStartPosition = {
                            x: position.pageX,
                            y: position.pageY
                        };

                        // check lock
                        if (!target.data('disable')) {
                            self._bztchIsTappable = true;
                            target.addClass(self._bztchHoverClassName);

                            // execute callback!!
                            _.each(taps, function (tap) {
                                if (tap.holdDuration) {
                                    tap.timerId && self._bztchTimer.clearTimeout(tap.timerId);
                                    tap.timerId = self._bztchTimer.addTimeout(function () {
                                        if (!self._bztchIsTappable) {
                                            self._bztchCancel(e);
                                            return;
                                        }
                                        tap.callbackHold.call(tap.context, e);
                                        self._bztchCancel(e);
                                    }, tap.holdDuration);
                                }
                                tap.callbackStart.call(tap.context, e);
                            });
                        }

                    },

                    /**
                     * touch move
                     * @param {Object} e
                     */
                    onBztchTapMove: function onBztchTapMove(e) {
                        var self = this,
                            target = $(e.currentTarget),
                            uid,
                            taps;

                        if (!self._bztchIsTappable) {
                            self._bztchCancel(e);
                            return;
                        }

                        uid = self._bztchGetId(target);

                        if (!uid || !self._bztchHasTap(uid)) {
                            return;
                        }

                        taps = self._bztchTaps[uid];

                        var position = normalizePosition(e);
                        // execute callback
                        _.each(taps, function (tap) {
                            tap.callbackMove.call(tap.context, e);
                        });

                        // threshold
                        if (
                            Math.abs(position.pageX - self._bztchStartPosition.x) > self._bztchThreshold ||
                            Math.abs(position.pageY - self._bztchStartPosition.y) > self._bztchThreshold
                        ) {
                            self._bztchCancel(e);
                            self._bztchIsTappable = false;
                            target.removeClass(self._bztchHoverClassName);
                        }
                    },

                    /**
                     * touch end
                     * @param {Object} e
                     */
                    onBztchTapEnd: function onBztchTapEnd(e) {
                        var self = this,
                            target = $(e.currentTarget),
                            uid,
                            taps;

                        e.preventDefault();
                        if (!self._bztchIsTappable) {
                            this._bztchCancel(e);
                            return;
                        }
                        self._bztchIsTappable = false;

                        uid = self._bztchGetId(target);
                        if (!uid || !self._bztchHasTap(uid)) {
                            return;
                        }

                        taps = self._bztchTaps[uid];

                        if (!target.data('disable')) {
                            _.each(taps, function (tap, i) {
                                tap.callbackEnd.call(tap.context, e);
                                tap.callback.call(tap.context, e);
                            });
                        }

                        _.each(taps, function (tap, i) {
                            if (tap.once) {
                                self._disposeTap(uid, i);
                            }
                        });

                        // reset
                        target.removeClass(self._bztchHoverClassName);
                        self._bztchCancel(e);
                    },

                    /**
                     * cancel
                     */
                    _bztchCancel: function _bztchCancel(e) {
                        this._bztchTimer.stop();
                        this._bztchIsTappable = false;
                        $(e.currentTarget).removeClass(this._bztchHoverClassName);
                    },

                    /**
                     * get tap event data
                     */
                    _bztchGetId: function _bztchGetId(target) {
                        return target.attr('data-' + this._bztchTapPrefix + 'Uid');
                    },

                    /**
                     * has tap data
                     */
                    _bztchHasTap: function _bztchHasTap(id) {
                        return _.has((this._bztchTaps ? this._bztchTaps : {}), id);
                    },

                    enable: function enable($el) {
                        if ($el) {
                            $el.removeClass(this._bztchDisableClassName);
                            $el.data('disable', false);
                        } else {
                            _.each(this._bztchTaps, function (taps) {
                                _.each(taps, function (tap) {
                                    if (tap.$elm) {
                                        tap.$elm.data('disable', false);
                                        tap.$elm.removeClass(this._bztchDisableClassName);
                                    }
                                }, this);
                            }, this);
                        }
                    },

                    disable: function disable($el) {
                        if ($el) {
                            $el.data('disable', true);
                            $el.addClass(this._bztchDisableClassName);
                        } else {
                            _.each(this._bztchTaps, function (taps) {
                                _.each(taps, function (tap) {
                                    if (tap.$elm) {
                                        tap.$elm.data('disable', true);
                                        tap.$elm.addClass(this._bztchDisableClassName);
                                    }
                                }, this);
                            }, this);
                        }
                    },

                    _disposeTap: function _disposeTap(id, index) {
                        if (!this._bztchTaps || !this._bztchTaps[id] || !this._bztchTaps[id][index]) {
                            return;
                        }
                        delete this._bztchTaps[id][index].callback;
                        delete this._bztchTaps[id][index].callbackStart;
                        delete this._bztchTaps[id][index].callbackMove;
                        delete this._bztchTaps[id][index].callbackHold;
                        delete this._bztchTaps[id][index].context;
                        delete this._bztchTaps[id][index].$elm;
                        delete this._bztchTaps[id][index];

                        this._bztchTaps[id].splice(index, 1);

                    },

                    /**
                     * dispose
                     */
                    dispose: function dispose() {

                        _.each(this._bztchTaps, function (taps, id) {
                            _.each(taps, function (tap, i) {
                                this._disposeTap(id, i);
                            }, this);
                            delete this._bztchTaps[id];
                        }, this);

                        delete this._bztchTaps;
                        delete this._bztchIsTappable;
                        delete this._bztchIsTapMouseDown;
                        delete this._bztchPrefix;
                        delete this._bztchTapPrefix;
                        delete this._bztchHoverClassName;
                        delete this._bztchStartPosition;

                        // super
                        TouchView.__super__.dispose.apply(this, arguments);
                    }
                };

                return Inheritance;

            })(this);

            /**
             * Touch View class
             *
             * @class
             * @extends beez.View
             */
            var TouchView = beez.View.extend(
                'beez.Touch',
                Inheritance.prototype
            );

            beez.touch = {
                View: TouchView,
                __inheritance__: Inheritance
            };

            return beez.touch;
        });
    })(this);
}
<|endoftext|>


<commit_before>$(function () {

    var swaggerUrl = caramel.context + "/asts/api/apis/swagger?provider=" + store.publisher.api.provider + "&name=" + store.publisher.api.name + "&version=" + store.publisher.api.version;
    $(document).ready(function () {
        $.ajaxSetup({
                        contentType: "application/x-www-form-urlencoded; charset=utf-8"
                    });

        $.get(swaggerUrl, function (data) {
            var designer = new APIMangerAPI.APIDesigner();
            designer.load_api_document(data.data);
            designer.set_default_management_values();
            designer.render_resources();
            $("#swaggerUpload").modal('hide');
        });

        $("#manage_form_1").submit(function (e) {
            e.preventDefault();
        });

        $('#save_api').click(function (e) {
            $this = $(this).attr('id');
        });

        $('#responseCache').change(function () {
            var cache = $('#responseCache').find(":selected").val();
            if (cache == "enabled") {
                $('#cacheTimeout').show();
            }
            else {
                $('#cacheTimeout').hide();
            }
        });

        $('input').on('change', function () {
            var values = $('input:checked.env').map(function () {
                return this.value;
            }).get();
            if (values == "") {
                values = "none";
            }
            $('#environments').val(values.toString());
        });

        function doGatewayAction() {
            var type = $("#retryType").val();
            if (type == "manage") {
                $("#environmentsRetry-modal").modal('hide');
                $("body").trigger("api_saved");
                location.href = "";//TODO
            } else {
                location.href = "";//TODO
            }
        }

        $('#publish_api').click(function (e) {
            $("body").on("api_saved", publishAPI);
            $("#manage_form").submit();
            return false;
        });

        var publish_api = function (e) {
            $.ajax({
                       type: "POST",
                       url: "",
                       async: false,
                       data: {
                           action: "updateStatus",
                           name: store.publisher.api.name,
                           version: store.publisher.api.version,
                           provider: store.publisher.api.provider,
                           status: "PUBLISHED",
                           publishToGateway: true,
                           requireResubscription: true
                       },
                       success: function (responseText) {
                           if (!responseText.error) {
                               //jagg.message({content:"API Published",type:"info"});
                               alert("Error");
                               location.href = "TODO";
                           } else {
                               if (responseText.message == "timeout") {
                                   if (ssoEnabled) {
                                       var currentLoc = window.location.pathname;
                                       if (currentLoc.indexOf(".jag") >= 0) {
                                           location.href = "index.jag";
                                       } else {
                                           location.href = 'site/pages/index.jag';
                                       }
                                   } else {
                                       jagg.showLogin();
                                   }
                               } else {
                                   var message = responseText.message;
                                   if (message.split("||")[1] == "warning") {
                                       var environmentsFailed = JSON.parse(message.split("||")[0]);
                                       var failedToPublishEnvironments = environmentsFailed.PUBLISHED;
                                       var failedToUnpublishedEnvironments = environmentsFailed.UNPUBLISHED;
                                       var divPublish = "", divUnpublished = "";
                                       for (i = 0; i < failedToPublishEnvironments.split(",").length; i++) {
                                           divPublish += failedToPublishEnvironments.split(",")[i] + "
";
                                       }
                                       for (i = 0; i < failedToUnpublishedEnvironments.split(",").length; i++) {
                                           divUnpublished += failedToUnpublishedEnvironments.split(",")[i] + "
";
                                       }
                                       $("#modal-published-content").empty();
                                       $("#modal-unpublished-content").empty();
                                       $("#modal-published-content").append(divPublish);
                                       $("#modal-unpublished-content").append(divUnpublished);
                                       if (failedToPublishEnvironments == "") {
                                           $("#modal-published-header").hide();
                                           $("#modal-published-content").hide();
                                       }
                                       if (failedToUnpublishedEnvironments == "") {
                                           $("#modal-unpublished-header").hide();
                                           $("#modal-unpublished-content").hide();
                                       }
                                       $("#retryType").val("manage");
                                       $("#environmentsRetry-modal").modal('show');
                                   }
                                   else {
                                       //jagg.message({content:responseText.message,type:"error"});
                                       alert("ERROR");
                                   }
                               }
                           }
                       },
                       dataType: "json"
                   });
        };

        $("#manage_form").validate({
                                               submitHandler: function (form) {
                                                   $('#submit').attr('disabled', 'disabled');
                                                   if (!validate_tiers()) {
                                                       return false;
                                                   }
                                                   var designer = APIMangerAPI.APIDesigner();
                                                   $('#swagger').val(JSON.stringify(designer.api_doc));
                                                   $('#saveMessage').show();
                                                   $('#saveButtons').hide();
                                                   $(form).ajaxSubmit({
                                                                          success: function (responseText, statusText, xhr,
                                                                                $form) {
                                                                              $('#saveMessage').hide();
                                                                              $('#saveButtons').show();
                                                                              if (!responseText.error) {
                                                                                $("body").trigger("api_saved");
                                                                              } else {
                                                                                if (responseText.message == "timeout") {
                                                                                if (ssoEnabled) {
                                                                                var currentLoc = window.location.pathname;
                                                                                if (currentLoc.indexOf(".jag") >= 0) {
                                                                                location.href = "index.jag";
                                                                                } else {
                                                                                location.href = 'site/pages/index.jag';
                                                                                }
                                                                                } else {
                                                                                jagg.showLogin();
                                                                                }
                                                                                } else {
                                                                                var message = responseText.message;
                                                                                if (message.split("||")[1] == "warning") {
                                                                                var environmentsFailed = JSON.parse(message.split("||")[0]);
                                                                                var failedToPublishEnvironments = environmentsFailed.PUBLISHED;
                                                                                var failedToUnpublishedEnvironments = environmentsFailed.UNPUBLISHED;
                                                                                var divPublish = "", divUnpublished = "";
                                                                                for (i = 0; i < failedToPublishEnvironments.split(",").length; i++) {
                                                                                divPublish += failedToPublishEnvironments.split(",")[i] + "
";
                                                                                }
                                                                                for (i = 0; i < failedToUnpublishedEnvironments.split(",").length; i++) {
                                                                                divUnpublished += failedToUnpublishedEnvironments.split(",")[i] + "
";
                                                                                }
                                                                                $("#modal-published-content").empty();
                                                                                $("#modal-unpublished-content").empty();
                                                                                $("#modal-published-content").append(divPublish);
                                                                                $("#modal-unpublished-content").append(divUnpublished);
                                                                                if (failedToPublishEnvironments == "") {
                                                                                $("#modal-published-header").hide();
                                                                                $("#modal-published-content").hide();
                                                                                }
                                                                                if (failedToUnpublishedEnvironments == "") {
                                                                                $("#modal-unpublished-header").hide();
                                                                                $("#modal-unpublished-content").hide();
                                                                                }
                                                                                $("#retryType").val("lifeCycle");
                                                                                $("#environmentsRetry-modal").modal('show');
                                                                                }
                                                                                else {
                                                                                jagg.message({
                                                                                content: responseText.message,
                                                                                type: "error"
                                                                                });
                                                                                }
                                                                                }
                                                                              }
                                                                          }, dataType: 'json'
                                                                      });
                                               }
                                           });

        var publishAPI = function () {
            var data = {};
            $("body").off('api_saved');
            if (store.publisher.api.lifeState == 'PUBLISHED') {
                data = {
                    action: "updateStatus",
                    name: store.publisher.api.name,
                    version: store.publisher.api.version,
                    provider: store.publisher.api.provider,
                    status: "PUBLISHED",
                    publishToGateway: true,
                    requireResubscription: true
                };
                $.ajax({
                           url: caramel.context + '/apis/asset/' + store.publisher.api.id + '/lifecycle?type=api',
                           type: 'POST',
                           data: JSON.stringify(data),
                           contentType: 'application/json',
                           success: function (data) {
                               BootstrapDialog.alert('Successfully Changed the life cycle state');
                           },
                           error: function (data) {
                               BootstrapDialog.alert('Error while changing the life cycle state');
                           }
                       });
            } else {
                data.action = 'publish';
                data.nextState = 'published';
                data.comment = "Changed API Status";
                $.ajax({
                           url: caramel.context + '/apis/asset/' + store.publisher.api.id + '/change-state?type=api&lifecycle=' + store.publisher.api.lifeCycle,
                           type: 'POST',
                           data: JSON.stringify(data),
                           contentType: 'application/json',
                           success: function (data) {
                               store.publisher.api.lifeState = 'PUBLISHED';
                               BootstrapDialog.alert('Successfully Changed the life cycle state');
                           },
                           error: function (data) {
                               BootstrapDialog.alert('Error while changing the life cycle state');
                           }
                       });
            }
        };

        //hack to validate tiers
        function validate_tiers() {
            var selectedValues = $('#tier').val();
            if (selectedValues && selectedValues.length > 0) {
                $("button.multiselect").removeClass('error-multiselect');
                $("#tier_error").remove();
                return true;
            }
            //set error
            $("button.multiselect").addClass('error-multiselect').after('This field is required.').focus();
            return false;
        }
    });
});
<commit_msg>minor fix to call backend api life cycle service<commit_after>$(function () {

    var swaggerUrl = caramel.context + "/asts/api/apis/swagger?provider=" + store.publisher.api.provider + "&name=" + store.publisher.api.name + "&version=" + store.publisher.api.version;
    $(document).ready(function () {
        $.ajaxSetup({
                        contentType: "application/x-www-form-urlencoded; charset=utf-8"
                    });

        $.get(swaggerUrl, function (data) {
            var designer = new APIMangerAPI.APIDesigner();
            designer.load_api_document(data.data);
            designer.set_default_management_values();
            designer.render_resources();
            $("#swaggerUpload").modal('hide');
        });

        $("#manage_form_1").submit(function (e) {
            e.preventDefault();
        });

        $('#save_api').click(function (e) {
            $this = $(this).attr('id');
        });

        $('#responseCache').change(function () {
            var cache = $('#responseCache').find(":selected").val();
            if (cache == "enabled") {
                $('#cacheTimeout').show();
            }
            else {
                $('#cacheTimeout').hide();
            }
        });

        $('input').on('change', function () {
            var values = $('input:checked.env').map(function () {
                return this.value;
            }).get();
            if (values == "") {
                values = "none";
            }
            $('#environments').val(values.toString());
        });

        function doGatewayAction() {
            var type = $("#retryType").val();
            if (type == "manage") {
                $("#environmentsRetry-modal").modal('hide');
                $("body").trigger("api_saved");
                location.href = "";//TODO
            } else {
                location.href = "";//TODO
            }
        }

        $('#publish_api').click(function (e) {
            $("body").on("api_saved", publishAPI);
            $("#manage_form").submit();
            return false;
        });

        var publish_api = function (e) {
            $.ajax({
                       type: "POST",
                       url: "",
                       async: false,
                       data: {
                           action: "updateStatus",
                           name: store.publisher.api.name,
                           version: store.publisher.api.version,
                           provider: store.publisher.api.provider,
                           status: "PUBLISHED",
                           publishToGateway: true,
                           requireResubscription: true
                       },
                       success: function (responseText) {
                           if (!responseText.error) {
                               //jagg.message({content:"API Published",type:"info"});
                               alert("Error");
                               location.href = "TODO";
                           } else {
                               if (responseText.message == "timeout") {
                                   if (ssoEnabled) {
                                       var currentLoc = window.location.pathname;
                                       if (currentLoc.indexOf(".jag") >= 0) {
                                           location.href = "index.jag";
                                       } else {
                                           location.href = 'site/pages/index.jag';
                                       }
                                   } else {
                                       jagg.showLogin();
                                   }
                               } else {
                                   var message = responseText.message;
                                   if (message.split("||")[1] == "warning") {
                                       var environmentsFailed = JSON.parse(message.split("||")[0]);
                                       var failedToPublishEnvironments = environmentsFailed.PUBLISHED;
                                       var failedToUnpublishedEnvironments = environmentsFailed.UNPUBLISHED;
                                       var divPublish = "", divUnpublished = "";
                                       for (i = 0; i < failedToPublishEnvironments.split(",").length; i++) {
                                           divPublish += failedToPublishEnvironments.split(",")[i] + "
";
                                       }
                                       for (i = 0; i < failedToUnpublishedEnvironments.split(",").length; i++) {
                                           divUnpublished += failedToUnpublishedEnvironments.split(",")[i] + "
";
                                       }
                                       $("#modal-published-content").empty();
                                       $("#modal-unpublished-content").empty();
                                       $("#modal-published-content").append(divPublish);
                                       $("#modal-unpublished-content").append(divUnpublished);
                                       if (failedToPublishEnvironments == "") {
                                           $("#modal-published-header").hide();
                                           $("#modal-published-content").hide();
                                       }
                                       if (failedToUnpublishedEnvironments == "") {
                                           $("#modal-unpublished-header").hide();
                                           $("#modal-unpublished-content").hide();
                                       }
                                       $("#retryType").val("manage");
                                       $("#environmentsRetry-modal").modal('show');
                                   }
                                   else {
                                       //jagg.message({content:responseText.message,type:"error"});
                                       alert("ERROR");
                                   }
                               }
                           }
                       },
                       dataType: "json"
                   });
        };

        $("#manage_form").validate({
                                       submitHandler: function (form) {
                                           $('#submit').attr('disabled', 'disabled');
                                           if (!validate_tiers()) {
                                               return false;
                                           }
                                           var designer = APIMangerAPI.APIDesigner();
                                           $('#swagger').val(JSON.stringify(designer.api_doc));
                                           $('#saveMessage').show();
                                           $('#saveButtons').hide();
                                           $(form).ajaxSubmit({
                                                                  success: function (responseText, statusText, xhr,
                                                                                $form) {
                                                                      $('#saveMessage').hide();
                                                                      $('#saveButtons').show();
                                                                      if (!responseText.error) {
                                                                          $("body").trigger("api_saved");
                                                                      } else {
                                                                          if (responseText.message == "timeout") {
                                                                              if (ssoEnabled) {
                                                                                var currentLoc = window.location.pathname;
                                                                                if (currentLoc.indexOf(".jag") >= 0) {
                                                                                location.href = "index.jag";
                                                                                } else {
                                                                                location.href = 'site/pages/index.jag';
                                                                                }
                                                                              } else {
                                                                                jagg.showLogin();
                                                                              }
                                                                          } else {
                                                                              var message = responseText.message;
                                                                              if (message.split("||")[1] == "warning") {
                                                                                var environmentsFailed = JSON.parse(message.split("||")[0]);
                                                                                var failedToPublishEnvironments = environmentsFailed.PUBLISHED;
                                                                                var failedToUnpublishedEnvironments = environmentsFailed.UNPUBLISHED;
                                                                                var divPublish = "", divUnpublished = "";
                                                                                for (i = 0; i < failedToPublishEnvironments.split(",").length; i++) {
                                                                                divPublish += failedToPublishEnvironments.split(",")[i] + "
";
                                                                                }
                                                                                for (i = 0; i < failedToUnpublishedEnvironments.split(",").length; i++) {
                                                                                divUnpublished += failedToUnpublishedEnvironments.split(",")[i] + "
";
                                                                                }
                                                                                $("#modal-published-content").empty();
                                                                                $("#modal-unpublished-content").empty();
                                                                                $("#modal-published-content").append(divPublish);
                                                                                $("#modal-unpublished-content").append(divUnpublished);
                                                                                if (failedToPublishEnvironments == "") {
                                                                                $("#modal-published-header").hide();
                                                                                $("#modal-published-content").hide();
                                                                                }
                                                                                if (failedToUnpublishedEnvironments == "") {
                                                                                $("#modal-unpublished-header").hide();
                                                                                $("#modal-unpublished-content").hide();
                                                                                }
                                                                                $("#retryType").val("lifeCycle");
                                                                                $("#environmentsRetry-modal").modal('show');
                                                                              }
                                                                              else {
                                                                                jagg.message({
                                                                                content: responseText.message,
                                                                                type: "error"
                                                                                });
                                                                              }
                                                                          }
                                                                      }
                                                                  }, dataType: 'json'
                                                              });
                                       }
                                   });

        var publishAPI = function () {
            var data = {};
            $("body").off('api_saved');
            if (store.publisher.api.lifeState.toUpperCase() == 'PUBLISHED') {
                data = {
                    action: "updateStatus",
                    name: store.publisher.api.name,
                    version: store.publisher.api.version,
                    provider: store.publisher.api.provider,
                    status: "PUBLISHED",
                    publishToGateway: true,
                    requireResubscription: true
                };
                $.ajax({
                           url: caramel.context + '/asts/api/apis/' + store.publisher.api.id + '/lifecycle?type=api',
                           type: 'POST',
                           data: JSON.stringify(data),
                           contentType: 'application/json',
                           success: function (data) {
                               BootstrapDialog.alert('Successfully Changed the life cycle state');
                           },
                           error: function (data) {
                               BootstrapDialog.alert('Error while changing the life cycle state');
                           }
                       });
            } else {
                data.action = 'publish';
                data.nextState = 'published';
                data.comment = "Changed API Status";
                $.ajax({
                           url: caramel.context + '/apis/asset/' + store.publisher.api.id + '/change-state?type=api&lifecycle=' + store.publisher.api.lifeCycle,
                           type: 'POST',
                           data: JSON.stringify(data),
                           contentType: 'application/json',
                           success: function (data) {
                               store.publisher.api.lifeState = 'PUBLISHED';
                               BootstrapDialog.alert('Successfully Changed the life cycle state');
                           },
                           error: function (data) {
                               BootstrapDialog.alert('Error while changing the life cycle state');
                           }
                       });
            }
        };

        //hack to validate tiers
        function validate_tiers() {
            var selectedValues = $('#tier').val();
            if (selectedValues && selectedValues.length > 0) {
                $("button.multiselect").removeClass('error-multiselect');
                $("#tier_error").remove();
                return true;
            }
            //set error
            $("button.multiselect").addClass('error-multiselect').after('This field is required.').focus();
            return false;
        }
    });
});
<|endoftext|>


<commit_before>// This is the Brocfile. It sets up all the assets from the input JS/CSS/images
// and so on and converts them to static assets in the output directory or
// preview server.
var _               = require('underscore');
var babel           = require('broccoli-babel-transpiler');
var browserify      = require('broccoli-browserify');
var concat          = require('broccoli-concat');
var compileSass     = require('broccoli-sass');
var funnel          = require('broccoli-funnel');
var gzip            = require('broccoli-gzip');
var jade            = require('broccoli-jade');
var mergeTrees      = require('broccoli-merge-trees');
var templateBuilder = require('broccoli-template-builder');
var uglify          = require('broccoli-uglify-sourcemap');

var sassDir = 'app/styles';
var scripts = 'app/scripts';

// Covert main.scss stylesheet to app.css stylesheet in output directory
var styles = compileSass([sassDir], 'main.scss', 'app.css');

// Process all the JavaScript.
// First we use babel to convert the ES6 to ES5 for web browsers.
scripts = babel(scripts);
// Then use browserify to handle any `require` statements and automatically
// insert the required library inline.
scripts = browserify(scripts, {
  entries: ['./app.js'],
  outputFile: 'app.js'
});

// == Funnel external libraries into individual trees ==
var defaultOptions = {
  include: [
    "**/*.css",
    "**/*.js",
    "**/*.map"
  ]
};

var bootstrap   = funnel('node_modules/bootstrap/dist', defaultOptions);
var fontAwesome = funnel('node_modules/font-awesome', defaultOptions);
var jquery      = funnel('node_modules/jquery/dist', defaultOptions);
var leaflet     = funnel('node_modules/leaflet/dist', defaultOptions);
var q           = funnel('node_modules/q', defaultOptions);
var underscore  = funnel('node_modules/underscore', defaultOptions);
var vendor      = funnel('vendor', defaultOptions);

var libraryTree = mergeTrees([
  bootstrap,
  fontAwesome,
  jquery,
  leaflet,
  q,
  underscore,
  vendor
]);

// == Concatenate script trees ==
// Use inputFiles to specify loading order.

var allScripts = concat(mergeTrees([
  libraryTree,
  scripts
]), {
  inputFiles: [
    'q.js',
    'jquery.js',
    'underscore.js',
    'leaflet-src.js',
    'app.js'
  ],
  outputFile: 'app.js'
});

// Apply uglify to minify the javascript in production.
// (The process is too slow to do this on-the-fly in development.)
if (process.env["NODE_ENV"] === "production") {
  allScripts = uglify(allScripts);
}

// == Concatenate style trees ==
// Use inputFiles to specify loading order.

var allStyles = concat(mergeTrees([
  libraryTree,
  styles
]), {
  inputFiles: [
    'css/bootstrap.css',
    'css/font-awesome.css',
    'leaflet.css',
    'app.css'
  ],
  outputFile: 'style.css',
  sourceMapConfig: {
    extensions: ['css'],
    mapCommentType: 'block'
  }
});

// == Funnel external assets into individual trees ==

var faFonts = funnel('node_modules/font-awesome/fonts', {
  destDir: 'fonts'
});

var leafletAssets = funnel('node_modules/leaflet/dist/images', {
  destDir: 'images'
});

var vendorAssets = funnel('vendor/images', {
  destDir: 'images'
});

// This builds all the Javascript Templates (JST) into JS files where the
// templates have been wrapped in functions using underscore's template system.
var templates = templateBuilder('app/templates', {
  extensions: ['jst'],
  outputFile: 'templates.js',
  compile: function(string) {
    return _.template(string, { variable: "obj" }).source;
  }
});

// Compile view files
var views = jade('app/views');

// Build gzipped versions of the files, but only in production.
var doGZIP;
if (process.env["NODE_ENV"] === "production") {
  doGZIP = gzip;
} else {
  doGZIP = function(node) { return node; };
}

module.exports = doGZIP(mergeTrees([views, templates, vendorAssets,
  faFonts,
  leafletAssets,
  allStyles,
  allScripts
]), {
  extensions: ['css', 'html', 'js']
});
<commit_msg>Disable source map configs<commit_after>// This is the Brocfile. It sets up all the assets from the input JS/CSS/images
// and so on and converts them to static assets in the output directory or
// preview server.
var _               = require('underscore');
var babel           = require('broccoli-babel-transpiler');
var browserify      = require('broccoli-browserify');
var concat          = require('broccoli-concat');
var compileSass     = require('broccoli-sass');
var funnel          = require('broccoli-funnel');
var gzip            = require('broccoli-gzip');
var jade            = require('broccoli-jade');
var mergeTrees      = require('broccoli-merge-trees');
var templateBuilder = require('broccoli-template-builder');
var uglify          = require('broccoli-uglify-sourcemap');

var sassDir = 'app/styles';
var scripts = 'app/scripts';

// Covert main.scss stylesheet to app.css stylesheet in output directory
var styles = compileSass([sassDir], 'main.scss', 'app.css');

// Process all the JavaScript.
// First we use babel to convert the ES6 to ES5 for web browsers.
scripts = babel(scripts);
// Then use browserify to handle any `require` statements and automatically
// insert the required library inline.
scripts = browserify(scripts, {
  entries: ['./app.js'],
  outputFile: 'app.js'
});

// == Funnel external libraries into individual trees ==
var defaultOptions = {
  include: [
    "**/*.css",
    "**/*.js",
    "**/*.map"
  ]
};

var bootstrap   = funnel('node_modules/bootstrap/dist', defaultOptions);
var fontAwesome = funnel('node_modules/font-awesome', defaultOptions);
var jquery      = funnel('node_modules/jquery/dist', defaultOptions);
var leaflet     = funnel('node_modules/leaflet/dist', defaultOptions);
var q           = funnel('node_modules/q', defaultOptions);
var underscore  = funnel('node_modules/underscore', defaultOptions);
var vendor      = funnel('vendor', defaultOptions);

var libraryTree = mergeTrees([
  bootstrap,
  fontAwesome,
  jquery,
  leaflet,
  q,
  underscore,
  vendor
]);

// == Concatenate script trees ==
// Use inputFiles to specify loading order.

var allScripts = concat(mergeTrees([
  libraryTree,
  scripts
]), {
  inputFiles: [
    'q.js',
    'jquery.js',
    'underscore.js',
    'leaflet-src.js',
    'app.js'
  ],
  outputFile: 'app.js'
});

// Apply uglify to minify the javascript in production.
// (The process is too slow to do this on-the-fly in development.)
if (process.env["NODE_ENV"] === "production") {
  allScripts = uglify(allScripts);
}

// == Concatenate style trees ==
// Use inputFiles to specify loading order.

var allStyles = concat(mergeTrees([
  libraryTree,
  styles
]), {
  inputFiles: [
    'css/bootstrap.css',
    'css/font-awesome.css',
    'leaflet.css',
    'app.css'
  ],
  outputFile: 'style.css',
  sourceMapConfig: {
    enabled: false,
    extensions: ['css'],
    mapCommentType: 'block'
  }
});

// == Funnel external assets into individual trees ==

var faFonts = funnel('node_modules/font-awesome/fonts', {
  destDir: 'fonts'
});

var leafletAssets = funnel('node_modules/leaflet/dist/images', {
  destDir: 'images'
});

var vendorAssets = funnel('vendor/images', {
  destDir: 'images'
});

// This builds all the Javascript Templates (JST) into JS files where the
// templates have been wrapped in functions using underscore's template system.
var templates = templateBuilder('app/templates', {
  extensions: ['jst'],
  outputFile: 'templates.js',
  compile: function(string) {
    return _.template(string, { variable: "obj" }).source;
  }
});

// Compile view files
var views = jade('app/views');

// Build gzipped versions of the files, but only in production.
var doGZIP;
if (process.env["NODE_ENV"] === "production") {
  doGZIP = gzip;
} else {
  doGZIP = function(node) { return node; };
}

module.exports = doGZIP(mergeTrees([views, templates, vendorAssets,
  faFonts,
  leafletAssets,
  allStyles,
  allScripts
]), {
  extensions: ['css', 'html', 'js']
});
<|endoftext|>