<commit_before>import Reflux from 'reflux';
import StateMixin from 'reflux-state-mixin';
import {{pascalcase name}}Actions from 'actions';

const debug = require('debug')('mongodb-compass:stores:{{slugcase name}}');

/**
 * {{capitalcase name}} store.
 */
const {{pascalcase name}}Store = Reflux.createStore({
  /**
   * adds a state to the store, similar to React.Component's state
   * @see https://github.com/yonatanmn/Super-Simple-Flux#reflux-state-mixin
   *
   * If you call `this.setState({...})` this will cause the store to trigger
   * and push down its state as props to connected components.
   */
  mixins: [StateMixin.store],

  /**
   * listen to all actions defined in ../actions/index.jsx
   */
  listenables: {{pascalcase name}}Actions,

  /**
   * Initialize everything that is not part of the store's state.
   */
  init() {
  },

  /**
   * This method is called when all plugins are activated. You can register
   * listeners to other plugins' stores here, e.g.
   *
   * appRegistry.getStore('OtherPlugin.Store').listen(this.otherStoreChanged.bind(this));
   *
   * If this plugin does not depend on other stores, you can delete the method.
   *
   * @param {Object} appRegistry   app registry containing all stores and components
   */
  onActivated() {
  },

  /**
   * This method is called when the data service is finished connecting. You
   * receive either an error or the connected data service object, and if the
   * connection was successful you can now make calls to the database, e.g.
   *
   * dataService.command('admin', {connectionStatus: 1}, this.handleStatus.bind(this));
   *
   * If this plugin does not need to talk to the database, you can delete this
   * method.
   *
   * @param {Object} error         the error object if connection was unsuccessful
   * @param {Object} dataService   the dataService object if connection was successful
   *
   */
  onConnected() {
  },

  /**
   * Initialize the {{capitalcase name}} store state. The returned object must
   * contain all keys that you might want to modify with this.setState().
   *
   * @return {Object} initial store state.
   */
  getInitialState() {
    return {
      status: 'enabled'
    };
  },

  /**
   * handlers for each action defined in ../actions/index.jsx, for example:
   */
  toggleStatus() {
    this.setState({
      status: this.state.status === 'enabled' ? 'disabled' : 'enabled'
    });
  },

  /**
   * log changes to the store as debug messages.
   * @param  {Object} prevState   previous state.
   */
  storeDidUpdate(prevState) {
    debug('{{pascalcase name}} store changed from', prevState, 'to', this.state);
  }
});

export default {{pascalcase name}}Store;
export { {{pascalcase name}}Store };
<commit_msg>Update to show new app registry emitter<commit_after>import Reflux from 'reflux';
import StateMixin from 'reflux-state-mixin';
import {{pascalcase name}}Actions from 'actions';

const debug = require('debug')('mongodb-compass:stores:{{slugcase name}}');

/**
 * {{capitalcase name}} store.
 */
const {{pascalcase name}}Store = Reflux.createStore({
  /**
   * adds a state to the store, similar to React.Component's state
   * @see https://github.com/yonatanmn/Super-Simple-Flux#reflux-state-mixin
   *
   * If you call `this.setState({...})` this will cause the store to trigger
   * and push down its state as props to connected components.
   */
  mixins: [StateMixin.store],

  /**
   * listen to all actions defined in ../actions/index.jsx
   */
  listenables: {{pascalcase name}}Actions,

  /**
   * Initialize everything that is not part of the store's state.
   */
  init() {
  },

  /**
   * This method is called when all plugins are activated. You can register
   * listeners to other plugins' stores here, e.g.
   *
   * appRegistry.getStore('OtherPlugin.Store').listen(this.otherStoreChanged.bind(this));
   *
   * If this plugin does not depend on other stores, you can delete the method.
   *
   * @param {Object} appRegistry - app registry containing all stores and components
   */
  onActivated(appRegistry) {
    // Events emitted from the app registry:
    // appRegistry.on('application-intialized', (version) => return true);
    // appRegistry.on('data-service-intialized', (dataService) => return true);
    // appRegistry.on('data-service-connected', (error, dataService) => return true);
    // appRegistry.on('collection-changed', (namespace) => return true);
    // appRegistry.on('database-changed', (namespace) => return true);
    // appRegistry.on('query-applied', (queryState) => return true);
  },

  /**
   * Initialize the {{capitalcase name}} store state. The returned object must
   * contain all keys that you might want to modify with this.setState().
   *
   * @return {Object} initial store state.
   */
  getInitialState() {
    return {
      status: 'enabled'
    };
  },

  /**
   * handlers for each action defined in ../actions/index.jsx, for example:
   */
  toggleStatus() {
    this.setState({
      status: this.state.status === 'enabled' ? 'disabled' : 'enabled'
    });
  },

  /**
   * log changes to the store as debug messages.
   * @param  {Object} prevState   previous state.
   */
  storeDidUpdate(prevState) {
    debug('{{pascalcase name}} store changed from', prevState, 'to', this.state);
  }
});

export default {{pascalcase name}}Store;
export { {{pascalcase name}}Store };
<|endoftext|>


<commit_before>var turn=0;
var activePlayer=-1;
var cards=new Array();
var gameNumber=0;
var votes=0;

function Card(color,value) {

	this.color = color;
	this.value = value;
	switch(parseInt(color))
	{
		case 0:this.colortext="Red";break;
		case 1:this.colortext="Green";break;
		case 2:this.colortext="Blue";break;
		case 3:this.colortext="Yellow";break;
		case 4:this.colortext="Wild";break;
		default:this.colortext="Error";
	}
	switch(parseInt(value))
	{
		case 10:this.valuetext="";break;
		case 11:this.valuetext="+2";break;
		case 12:this.valuetext="";break;
		case 13:this.valuetext="";break;
		case 14:this.valuetext="+4";break;
		default:this.valuetext=value;
	}
}

Card.prototype.render = function() {
	$("#cardPile").html(
		'
' +
		'
' +
		this.value +
		'
' +
		'
' +
		this.value +
		'
' +
		'
' +
		this.value +
		'
' +
		'
');
}

function updateCurrentPlayers(players) {
	$("#currentPlayers").html("");
	for (x in players) {
		var active="";
		if (x==activePlayer) {active=" active";}
		$("#currentPlayers").append(
			"
"
			+"
"
			+players[x]+"
"
			+((cards && cards.length>x)?(" "+cards[x]+""):"")
			+"
"
		);
	}
}

function updateVotes(votes) {
	$("#votes").html("Votos: "+votes);
}

function recieveCard(color,value) {
	(new Card(color,value)).render();
}

function update() {
	$.getJSON("http://localhost:3000/status?callback=?", function(data) {
		console.log(data);
		if (data.h) {
			recieveCard(data.h.c,data.h.t);
		}
		if (data.p!==undefined) {
			activePlayer=data.p;
		}
		cards=data.c;
	});
	$.getJSON("http://localhost:3000/lobby?callback=?", function(data) {
		if (data.p) {
			updateCurrentPlayers(data.p);
		}
		if (data.tv) {
			updateVotes(data.tv);
		}
	});
	setTimeout(update,1000);
}

update();
<commit_msg>Optimizacoes as chamadas ao servidor<commit_after>var turn=0;
var activePlayer=-1;
var cards=new Array();
var gameNumber=0;
var votes=0;

function Card(color,value) {

	this.color = color;
	this.value = value;
	switch(parseInt(color))
	{
		case 0:this.colortext="Red";break;
		case 1:this.colortext="Green";break;
		case 2:this.colortext="Blue";break;
		case 3:this.colortext="Yellow";break;
		case 4:this.colortext="Wild";break;
		default:this.colortext="Error";
	}
	switch(parseInt(value))
	{
		case 10:this.valuetext="";break;
		case 11:this.valuetext="+2";break;
		case 12:this.valuetext="";break;
		case 13:this.valuetext="";break;
		case 14:this.valuetext="+4";break;
		default:this.valuetext=value;
	}
}

Card.prototype.render = function() {
	$("#cardPile").html(
		'
' +
		'
' +
		this.value +
		'
' +
		'
' +
		this.value +
		'
' +
		'
' +
		this.value +
		'
' +
		'
');
}

function updateCurrentPlayers(players) {
	$("#currentPlayers").html("");
	for (x in players) {
		var active="";
		if (x==activePlayer) {active=" active";}
		$("#currentPlayers").append(
			"
"
			+"
"
			+players[x]+"
"
			+((cards && cards.length>x)?(" "+cards[x]+""):"")
			+"
"
		);
	}
}

function updateVotes(votes,players) {
	$("#votes").html("Votos: "+votes+"/"+players);
}

function recieveCard(color,value) {
	(new Card(color,value)).render();
}

function updateStatus() {
	$.getJSON("http://localhost:3000/status?callback=?", function(data) {
		if (data.h) {
			recieveCard(data.h.c,data.h.t);
		}
		if (data.p!==undefined) {
			activePlayer=data.p;
		}
		cards=data.c;
		setTimeout(updateStatus,1000);
	});
}

function updateLobby() {
	$.getJSON("http://localhost:3000/lobby?callback=?", function(data) {
		console.log(data);
		if (data.p) {
			updateCurrentPlayers(data.p);
		}
		if (data.tv) {
			updateVotes(data.tv,data.ps);
		}
		if (data.s==0) {
			setTimeout(updateLobby,1000);
		}
	});
}

updateLobby();
updateStatus();
<|endoftext|>


<commit_before>$(w).resize(function(){ //Update dimensions on resize
	sw = document.body.clientWidth;
	sh = document.body.clientHeight;
	checkMobile();
});

//Check if Mobile
function checkMobile() {
  mobile = (sw > breakpoint) ? false : true;

    if (!mobile) { //If Not Mobile
        loadAux();
	$('.aux header a').addClass('disabled').addClass('open');
	$('[role="tabpanel"],#nav,#search').show(); //Show full navigation and search
     } else { //Hide
              if(!$('#nav-anchors a').hasClass('active')) {
                    $('#nav,#search').hide(); //Hide full navigation and search
               }
     }
}
<commit_msg>Added buildGallery function<commit_after>$(w).resize(function(){ //Update dimensions on resize
	sw = document.body.clientWidth;
	sh = document.body.clientHeight;
	checkMobile();
});

//Check if Mobile
function checkMobile() {
  mobile = (sw > breakpoint) ? false : true;

    if (!mobile) { //If Not Mobile
        loadAux();
	$('.aux header a').addClass('disabled').addClass('open');
	$('[role="tabpanel"],#nav,#search').show(); //Show full navigation and search
     } else { //Hide
              if(!$('#nav-anchors a').hasClass('active')) {
                    $('#nav,#search').hide(); //Hide full navigation and search
               }
     }
}

function buildGallery() {
	container.html('

');
	imgList = $('#img-list');
	nav.find('a:first').addClass('active');

	//For Each Navigation Link
	nav.find('a').each(function() {
		 var $this = $(this);
	         var href = $this.attr('href');

		  //Prepare list item with image source in data attribute
		  arr += '

';
	 });

	 //Append to #img-list
	 imgList.find('ul').append(arr);

	 //Nav Thumbnail Click
	 nav.on('click, 'a', function(e) {
		var pos = $(this).parent().index();
		e.preventDefault();
		loadImg(pos);
		if(swipeEnabled) {
			mySwipe.slide(index, 300);
		}
		updateNav(pos);
	});
}
<|endoftext|>


<commit_before>"use strict";

import fastApply from "fast-apply";
import libUrl from "url";
import urlTransform from "./urlTransform";
import merge from "./utils/merge";
import get from "./utils/get";
import fetchResolver from "./fetchResolver";
import PubSub from "./PubSub";
import createHolder from "./createHolder";

function none() {}

function extractArgs(args) {
  let pathvars;
  let params={};
  let callback;
  if (args[0] instanceof Function) {
    callback = args[0];
  } else if (args[1] instanceof Function) {
    pathvars = args[0];
    callback = args[1];
  } else {
    pathvars = args[0];
    params = args[1];
    callback = args[2] || none;
  }
  return [pathvars, params, callback];
}

function helperCrudFunction(name) {
  return (...args)=> {
    const [pathvars, params, cb] = extractArgs(args);
    return [pathvars, { ...params, method: name.toUpperCase() }, cb];
  };
}

function defaultMiddlewareArgsParser(dispatch, getState) {
  return { dispatch, getState };
}

export const CRUD = ["get", "post", "put", "delete", "patch"].reduce(
  (memo, name)=> {
    memo[name] = helperCrudFunction(name);
    return memo;
  }, {});

/**
 * Constructor for create action
 * @param  {String} url          endpoint's url
 * @param  {String} name         action name
 * @param  {Object} options      action configuration
 * @param  {Object} ACTIONS      map of actions
 * @param  {[type]} fetchAdapter adapter for fetching data
 * @return {Function+Object}     action function object
 */
export default function actionFn(url, name, options, ACTIONS={}, meta={}) {
  const { actionFetch, actionSuccess, actionFail, actionReset } = ACTIONS;
  const pubsub = new PubSub();
  const requestHolder = createHolder();
  const responseHandler = meta && meta.holder && meta.holder.responseHandler;
  /**
   * Fetch data from server
   * @param  {Object}   pathvars    path vars for url
   * @param  {Object}   params      fetch params
   * @param  {Function} getState    helper meta function
  */
  const request = (pathvars, params, getState=none)=> {
    const resultUrlT = urlTransform(url, pathvars, meta.urlOptions);
    const rootUrl = meta.holder ? meta.holder.rootUrl : null;
    let urlT = resultUrlT;
    if (rootUrl) {
      const urlObject = libUrl.parse(urlT);
      if (!urlObject.host) {
        const urlPath = (rootUrl.path ? rootUrl.path.replace(/\/$/, "") : "") +
          "/" + (urlObject.path ? urlObject.path.replace(/^\//, "") : "");
        urlT = `${rootUrl.protocol}//${rootUrl.host}${urlPath}`;
      }
    }
    const globalOptions = !meta.holder ? {} :
      (meta.holder.options instanceof Function) ?
        meta.holder.options(urlT, params, getState) : (meta.holder.options);
    const baseOptions = (options instanceof Function) ?
      options(urlT, params, getState) :
      options;
    const opts = merge({}, globalOptions, baseOptions, params);
    const response = meta.fetch(urlT, opts);
    const result = !meta.validation ? response : response.then(
      data=> new Promise(
        (resolve, reject)=> meta.validation(data,
          err=> err ? reject(err) : resolve(data))));
    if (responseHandler) {
      if (result && result.then) {
        result.then(
          data=> responseHandler(null, data),
          err=> responseHandler(err)
        );
      } else {
        responseHandler(result);
      }
    }
    result && result.catch && result.catch(none);
    return result;
  };

  /**
   * Fetch data from server
   * @param  {Object}   pathvars    path vars for url
   * @param  {Object}   params      fetch params
   * @param  {Function} callback)   callback execute after end request
   */
  function fn(...args) {
    const [pathvars, params, callback] = extractArgs(args);
    const syncing = params ? !!params.syncing : false;
    params && delete params.syncing;
    pubsub.push(callback);
    return (...middlewareArgs)=> {
      const middlewareParser = (meta.holder && meta.holder.middlewareParser) ||
        defaultMiddlewareArgsParser;
      const { dispatch, getState } = middlewareParser(...middlewareArgs);
      const { reducerName, prefix } = meta;
      const state = getState();
      const isLoading = get(state, prefix, reducerName, "loading");
      if (isLoading) {
        return;
      }
      const requestOptions = { pathvars, params };
      const prevData =  get(state, prefix, reducerName, "data");
      dispatch({ type: actionFetch, syncing, request: requestOptions });
      const fetchResolverOpts = {
        dispatch,
        getState,
        actions: meta.actions,
        prefetch: meta.prefetch
      };
      const result = new Promise((done, fail)=> {
        fetchResolver(0, fetchResolverOpts, (err)=> {
          if (err) {
            pubsub.reject(err);
            return fail(err);
          }
          new Promise((resolve, reject)=> {
            requestHolder.set({
              resolve,
              reject,
              promise: request(pathvars, params, getState).then(resolve, reject)
            });
          }).then((d)=> {
            requestHolder.pop();
            const data = meta.transformer(d, prevData, {
              type: actionSuccess, request: requestOptions
            });
            dispatch({
              data,
              origData: d,
              type: actionSuccess,
              syncing: false,
              request: requestOptions
            });
            if (meta.broadcast) {
              meta.broadcast.forEach((type)=> {
                dispatch({ type, data, origData: d, request: requestOptions });
              });
            }
            if (meta.postfetch) {
              meta.postfetch.forEach((postfetch)=> {
                (postfetch instanceof Function) && postfetch({
                  data, getState, dispatch, actions: meta.actions, request: requestOptions
                });
              });
            }
            pubsub.resolve(data);
            done(data);
          }, (error)=> {
            dispatch({ type: actionFail, syncing: false, error, request: requestOptions });
            pubsub.reject(error);
            fail(error);
          });
        });
      });
      result.catch(none);
      return result;
    };
  }

  /*
    Pure rest request
   */
  fn.request = request;

  /**
   * Reset store to initial state
   */
  fn.reset = (mutation)=> {
    const defer = requestHolder.pop();
    defer && defer.reject(new Error("Application abort request"));
    return mutation === "sync" ? { type: actionReset, mutation } : { type: actionReset };
  };

  /**
   * Sync store with server. In server mode works as usual method.
   * If data have already synced, data would not fetch after call this method.
   * @param  {Object} pathvars    path vars for url
   * @param  {Object} params      fetch params
   * @param  {Function} callback) callback execute after end request
   */
  fn.sync = (...args)=> {
    const [pathvars, params, callback] = extractArgs(args);
    const isServer = meta.holder ? meta.holder.server : false;
    return (dispatch, getState)=> {
      const state = getState();
      const store = state[name];
      if (!isServer && store && store.sync) {
        callback(null, store.data);
        return;
      }
      const modifyParams = { ...params, syncing: true };
      return fn(pathvars, modifyParams, callback)(dispatch, getState);
    };
  };

  let helpers = meta.helpers || {};
  if (meta.crud) {
    helpers = { ...CRUD, ...helpers };
  }
  const fnHelperCallback = (memo, func, helpername)=> {
    if (memo[helpername]) {
      throw new Error(
        `Helper name: "${helpername}" for endpoint "${name}" has been already reserved`
      );
    }
    const { sync, call } = (func instanceof Function) ? { call: func } : func;
    memo[helpername] = (...args)=> (dispatch, getState)=> {
      const index = args.length - 1;
      const callbackFn = (args[index] instanceof Function) ? args[index] : none;
      const helpersResult = fastApply(call, { getState, dispatch, actions: meta.actions }, args);
      const result = new Promise((resolve, reject)=> {
        const callback = (err, data)=> {
          err ? reject(err) : resolve(data);
          callbackFn(err, data);
        };
        // If helper alias using async functionality
        if (helpersResult instanceof Function) {
          helpersResult((error, newArgs=[])=> {
            if (error) {
              callback(error);
            } else {
              fastApply(
                sync ? fn.sync : fn, null, newArgs.concat(callback)
              )(dispatch, getState);
            }
          });
        } else {
          // if helper alias is synchronous
          fastApply(
            sync ? fn.sync : fn, null, helpersResult.concat(callback)
          )(dispatch, getState);
        }
      });
      result.catch(none);
      return result;
    };
    return memo;
  };

  return Object.keys(helpers).reduce(
    (memo, key)=> fnHelperCallback(memo, helpers[key], key, helpers), fn);
}
<commit_msg>Fix: responseHandler not called<commit_after>"use strict";

import fastApply from "fast-apply";
import libUrl from "url";
import urlTransform from "./urlTransform";
import merge from "./utils/merge";
import get from "./utils/get";
import fetchResolver from "./fetchResolver";
import PubSub from "./PubSub";
import createHolder from "./createHolder";

function none() {}

function extractArgs(args) {
  let pathvars;
  let params={};
  let callback;
  if (args[0] instanceof Function) {
    callback = args[0];
  } else if (args[1] instanceof Function) {
    pathvars = args[0];
    callback = args[1];
  } else {
    pathvars = args[0];
    params = args[1];
    callback = args[2] || none;
  }
  return [pathvars, params, callback];
}

function helperCrudFunction(name) {
  return (...args)=> {
    const [pathvars, params, cb] = extractArgs(args);
    return [pathvars, { ...params, method: name.toUpperCase() }, cb];
  };
}

function defaultMiddlewareArgsParser(dispatch, getState) {
  return { dispatch, getState };
}

export const CRUD = ["get", "post", "put", "delete", "patch"].reduce(
  (memo, name)=> {
    memo[name] = helperCrudFunction(name);
    return memo;
  }, {});

/**
 * Constructor for create action
 * @param  {String} url          endpoint's url
 * @param  {String} name         action name
 * @param  {Object} options      action configuration
 * @param  {Object} ACTIONS      map of actions
 * @param  {[type]} fetchAdapter adapter for fetching data
 * @return {Function+Object}     action function object
 */
export default function actionFn(url, name, options, ACTIONS={}, meta={}) {
  const { actionFetch, actionSuccess, actionFail, actionReset } = ACTIONS;
  const pubsub = new PubSub();
  const requestHolder = createHolder();
  /**
   * Fetch data from server
   * @param  {Object}   pathvars    path vars for url
   * @param  {Object}   params      fetch params
   * @param  {Function} getState    helper meta function
  */
  const request = (pathvars, params, getState=none)=> {
    const responseHandler = meta && meta.holder && meta.holder.responseHandler;
    const resultUrlT = urlTransform(url, pathvars, meta.urlOptions);
    const rootUrl = meta.holder ? meta.holder.rootUrl : null;
    let urlT = resultUrlT;
    if (rootUrl) {
      const urlObject = libUrl.parse(urlT);
      if (!urlObject.host) {
        const urlPath = (rootUrl.path ? rootUrl.path.replace(/\/$/, "") : "") +
          "/" + (urlObject.path ? urlObject.path.replace(/^\//, "") : "");
        urlT = `${rootUrl.protocol}//${rootUrl.host}${urlPath}`;
      }
    }
    const globalOptions = !meta.holder ? {} :
      (meta.holder.options instanceof Function) ?
        meta.holder.options(urlT, params, getState) : (meta.holder.options);
    const baseOptions = (options instanceof Function) ?
      options(urlT, params, getState) :
      options;
    const opts = merge({}, globalOptions, baseOptions, params);
    const response = meta.fetch(urlT, opts);
    const result = !meta.validation ? response : response.then(
      data=> new Promise(
        (resolve, reject)=> meta.validation(data,
          err=> err ? reject(err) : resolve(data))));
    if (responseHandler) {
      if (result && result.then) {
        result.then(
          data=> responseHandler(null, data),
          err=> responseHandler(err)
        );
      } else {
        responseHandler(result);
      }
    }
    result && result.catch && result.catch(none);
    return result;
  };

  /**
   * Fetch data from server
   * @param  {Object}   pathvars    path vars for url
   * @param  {Object}   params      fetch params
   * @param  {Function} callback)   callback execute after end request
   */
  function fn(...args) {
    const [pathvars, params, callback] = extractArgs(args);
    const syncing = params ? !!params.syncing : false;
    params && delete params.syncing;
    pubsub.push(callback);
    return (...middlewareArgs)=> {
      const middlewareParser = (meta.holder && meta.holder.middlewareParser) ||
        defaultMiddlewareArgsParser;
      const { dispatch, getState } = middlewareParser(...middlewareArgs);
      const { reducerName, prefix } = meta;
      const state = getState();
      const isLoading = get(state, prefix, reducerName, "loading");
      if (isLoading) {
        return;
      }
      const requestOptions = { pathvars, params };
      const prevData =  get(state, prefix, reducerName, "data");
      dispatch({ type: actionFetch, syncing, request: requestOptions });
      const fetchResolverOpts = {
        dispatch,
        getState,
        actions: meta.actions,
        prefetch: meta.prefetch
      };
      const result = new Promise((done, fail)=> {
        fetchResolver(0, fetchResolverOpts, (err)=> {
          if (err) {
            pubsub.reject(err);
            return fail(err);
          }
          new Promise((resolve, reject)=> {
            requestHolder.set({
              resolve,
              reject,
              promise: request(pathvars, params, getState).then(resolve, reject)
            });
          }).then((d)=> {
            requestHolder.pop();
            const data = meta.transformer(d, prevData, {
              type: actionSuccess, request: requestOptions
            });
            dispatch({
              data,
              origData: d,
              type: actionSuccess,
              syncing: false,
              request: requestOptions
            });
            if (meta.broadcast) {
              meta.broadcast.forEach((type)=> {
                dispatch({ type, data, origData: d, request: requestOptions });
              });
            }
            if (meta.postfetch) {
              meta.postfetch.forEach((postfetch)=> {
                (postfetch instanceof Function) && postfetch({
                  data, getState, dispatch, actions: meta.actions, request: requestOptions
                });
              });
            }
            pubsub.resolve(data);
            done(data);
          }, (error)=> {
            dispatch({ type: actionFail, syncing: false, error, request: requestOptions });
            pubsub.reject(error);
            fail(error);
          });
        });
      });
      result.catch(none);
      return result;
    };
  }

  /*
    Pure rest request
   */
  fn.request = request;

  /**
   * Reset store to initial state
   */
  fn.reset = (mutation)=> {
    const defer = requestHolder.pop();
    defer && defer.reject(new Error("Application abort request"));
    return mutation === "sync" ? { type: actionReset, mutation } : { type: actionReset };
  };

  /**
   * Sync store with server. In server mode works as usual method.
   * If data have already synced, data would not fetch after call this method.
   * @param  {Object} pathvars    path vars for url
   * @param  {Object} params      fetch params
   * @param  {Function} callback) callback execute after end request
   */
  fn.sync = (...args)=> {
    const [pathvars, params, callback] = extractArgs(args);
    const isServer = meta.holder ? meta.holder.server : false;
    return (dispatch, getState)=> {
      const state = getState();
      const store = state[name];
      if (!isServer && store && store.sync) {
        callback(null, store.data);
        return;
      }
      const modifyParams = { ...params, syncing: true };
      return fn(pathvars, modifyParams, callback)(dispatch, getState);
    };
  };

  let helpers = meta.helpers || {};
  if (meta.crud) {
    helpers = { ...CRUD, ...helpers };
  }
  const fnHelperCallback = (memo, func, helpername)=> {
    if (memo[helpername]) {
      throw new Error(
        `Helper name: "${helpername}" for endpoint "${name}" has been already reserved`
      );
    }
    const { sync, call } = (func instanceof Function) ? { call: func } : func;
    memo[helpername] = (...args)=> (dispatch, getState)=> {
      const index = args.length - 1;
      const callbackFn = (args[index] instanceof Function) ? args[index] : none;
      const helpersResult = fastApply(call, { getState, dispatch, actions: meta.actions }, args);
      const result = new Promise((resolve, reject)=> {
        const callback = (err, data)=> {
          err ? reject(err) : resolve(data);
          callbackFn(err, data);
        };
        // If helper alias using async functionality
        if (helpersResult instanceof Function) {
          helpersResult((error, newArgs=[])=> {
            if (error) {
              callback(error);
            } else {
              fastApply(
                sync ? fn.sync : fn, null, newArgs.concat(callback)
              )(dispatch, getState);
            }
          });
        } else {
          // if helper alias is synchronous
          fastApply(
            sync ? fn.sync : fn, null, helpersResult.concat(callback)
          )(dispatch, getState);
        }
      });
      result.catch(none);
      return result;
    };
    return memo;
  };

  return Object.keys(helpers).reduce(
    (memo, key)=> fnHelperCallback(memo, helpers[key], key, helpers), fn);
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

require('proof')(6, function (step, deepEqual, say) {
  var fs = require('fs'), cadence = require('../..');

  cadence(function (step) {

    var done = step(2);
    var items = step([])([]);
    generate([ 1, 2, 3 ], items, done);

  }, function (one, two, items) {

    deepEqual(one, 1, 'first');
    deepEqual(two, 2, 'second');
    deepEqual(items, [ 1, 2, 3 ], 'gathered');

  })(step());

  cadence(function (step) {

    var done = step(2);
    var items = step([])([]);
    generateIf([ 1, 2, 3 ], items, done);

  }, function (one, two, items) {

    deepEqual(one, 1, 'prune first');
    deepEqual(two, 2, 'prune second');
    deepEqual(items, [ 1, 3 ], 'prune gathered');

  })(step());

});

function generate (values, array, done) {
  values.forEach(function (value) { array(null, value) });
  done(null, 1, 2);
}

function generateIf (values, array, done) {
  values.forEach(function (value) {
    if (value % 2) array(null, value)
    else array(null);
  });
  done(null, 1, 2);
}
<commit_msg>Test an empty zero-to-many array.<commit_after>#!/usr/bin/env node

require('proof')(9, function (step, deepEqual, say) {
  var fs = require('fs'), cadence = require('../..');

  cadence(function (step) {

    var done = step(2);
    var items = step([])([]);
    generate([ 1, 2, 3 ], items, done);

  }, function (one, two, items) {

    deepEqual(one, 1, 'first');
    deepEqual(two, 2, 'second');
    deepEqual(items, [ 1, 2, 3 ], 'gathered');

  })(step());

  cadence(function (step) {

    var done = step(2);
    var items = step([])([]);
    generateIf([ 1, 2, 3 ], items, done);

  }, function (one, two, items) {

    deepEqual(one, 1, 'prune first');
    deepEqual(two, 2, 'prune second');
    deepEqual(items, [ 1, 3 ], 'prune gathered');

  })(step());

  cadence(function (step) {

    var done = step(2);
    var items = step([])([]);
    generate([], items, done);

  }, function (one, two, items) {

    deepEqual(one, 1, 'empty first');
    deepEqual(two, 2, 'empty second');
    deepEqual(items, [], 'empty gathered');

  })(step());

});

function generate (values, array, done) {
  values.forEach(function (value) { array(null, value) });
  done(null, 1, 2);
}

function generateIf (values, array, done) {
  values.forEach(function (value) {
    if (value % 2) array(null, value)
    else array(null);
  });
  done(null, 1, 2);
}
<|endoftext|>


<commit_before>window.resourceURLs = function() {
  urls = backgroundURLs().concat(imageURLs(), scriptURLs(), linkURLs(), currentURL());

  return jQuery.map(urls, function(url) {
    if (url.match(/^\/\//)) {
      return 'http:' + url;
    }
    else if (url.match(/^https?/)) {
      return url;
    }
    else {
      return window.location.origin + '/' + url;
    }
  });
}

window.backgroundURLs = function() {
  backgroundURLs = new Array();

  jQuery('*').each(function() {
    if (jQuery(this).css('background').match('url')) {
      backgroundURLs.push(jQuery(this).css('background').match(/url\((.*)\)/)[1]);
    }
  });

  return backgroundURLs;
}

window.imageURLs = function() {
  imageURLs = new Array();

  jQuery('img').each(function() {
    if (jQuery(this).attr('src')) {
      imageURLs.push(jQuery(this).attr('src'));
    }
  });

  return imageURLs;
}

window.scriptURLs = function() {
  scriptURLs = new Array();

  jQuery('script').each(function() {
    if (jQuery(this).attr('src')) {
      scriptURLs.push(jQuery(this).attr('src'));
    }
  });

  return scriptURLs;
}

window.linkURLs = function() {
  linkURLs = new Array();

  jQuery('link').each(function() {
    if (jQuery(this).attr('href')) {
      linkURLs.push(jQuery(this).attr('href'));
    }
  });

  return linkURLs;
}

window.currentURL = function() {
  return [window.location.href];
}
<commit_msg>Fix issue with javascript css background matching being too greedy.<commit_after>window.resourceURLs = function() {
  urls = backgroundURLs().concat(imageURLs(), scriptURLs(), linkURLs(), currentURL());

  return jQuery.map(urls, function(url) {
    if (url.match(/^\/\//)) {
      return 'http:' + url;
    }
    else if (url.match(/^https?/)) {
      return url;
    }
    else {
      return window.location.origin + '/' + url;
    }
  });
}

window.backgroundURLs = function() {
  backgroundURLs = new Array();

  jQuery('*').each(function() {
    if (jQuery(this).css('background').match('url')) {
      backgroundURLs.push(jQuery(this).css('background').match(/url\((.*?)\)/)[1]);
    }
  });

  return backgroundURLs;
}

window.imageURLs = function() {
  imageURLs = new Array();

  jQuery('img').each(function() {
    if (jQuery(this).attr('src')) {
      imageURLs.push(jQuery(this).attr('src'));
    }
  });

  return imageURLs;
}

window.scriptURLs = function() {
  scriptURLs = new Array();

  jQuery('script').each(function() {
    if (jQuery(this).attr('src')) {
      scriptURLs.push(jQuery(this).attr('src'));
    }
  });

  return scriptURLs;
}

window.linkURLs = function() {
  linkURLs = new Array();

  jQuery('link').each(function() {
    if (jQuery(this).attr('href')) {
      linkURLs.push(jQuery(this).attr('href'));
    }
  });

  return linkURLs;
}

window.currentURL = function() {
  return [window.location.href];
}
<|endoftext|>


<commit_before>/**
 * @file Instantiates and configures angular modules for your module.
 */
define(['angular'], function (ng) {
  'use strict';

  ng.module('{{template_name}}.controllers', []);
  ng.module('{{template_name}}.providers', []);
  ng.module('{{template_name}}.services', []);
  ng.module('{{template_name}}.factories', []);
  ng.module('{{template_name}}.directives', []);

  var module = ng.module('{{template_name}}', [
    'cs_common',
    '{{template_name}}.controllers',
    '{{template_name}}.providers',
    '{{template_name}}.services',
    '{{template_name}}.factories',
    '{{template_name}}.directives'
  ]);

  module.config([
    '$routeProvider',
    'CSTemplateProvider',
    function ($routeProvider, CSTemplate) {

      // Set the subfolder of your module that contains all your view templates.
      CSTemplate.setPath('/modules/{{template_name}}/views');

      // Register any routes you need for your module.
      $routeProvider
        .when('/example', {
          templateUrl: CSTemplate.view('{{Template}}-view'),
          controller: '{{Template}}Controller',
          public: true
        });
    }

  ]);

  return module;
});
<commit_msg>Fix wrong template file name<commit_after>/**
 * @file Instantiates and configures angular modules for your module.
 */
define(['angular'], function (ng) {
  'use strict';

  ng.module('{{template_name}}.controllers', []);
  ng.module('{{template_name}}.providers', []);
  ng.module('{{template_name}}.services', []);
  ng.module('{{template_name}}.factories', []);
  ng.module('{{template_name}}.directives', []);

  var module = ng.module('{{template_name}}', [
    'cs_common',
    '{{template_name}}.controllers',
    '{{template_name}}.providers',
    '{{template_name}}.services',
    '{{template_name}}.factories',
    '{{template_name}}.directives'
  ]);

  module.config([
    '$routeProvider',
    'CSTemplateProvider',
    function ($routeProvider, CSTemplate) {

      // Set the subfolder of your module that contains all your view templates.
      CSTemplate.setPath('/modules/{{template_name}}/views');

      // Register any routes you need for your module.
      $routeProvider
        .when('/example', {
          templateUrl: CSTemplate.view('{{template_name}}-view'),
          controller: '{{Template}}Controller',
          public: true
        });
    }

  ]);

  return module;
});
<|endoftext|>


<commit_before>// Hotmess.js template engine (https://github.com/rlauck/hotmess)
// @author Ryan Lauck
(function(root){
	"use strict";

	var map = {"&":"&", "<":"<", ">":">", '"':'"', "'":''', "/":'/'},
	    html = /&(?!#?\w+;)|<|>|"|'|\//g,
	    replacement = function(c){return map[c];};

	function value(code){
		if(/^\s*\.key\b/.test(code)) return "i"; // match current iteration key
		return code.replace(/[^\.\/\(\)$\w\xA0-\uFFFF]/g, '') // strip control chars and whitespace
			.replace(/(\.\.\/)/g, 'p.') // replace the parent context operator
			.replace(/^((?:p\.)+)?\.?((?:\.?[^\.\(]+)*)(\(\))?/, // match on parent/current context and property/method
				function(m, p, vals, func){ return [p] + (vals ? 'v.'+vals : 'v') + (func ? '(v,i)' : ''); });
	}

	root.hotmess = {
		version: '0.0.4',
		_t: {},
		enc: function(s, def) {
			//return ((s === void(0) ? def : s)+'').replace(html, replacement);
			return String.replace(s === void(0) ? def : s, html, replacement);
		},
		raw: function(s, def) {
			return s === void(0) ? def : s;
		},
		compile: function(tmpl) {
			return Function("v,i", ("var a,p,o='" + (tmpl||'')
				.replace(/'|\\/g, '\\$&') // escape apostrophe and backslash
				.replace(/\{\{\?(\?)?(.*?)\}\}/g, function(m, elseif, test) { // conditional tag
					return elseif ?
						(test ? "';}else if("+value(test)+"){o+='" : "';}else{o+='") :
						(test ? "';if("+value(test)+"){o+='"       : "';}o+='");
				})
				.replace(/\{\{~(?:\}\}|(.+?)\}\})/g, function(m, list) { // list tag
					return list ? // if the list tag has contents its a start tag otherwise its a closing tag
						"';p={v:v,p:p,i:i,a:a};a="+value(list)+";if(a){i=-1;while(++i < a.length){v=a[i];o+='" : // push context, begin loop
						"';}}i=p.i;v=p.v;a=p.a;p=p.p;o+='"; // end loop, pop context
				})
				.replace(/\{\{>\s*([\.$\w\xA0-\uFFFF]+?)\s*\}\}/g, function(m, partial){ // partial tag
					return "';o+=hotmess.template('"+partial+"')(v,i);o+='";
				})
				.replace(/\{\{(&)?\s*(\S+?)\s*(?:\:\s*(")?(.+?)"?\s*)?\}\}/g, function(m, unesc, v, q, def) { // variable tag
					return "';o+=" + (unesc ? "hotmess.raw(" : "hotmess.enc(") + value(v) + "," + (q || !def ? "'"+def+"'" : value(def)) + ");o+='";
				})
				+ "';return o;")
				.replace(/\n/g, '\\n').replace(/\t/g, '\\t').replace(/\r/g, '\\r') // preserve whitespace (ex: <pre>)
				.replace(/(\s|;|\}|^|\{)o\+='';/g, '$1')); // clean empty appends
		},
		template: function(name, tmpl){
			return !tmpl ? this._t[name] : this._t[name] = (typeof tmpl == 'string' ? this.compile(tmpl) : tmpl);
		}
	};

	(typeof define == 'function') && define.amd && define(root.hotmess);
}(this.exports||this));<commit_msg>forgot that String.replace is only available in gecko :/<commit_after>// Hotmess.js template engine (https://github.com/rlauck/hotmess)
// @author Ryan Lauck
(function(root){
	"use strict";

	var map = {"&":"&", "<":"<", ">":">", '"':'"', "'":''', "/":'/'},
	    html = /&(?!#?\w+;)|<|>|"|'|\//g,
	    replacement = function(c){return map[c];};

	function value(code){
		if(/^\s*\.key\b/.test(code)) return "i"; // match current iteration key
		return code.replace(/[^\.\/\(\)$\w\xA0-\uFFFF]/g, '') // strip control chars and whitespace
			.replace(/(\.\.\/)/g, 'p.') // replace the parent context operator
			.replace(/^((?:p\.)+)?\.?((?:\.?[^\.\(]+)*)(\(\))?/, // match on parent/current context and property/method
				function(m, p, vals, func){ return [p] + (vals ? 'v.'+vals : 'v') + (func ? '(v,i)' : ''); });
	}

	root.hotmess = {
		version: '0.0.4',
		_t: {},
		enc: function(s, def) {
			return ((s === void(0) ? def : s)+'').replace(html, replacement);
		},
		raw: function(s, def) {
			return s === void(0) ? def : s;
		},
		compile: function(tmpl) {
			return Function("v,i", ("var a,p,o='" + (tmpl||'')
				.replace(/'|\\/g, '\\$&') // escape apostrophe and backslash
				.replace(/\{\{\?(\?)?(.*?)\}\}/g, function(m, elseif, test) { // conditional tag
					return elseif ?
						(test ? "';}else if("+value(test)+"){o+='" : "';}else{o+='") :
						(test ? "';if("+value(test)+"){o+='"       : "';}o+='");
				})
				.replace(/\{\{~(?:\}\}|(.+?)\}\})/g, function(m, list) { // list tag
					return list ? // if the list tag has contents its a start tag otherwise its a closing tag
						"';p={v:v,p:p,i:i,a:a};a="+value(list)+";if(a){i=-1;while(++i < a.length){v=a[i];o+='" : // push context, begin loop
						"';}}i=p.i;v=p.v;a=p.a;p=p.p;o+='"; // end loop, pop context
				})
				.replace(/\{\{>\s*([\.$\w\xA0-\uFFFF]+?)\s*\}\}/g, function(m, partial){ // partial tag
					return "';o+=hotmess.template('"+partial+"')(v,i);o+='";
				})
				.replace(/\{\{(&)?\s*(\S+?)\s*(?:\:\s*(")?(.+?)"?\s*)?\}\}/g, function(m, unesc, v, q, def) { // variable tag
					return "';o+=" + (unesc ? "hotmess.raw(" : "hotmess.enc(") + value(v) + "," + (q || !def ? "'"+def+"'" : value(def)) + ");o+='";
				})
				+ "';return o;")
				.replace(/\n/g, '\\n').replace(/\t/g, '\\t').replace(/\r/g, '\\r') // preserve whitespace (ex: <pre>)
				.replace(/(\s|;|\}|^|\{)o\+='';/g, '$1')); // clean empty appends
		},
		template: function(name, tmpl){
			return !tmpl ? this._t[name] : this._t[name] = (typeof tmpl == 'string' ? this.compile(tmpl) : tmpl);
		}
	};

	(typeof define == 'function') && define.amd && define(root.hotmess);
}(this.exports||this));<|endoftext|>


<commit_before>/*
 * index.js: Top-level include for the utils module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var fs = require('fs'),
    path = require('path'),
    util = require('util'),
    flatiron = require('flatiron'),
    dateformat = require('dateformat'),
    async = flatiron.common.async,
    request = require('request'),
    semver = require('semver'),
    jitsu = require('../../jitsu');

var common = module.exports = flatiron.common.clone(flatiron.common);

//
// ### function formatApp (app, exclude)
// #### @app {Object} Application document to format
// #### @exclude {Array} **Optional** List of additional properties to exclude
// Formats the specified `app` by removing unnecessary properties combined with
// any additional properties the caller wishes to `exclude`.
//
common.formatApp = function (app, exclude) {
  var snapshots = app.snapshots,
      remove = ['_id', '_rev', 'drones', 'id', 'maxDrones', 'resource'];

  app.snapshots = !snapshots ? [] : snapshots.map(function (snap) {
    var created = new Date(snap.ctime);
    created = dateformat(created, "mm/dd HH:MM:ss Z");
    return {
      id: snap.id,
      created: created
    }
  });

  if (exclude) {
    remove = remove.concat(exclude);
  }

  //
  // TODO: won't work with current rendering of package.json
  //
  // app.state = common.formatAppState(app.state);

  //
  // Update the ctime and mtime of the document to a more human-readable format
  //
  app.ctime = dateformat(app.ctime, "mm/dd HH:MM:ss Z");
  app.mtime = dateformat(app.mtime, "mm/dd HH:MM:ss Z");

  //
  // Format ctime to more human-readable format for snapshots if they are available
  //
  if (app.active) {
    app.active.ctime = dateformat(app.active.ctime, "mm/dd HH:MM:ss Z");
  }

  if (app.running) {
    app.running.ctime = dateformat(app.running.ctime, "mm/dd HH:MM:ss Z");
  }

  remove.forEach(function (key) {
    delete app[key];
  });

  return app;
}

common.formatAppState = function (state) {

  var str;

  if(state === "started") {
    str = state.green;
  } else {
    str = (state || 'unknown').grey;
  }

  return str;

};

//
// ### function missingKeys (source, target)
// #### @source {Array} List of keys for the current object
// #### @target {Array} List of keys for the new object
// Returns the complement of the intersection of the two arrays.
//
// e.g. [1,2,3,5], [1,2,3,4,5] => [4]
//
common.missingKeys = function (source, target) {
  var missing = [];

  source.forEach(function (key) {
    if (target.indexOf(key) === -1) {
      missing.push(key);
    }
  });

  return missing;
};

//
// ### function objectDiff (current, update, level)
// #### @current {Object} Current representation of the object.
// #### @update {Object} Updated representation of the object.
// #### @level {Number} Level in the object we are diffing.
// Returns an incremental diff of the `current` object
// against the updated representation `update`
//
// e.g. { foo: 1, bar: 2 }, { foo: 2, bar: 2 } => { foo: 2 }
//
common.objectDiff = function (current, update, level) {
  var ckeys = Object.keys(current),
      ukeys = Object.keys(update),
      diff = {};

  //
  // Ignore changes on the first level of the object.
  //
  level = level || 0;
  if (level > 0) {
    common.missingKeys(ckeys, ukeys).forEach(function (key) {
      diff[key] = undefined;
    });
  }

  ukeys.forEach(function (key) {
    var nested, i;

    if (!current[key]) {
      diff[key] = update[key];
    }
    else if (Array.isArray(update[key])) {
      if (update[key].length !== current[key].length) {
        diff[key] = update[key];
      }
      else {
        for (i = 0; i < update[key]; i += 1) {
          if (current[key].indexOf(update[key][i]) === -1) {
            diff[key] = update[key];
            break;
          }
        }
      }
    }
    else if (typeof update[key] === 'object') {
      if ((nested = common.objectDiff(current[key], update[key], level + 1))) {
        diff[key] = update[key];
      }
    }
    else {
      if (current[key] !== update[key]) {
        diff[key] = update[key];
      }
    }
  });

  return Object.keys(diff).length > 0 ? diff : null;
};

common.checkVersion = function (callback) {
  var responded = false

  //
  // Check the GitHub tags for `jitsu` to see if the current
  // version is outdated. If it is not make sure to message the user at the end.
  //
  request({
    uri: 'http://registry.npmjs.org/jitsu/latest',
    timeout: 400
  }, function (err, res, body) {
    if (!responded) {
      responded = true;

      try {
        var pkg = JSON.parse(body);

        if (semver.gt(pkg.version, jitsu.version)) {
          jitsu.log.warn('A newer version of ' + 'jitsu'.magenta + ' is available. ' + 'please update immediately');
          jitsu.log.help('To install the latest ' + 'jitsu'.magenta + ' type `[sudo] npm install jitsu -g`');
          jitsu.log.warn('To ' + 'continue'.bold + ' without an update ' + 'type'.cyan  + ' ' + '\'yes\''.magenta);

          jitsu.prompt.confirm('Continue without updating? Bad things might happen (no)', function (err, result) {
            return err ? callback() : callback(!result);
          });

          return;
        }

        callback();
      }
      catch (ex) {
        //
        // Ignore errors from GitHub. We will notify the user
        // of an upgrade at the next possible opportunity.
        //
        callback();
      }
    }
  });
};
<commit_msg>[ui] show drone usage and max drones on `apps view`.<commit_after>/*
 * index.js: Top-level include for the utils module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var fs = require('fs'),
    path = require('path'),
    util = require('util'),
    flatiron = require('flatiron'),
    dateformat = require('dateformat'),
    async = flatiron.common.async,
    request = require('request'),
    semver = require('semver'),
    jitsu = require('../../jitsu');

var common = module.exports = flatiron.common.clone(flatiron.common);

//
// ### function formatApp (app, exclude)
// #### @app {Object} Application document to format
// #### @exclude {Array} **Optional** List of additional properties to exclude
// Formats the specified `app` by removing unnecessary properties combined with
// any additional properties the caller wishes to `exclude`.
//
common.formatApp = function (app, exclude) {
  var snapshots = app.snapshots,
      remove = ['_id', '_rev', 'id', 'resource'];

  app.snapshots = !snapshots ? [] : snapshots.map(function (snap) {
    var created = new Date(snap.ctime);
    created = dateformat(created, "mm/dd HH:MM:ss Z");
    return {
      id: snap.id,
      created: created
    }
  });

  if (exclude) {
    remove = remove.concat(exclude);
  }

  //
  // TODO: won't work with current rendering of package.json
  //
  // app.state = common.formatAppState(app.state);

  //
  // Update the ctime and mtime of the document to a more human-readable format
  //
  app.ctime = dateformat(app.ctime, "mm/dd HH:MM:ss Z");
  app.mtime = dateformat(app.mtime, "mm/dd HH:MM:ss Z");

  //
  // Format ctime to more human-readable format for snapshots if they are available
  //
  if (app.active) {
    app.active.ctime = dateformat(app.active.ctime, "mm/dd HH:MM:ss Z");
  }

  if (app.running) {
    app.running.ctime = dateformat(app.running.ctime, "mm/dd HH:MM:ss Z");
  }

  remove.forEach(function (key) {
    delete app[key];
  });

  return app;
}

common.formatAppState = function (state) {

  var str;

  if(state === "started") {
    str = state.green;
  } else {
    str = (state || 'unknown').grey;
  }

  return str;

};

//
// ### function missingKeys (source, target)
// #### @source {Array} List of keys for the current object
// #### @target {Array} List of keys for the new object
// Returns the complement of the intersection of the two arrays.
//
// e.g. [1,2,3,5], [1,2,3,4,5] => [4]
//
common.missingKeys = function (source, target) {
  var missing = [];

  source.forEach(function (key) {
    if (target.indexOf(key) === -1) {
      missing.push(key);
    }
  });

  return missing;
};

//
// ### function objectDiff (current, update, level)
// #### @current {Object} Current representation of the object.
// #### @update {Object} Updated representation of the object.
// #### @level {Number} Level in the object we are diffing.
// Returns an incremental diff of the `current` object
// against the updated representation `update`
//
// e.g. { foo: 1, bar: 2 }, { foo: 2, bar: 2 } => { foo: 2 }
//
common.objectDiff = function (current, update, level) {
  var ckeys = Object.keys(current),
      ukeys = Object.keys(update),
      diff = {};

  //
  // Ignore changes on the first level of the object.
  //
  level = level || 0;
  if (level > 0) {
    common.missingKeys(ckeys, ukeys).forEach(function (key) {
      diff[key] = undefined;
    });
  }

  ukeys.forEach(function (key) {
    var nested, i;

    if (!current[key]) {
      diff[key] = update[key];
    }
    else if (Array.isArray(update[key])) {
      if (update[key].length !== current[key].length) {
        diff[key] = update[key];
      }
      else {
        for (i = 0; i < update[key]; i += 1) {
          if (current[key].indexOf(update[key][i]) === -1) {
            diff[key] = update[key];
            break;
          }
        }
      }
    }
    else if (typeof update[key] === 'object') {
      if ((nested = common.objectDiff(current[key], update[key], level + 1))) {
        diff[key] = update[key];
      }
    }
    else {
      if (current[key] !== update[key]) {
        diff[key] = update[key];
      }
    }
  });

  return Object.keys(diff).length > 0 ? diff : null;
};

common.checkVersion = function (callback) {
  var responded = false

  //
  // Check the GitHub tags for `jitsu` to see if the current
  // version is outdated. If it is not make sure to message the user at the end.
  //
  request({
    uri: 'http://registry.npmjs.org/jitsu/latest',
    timeout: 400
  }, function (err, res, body) {
    if (!responded) {
      responded = true;

      try {
        var pkg = JSON.parse(body);

        if (semver.gt(pkg.version, jitsu.version)) {
          jitsu.log.warn('A newer version of ' + 'jitsu'.magenta + ' is available. ' + 'please update immediately');
          jitsu.log.help('To install the latest ' + 'jitsu'.magenta + ' type `[sudo] npm install jitsu -g`');
          jitsu.log.warn('To ' + 'continue'.bold + ' without an update ' + 'type'.cyan  + ' ' + '\'yes\''.magenta);

          jitsu.prompt.confirm('Continue without updating? Bad things might happen (no)', function (err, result) {
            return err ? callback() : callback(!result);
          });

          return;
        }

        callback();
      }
      catch (ex) {
        //
        // Ignore errors from GitHub. We will notify the user
        // of an upgrade at the next possible opportunity.
        //
        callback();
      }
    }
  });
};
<|endoftext|>


<commit_before>/*global define*/
define([
        '../ThirdParty/when',
        './buildModuleUrl',
        './Color',
        './defined',
        './loadImage',
        './loadXML'
    ], function(
        when,
        buildModuleUrl,
        Color,
        defined,
        loadImage,
        loadXML) {
    "use strict";

    var PinBuilder = function() {
        this._cache = {};
        this._serializer = new XMLSerializer();
        this._pinPromise = loadXML(buildModuleUrl('Assets/Textures/pin.svg'));
    };

    PinBuilder.prototype.fromColor = function(color, size) {
        if (!defined(size)) {
        }
        if (!defined(color)) {
        }
        return createPin(undefined, size, color, this._pinPromise, this._cache, this._serializer);
    };

    PinBuilder.prototype.fromUrl = function(url, color, size) {
        if (!defined(url)) {
        }
        if (!defined(size)) {
        }
        if (!defined(color)) {
        }
        return createPin(url, size, color, this._pinPromise, this._cache, this._serializer);
    };

    PinBuilder.prototype.fromMakiName = function(name, color, size) {
        if (!defined(name)) {
        }
        if (!defined(size)) {
        }
        if (!defined(color)) {
        }
        return createPin(buildModuleUrl('Assets/Textures/maki/' + name + '.png'), size, color, this._pinPromise, this._cache, this._serializer);
    };

    var colorScratch;

    function loadBase(xml, size, color, serializer) {
        var baseDiv = document.createElement('div');
        var baseDoc = xml;

        var shape = baseDoc.getElementsByTagName("svg")[0];
        shape.setAttribute("width", size);
        shape.setAttribute("height", size);

        var par = baseDiv.ownerDocument.importNode(baseDoc.documentElement, true);
        document.body.appendChild(par);

        var path = par.getElementsByTagName('path')[0];
        path.setAttribute("fill", color.toCssColorString());

        var stroke = path.getAttribute("stroke");
        colorScratch = color.clone(colorScratch);
        colorScratch.red = Math.min(1.0, colorScratch.red + 0.5);
        colorScratch.green = Math.min(1.0, colorScratch.green + 0.5);
        colorScratch.blue = Math.min(1.0, colorScratch.blue + 0.5);
        path.setAttribute("stroke", colorScratch.toCssColorString());

        xml = serializer.serializeToString(par);

        document.body.removeChild(par);

        var baseImage = new Image();
        baseImage.src = "data:image/svg+xml," + xml;
        return baseImage;
    }

    function createPin(url, color, size, pinPromise, cache, serializer) {
        var id = JSON.stringify({
            url : url,
            size : size,
            color : color
        });

        var item = cache[id];
        if (defined(item)) {
            return item;
        }
        var deferred = when.defer();
        cache[id] = deferred.promise;

        if (defined(url)) {
            when.all([pinPromise, loadImage(url)], function(images) {
                var baseImage = loadBase(images[0], size, color, serializer);
                var baseImageWhite = loadBase(images[0], size, Color.WHITE, serializer);
                var baseImageBLACK = loadBase(images[0], size, Color.BLACK, serializer);
                var iconImage = images[1];

                var canvas = document.createElement('canvas');
                canvas.width = size;
                canvas.height = size;
                var ctx = canvas.getContext("2d");

                ctx.drawImage(baseImage, 0, 0);

                var shrink = (size / 15);
                size = (size / 2) - shrink;
                var x = (size / 2) + shrink;
                var y = (size / 3) + (shrink / 2);

                ctx.globalCompositeOperation = 'destination-out';
                ctx.drawImage(iconImage, x - 1, y, size, size);
                ctx.globalCompositeOperation = 'destination-out';
                ctx.drawImage(iconImage, x, y - 1, size, size);
                ctx.globalCompositeOperation = 'destination-out';
                ctx.drawImage(iconImage, x + 1, y, size, size);
                ctx.globalCompositeOperation = 'destination-out';
                ctx.drawImage(iconImage, x, y + 1, size, size);

                ctx.globalCompositeOperation = 'destination-over';
                ctx.drawImage(baseImageBLACK, 0, 0);

                ctx.globalCompositeOperation = 'destination-out';
                ctx.drawImage(iconImage, x, y, size, size);

                ctx.globalCompositeOperation = 'destination-over';
                ctx.drawImage(baseImageWhite, 0, 0);

                deferred.resolve(canvas);
            }).otherwise(function(e) {
                deferred.reject(e);
            });
        } else {
            when(pinPromise, function(image) {
                var baseImage = loadBase(image, size, color, serializer);
                var canvas = document.createElement('canvas');
                canvas.width = size;
                canvas.height = size;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(baseImage, 0, 0);
                deferred.resolve(canvas);
            }).otherwise(function(e) {
                deferred.reject(e);
            });
        }
        return deferred.promise;
    }

    return PinBuilder;
});<commit_msg>Ongoing PinBuilder work.<commit_after>/*global define*/
define([
        '../ThirdParty/when',
        './buildModuleUrl',
        './Color',
        './defined',
        './loadImage',
        './loadXML'
    ], function(
        when,
        buildModuleUrl,
        Color,
        defined,
        loadImage,
        loadXML) {
    "use strict";

    var PinBuilder = function() {
        this._cache = {};
        this._serializer = new XMLSerializer();
        this._pinPromise = loadXML(buildModuleUrl('Assets/Textures/pin.svg'));
    };

    PinBuilder.prototype.fromColor = function(color, size) {
        if (!defined(size)) {
        }
        if (!defined(color)) {
        }
        return createPin(undefined, size, color, this._pinPromise, this._cache, this._serializer);
    };

    PinBuilder.prototype.fromUrl = function(url, color, size) {
        if (!defined(url)) {
        }
        if (!defined(size)) {
        }
        if (!defined(color)) {
        }
        return createPin(url, size, color, this._pinPromise, this._cache, this._serializer);
    };

    PinBuilder.prototype.fromMakiName = function(name, color, size) {
        if (!defined(name)) {
        }
        if (!defined(size)) {
        }
        if (!defined(color)) {
        }
        return createPin(buildModuleUrl('Assets/Textures/maki/' + name + '.png'), size, color, this._pinPromise, this._cache, this._serializer);
    };

    var colorScratch;

    function loadBase(xml, size, color, serializer) {
        var baseDiv = document.createElement('div');
        var baseDoc = xml;

        var shape = baseDoc.getElementsByTagName("svg")[0];
        shape.setAttribute("width", size);
        shape.setAttribute("height", size);

        var par = baseDiv.ownerDocument.importNode(baseDoc.documentElement, true);
        document.body.appendChild(par);

        var path = par.getElementsByTagName('path')[0];
        path.setAttribute("fill", color.toCssColorString());

        var stroke = path.getAttribute("stroke");
        colorScratch = color.clone(colorScratch);
        colorScratch.red = Math.min(1.0, colorScratch.red + 0.5);
        colorScratch.green = Math.min(1.0, colorScratch.green + 0.5);
        colorScratch.blue = Math.min(1.0, colorScratch.blue + 0.5);
        path.setAttribute("stroke", colorScratch.toCssColorString());

        xml = serializer.serializeToString(par);

        document.body.removeChild(par);

        return 'data:image/svg+xml;base64,' + btoa(xml);
    }

    function createPin(url, color, size, pinPromise, cache, serializer) {
        var id = JSON.stringify({
            url : url,
            size : size,
            color : color
        });

        var item = cache[id];
        if (defined(item)) {
            return item;
        }
        var deferred = when.defer();
        cache[id] = deferred.promise;

        if (defined(url)) {
            when.all([pinPromise, loadImage(url)], function(images) {
                var baseImage = new Image();
                baseImage.onload = function() {
                    var iconImage = images[1];

                    var canvas = document.createElement('canvas');
                    canvas.width = size;
                    canvas.height = size;
                    var ctx = canvas.getContext("2d");

                    ctx.globalCompositeOperation = 'source-over';
                    ctx.drawImage(baseImage, 0, 0);

                    var shrink = (size / 15);
                    size = (size / 2) - shrink;
                    var x = (size / 2) + shrink;
                    var y = (size / 3) + (shrink / 2);

                    ctx.globalCompositeOperation = 'destination-out';
                    ctx.drawImage(iconImage, x - 1, y, size, size);
                    ctx.drawImage(iconImage, x, y - 1, size, size);
                    ctx.drawImage(iconImage, x + 1, y, size, size);
                    ctx.drawImage(iconImage, x, y + 1, size, size);

                    ctx.globalCompositeOperation = 'destination-over';
                    ctx.fillStyle = Color.BLACK.toCssColorString();
                    ctx.fillRect(x - 1, y - 1, size + 1, size + 1);

                    ctx.globalCompositeOperation = 'destination-out';
                    ctx.drawImage(iconImage, x, y, size, size);

                    ctx.globalCompositeOperation = 'destination-over';
                    ctx.fillStyle = Color.WHITE.toCssColorString();
                    ctx.fillRect(x, y, size, size);

                    deferred.resolve(canvas);
                };
                baseImage.src = loadBase(images[0], size, color, serializer);
            }).otherwise(function(e) {
                deferred.reject(e);
            });
        } else {
            when(pinPromise, function(image) {
                var baseImage = new Image();
                baseImage.onload = function() {
                    var canvas = document.createElement('canvas');
                    canvas.width = size;
                    canvas.height = size;
                    var ctx = canvas.getContext("2d");
                    ctx.drawImage(baseImage, 0, 0);
                    deferred.resolve(canvas);
                };
                baseImage.src = loadBase(image, size, color, serializer);
            }).otherwise(function(e) {
                deferred.reject(e);
            });
        }
        return deferred.promise;
    }

    return PinBuilder;
});<|endoftext|>


<commit_before>/* Welcome to Agile Toolkit JS framework. This file implements Form. */

// The following HTML structure should be used:
//
//

// <form action="url">
//   ..
//
//
//   <... class='atk-field'>
//     <input id='formid_fieldid' type=>
//     field, etc
//   </...>
//   <error inserts here
//
//   ..repeats..
//
//
 .error template

// </form>
//

$.widget("ui.atk4_form", {

	form: undefined,
	id: undefined,

	submitted: undefined,
	base_url: undefined,
	loading: false,
	plain_submit: false,

	template: {},

	_getChanged: function(){
		return this.form.hasClass('form_changed');
	},
	_setChanged: function(state){
        if(this.element.is('.ignore_changes')){
            this.form.removeClass('form_changed');
            return;
        }
		if(state)this.form.addClass('form_changed');else this.form.removeClass('form_changed');
	},

    _create: function(){
		var self=this;

		this.id=this.element.attr('id');
		this.form=this.element;

		// If we are not being bound to form directly, then find form inside ourselves
		if(!this.form.is('form')){
			this.form=this.form.find('form');
			this.element.bind('submit',function(ev){
				ev.preventDefault();
				self.submitForm();
			});
		}

		console.log('created with url=',this.form.attr('action'));

		this.form.append('<input name="ajax_submit" id="ajax_submit" value="1" type="hidden"/>');
		this.form.addClass('atk4_form');
		this.element.addClass('atk4_form_widget');

		this.form.find('input').bind('keypress',function(e){
			if($(this).is('.ui-autocomplete-input'))return true;
			if(e.keyCode==13){
				$(this).trigger('change');
				self.submitForm();
				return false;
				}
		});

		if($.browser.msie){
			this.form.find('input:radio,input:checkbox').click(function(){
				this.blur();	// this will call onchange event, like it should
				this.focus();
			});
		}

		this.form.find(':input').each(function(){
			if($(this).attr('type')=='checkbox')
				$(this).attr('data-initvalue',$(this).attr('checked'))
			else
				$(this).attr('data-initvalue',$(this).val())
			})
		.bind('change',function(ev){
				//if($(this).attr('type')=='checkbox')
            if($(this).attr('data-initvalue')==$(this).val()){
                ev.preventDefault();
                return;
            }else {
                $(this).attr('data-initvalue',$(this).val());
            }
            self._setChanged(true);
        });

		this.form.find('input[type=radio]').click(function(){
			self._setChanged(true);
		}).change(function(){
			self._setChanged(true);
		});

		// This class defines field error template
		//
 .. ..

		// The following markup is using to show that form field contains errors.
		this.template['field_error']=this.element.find('.field-error-template').remove();
		if(!this.template['field_error'].length)console.log('Warning: form template does not have form-error-template class');

		this.form.submit(function(e){

			if(self.plain_submit){
				e.stopPropagation();
				self.plain_submit=false;
				return;// executes default action
			}

			e.stopPropagation();
			e.preventDefault();
			self.submitForm();
		});

		//this.element.find('.form_error').remove();

		/*
		-- obsolete code
		this.form.find('input[type=submit]').each(function(){
			var a=$('');
			var s=$(this);
			a.text(s.attr('value'));
			a.attr('tabIndex',s.attr('tabIndex')+1);
			a.click(function(){
				form.element.submit()});
			$(this).after(a);
			s.remove();
		});
		*/
		this.base_url=window.location.href.substr(0,window.location.href.indexOf('#'));
        if(!this.base_url)this.base_url=window.location.href;
		if(this.options.base_url)this.base_url=this.options.base_url;
    },
	submitPlain: function(){
		// Disable AJAX handling, perform submit to a specified target then restore functionality.
		// This function is used by file upload
		this.plain_submit=true;
		this.form.trigger('submit');
	},
	setFieldValue: function(field_name,value){
		var f=$('#'+this.id+'_'+field_name);

		if(!f.length){
			console.log('Unable to find field ',field_name,' and fill in ',value);
			return;
		}

		if(f.hasClass('field_reference')){
			var opt=f.find('option[value='+value+']');

			if(opt.length){
				// If it was found - then set value, should change dropdown
				f.val(value).change().trigger('change_ref');
				return;
			}

			var self=this;

			this.reloadField(field_name,null,function(){
				var f=$('#'+self.id+'_'+field_name);
				var opt=f.find('option[value='+value+']');
				if(opt.length){
					f.val(value).change().trigger('change_ref');
				}else{
					console.log('even after field reload, couldnt select ',value,' for ',field_name);
				}
			});
			return;
		}

		f.val(value).change();
	},
	reloadField: function(field_name,url,fn,notrigger){
		var field_id=this.id+'_'+field_name;
		if(!url)url=this.base_url;
		console.log('Field reloading: ',field_name);

		url=$.atk4.addArgument(url,this.id+'_cut_field',field_id);
		var f=$("#"+field_id);

		if(!notrigger)f.trigger('reload_field');

		//if(f.hasClass('field_reference')){
			var f2=f.closest('.form_field');
			//f.remove();
			f=f2;

		//}
		var c=this._getChanged();this._setChanged(false);
		f.atk4_load(url,fn);
		this._setChanged(c);
	},
	fieldError: function(field_name,error){

		if(this.options.error_handler){
			// Allows you to define custom error display handler
			return this.options.error_handler(field_name,error);
		}

		var field=
			typeof(field_name)=='string'?
				$('#'+this.id+'_'+field_name):
				field_name;

		if(!field.length){
			field=this.form.find('[name="'+field_name+'"]');
		}
		if(!field.length){
			alert('Field not found: '+field_name+', error is: '+error);
			return;
		}

		if(!error || error=='0')error="must be specified properly";

		field.focus();

		//field.closest('.form_field').find('.field_hint').hide();
		field.closest('form').find('.field_error').remove();

		// highlight field
		var field_highlight=field.closest('.atk-form-row').addClass('has-error').find('.atk-form-field');

		// Clear previous errors
		field_highlight.children('.atk-form-error').remove();

		if(!this.template['field_error'].length){
			// no template, use alert;
			alert(error);
			return;
		}
		var error_bl=this.template['field_error'].clone();

        // One of the below would find the text. This is faster appreach than
        // doing find('*').andSelf().filter('.field-error-text');
		error_bl.find('.field-error-text').
            add(error_bl.filter('.field-error-text')).text(error);

		error_bl.appendTo(field_highlight).fadeIn();

		this.form.addClass('form_has_error');

		/*
		h=$(//'

'+error+'');
		 '

'+
			 error+'

').insertAfter(field_highlight);
		*/

		error_bl.click(function(){ $(this).closest('.has-error').removeClass('has-error'); error_bl.remove(); });

		var self=this;

		// make it remove error automatically when edited
		field.bind('change.errorhide',function(){
			var t=$(this);
			t.unbind('change.errorhide');

			self.form.removeClass('form_has_error');
			field_highlight.closest('.has-error').removeClass('has-error');
			error_bl.fadeOut(function(){ error_bl.remove(); });
		});
	},
	clearError: function(field){
		if(field){
			field=field.closest('.has-error');
		}else{
			field=this.form.find('.has-error');
		}
		field.find('.atk-form-error').remove();
		field.removeClass('has-error');

		//if(!this.form.find('.field_has_error').length)this.form.removeClass('form_has_error');
	},
	submitForm: function(btn){
		var params={}, form=this;
		if(form.loading){
			$.univ().loadingInProgress();
			return false;
		}

		// btn is clicked
		var richtext=this.element.find('.atk4_richtext');
		if(richtext.length)richtext.atk4_richtext('changeHTML');
		params=this.element.find(":input").serializeArray()
		if(btn){
            for (var el in params){
                if (params[el].name == 'ajax_submit'){
                    params[el].value=btn;
                    break;
                }
            }
        }

		var properties={
			type: "POST",
			url: this.form.attr('action')
		};

		form.loading=true;
		$.atk4.get(properties,params,function(res){
			var c=form._getChanged();form._setChanged(false);

			if(!$.atk4._checkSession(res))return;
			/*
			if(res.substr(0,5)=='ERROR'){
				$.univ().dialogOK('Error','There was error with your request. System maintainers have been notified.');
				return;
			}
			*/
			try {
				eval(res);
			}catch(e){
				//while some browsers prevents popup we better use alert
				w=window.open(null,null,'height=400,width=700,location=no,menubar=no,scrollbars=yes,status=no,titlebar=no,toolbar=no');
				if(w){
					w.document.write('
Error in AJAX response: '+e+'
');
					w.document.write(res);
					w.document.write('<input type=button onclick="window.close()" value="Close">');
				}else{
					alert("Error in AJAX response: "+e+"\n"+res);
				}
			}
			form.loading=false;
			form._setChanged(c);
		},function(){
			form.loading=false;
		});
	}
});
<commit_msg>Minor compat<commit_after>/* Welcome to Agile Toolkit JS framework. This file implements Form. */

// The following HTML structure should be used:
//
//

// <form action="url">
//   ..
//
//
//   <... class='atk-field'>
//     <input id='formid_fieldid' type=>
//     field, etc
//   </...>
//   <error inserts here
//
//   ..repeats..
//
//
 .error template

// </form>
//

$.widget("ui.atk4_form", {

	form: undefined,
	id: undefined,

	submitted: undefined,
	base_url: undefined,
	loading: false,
	plain_submit: false,

	template: {},

	_getChanged: function(){
		return this.form.hasClass('form_changed');
	},
	_setChanged: function(state){
        if(this.element.is('.ignore_changes')){
            this.form.removeClass('form_changed');
            return;
        }
		if(state)this.form.addClass('form_changed');else this.form.removeClass('form_changed');
	},

    _create: function(){
		var self=this;

		this.id=this.element.attr('id');
		this.form=this.element;

		// If we are not being bound to form directly, then find form inside ourselves
		if(!this.form.is('form')){
			this.form=this.form.find('form');
			this.element.bind('submit',function(ev){
				ev.preventDefault();
				self.submitForm();
			});
		}

		console.log('created with url=',this.form.attr('action'));

		this.form.append('<input name="ajax_submit" id="ajax_submit" value="1" type="hidden"/>');
		this.form.addClass('atk4_form');
		this.element.addClass('atk4_form_widget');

		this.form.find('input').bind('keypress',function(e){
			if($(this).is('.ui-autocomplete-input'))return true;
			if(e.keyCode==13){
				$(this).trigger('change');
				self.submitForm();
				return false;
				}
		});

		if($.browser.msie){
			this.form.find('input:radio,input:checkbox').click(function(){
				this.blur();	// this will call onchange event, like it should
				this.focus();
			});
		}

		this.form.find(':input').each(function(){
			if($(this).attr('type')=='checkbox')
				$(this).attr('data-initvalue',$(this).attr('checked'))
			else
				$(this).attr('data-initvalue',$(this).val())
			})
		.bind('change',function(ev){
				//if($(this).attr('type')=='checkbox')
            if($(this).attr('data-initvalue')==$(this).val()){
                ev.preventDefault();
                return;
            }else {
                $(this).attr('data-initvalue',$(this).val());
            }
            self._setChanged(true);
        });

		this.form.find('input[type=radio]').click(function(){
			self._setChanged(true);
		}).change(function(){
			self._setChanged(true);
		});

		// This class defines field error template
		//
 .. ..

		// The following markup is using to show that form field contains errors.
		this.template['field_error']=this.element.find('.field-error-template').remove();
		if(!this.template['field_error'].length)console.log('Warning: form template does not have form-error-template class');

		this.form.submit(function(e){

			if(self.plain_submit){
				e.stopPropagation();
				self.plain_submit=false;
				return;// executes default action
			}

			e.stopPropagation();
			e.preventDefault();
			self.submitForm();
		});

		//this.element.find('.form_error').remove();

		/*
		-- obsolete code
		this.form.find('input[type=submit]').each(function(){
			var a=$('');
			var s=$(this);
			a.text(s.attr('value'));
			a.attr('tabIndex',s.attr('tabIndex')+1);
			a.click(function(){
				form.element.submit()});
			$(this).after(a);
			s.remove();
		});
		*/
		this.base_url=window.location.href.substr(0,window.location.href.indexOf('#'));
        if(!this.base_url)this.base_url=window.location.href;
		if(this.options.base_url)this.base_url=this.options.base_url;
    },
	submitPlain: function(){
		// Disable AJAX handling, perform submit to a specified target then restore functionality.
		// This function is used by file upload
		this.plain_submit=true;
		this.form.trigger('submit');
	},
	setFieldValue: function(field_name,value){
		var f=$('#'+this.id+'_'+field_name);

		if(!f.length){
			console.log('Unable to find field ',field_name,' and fill in ',value);
			return;
		}

		if(f.hasClass('field_reference')){
			var opt=f.find('option[value='+value+']');

			if(opt.length){
				// If it was found - then set value, should change dropdown
				f.val(value).change().trigger('change_ref');
				return;
			}

			var self=this;

			this.reloadField(field_name,null,function(){
				var f=$('#'+self.id+'_'+field_name);
				var opt=f.find('option[value='+value+']');
				if(opt.length){
					f.val(value).change().trigger('change_ref');
				}else{
					console.log('even after field reload, couldnt select ',value,' for ',field_name);
				}
			});
			return;
		}

		f.val(value).change();
	},
	reloadField: function(field_name,url,fn,notrigger){
		var field_id=this.id+'_'+field_name;
		if(!url)url=this.base_url;
		console.log('Field reloading: ',field_name);

		url=$.atk4.addArgument(url,this.id+'_cut_field',field_id);
		var f=$("#"+field_id);

		if(!notrigger)f.trigger('reload_field');

		//if(f.hasClass('field_reference')){
			var f2=f.closest('.atk-form-field');
			//f.remove();
			f=f2;

		//}
		var c=this._getChanged();this._setChanged(false);
		f.atk4_load(url,fn);
		this._setChanged(c);
	},
	fieldError: function(field_name,error){

		if(this.options.error_handler){
			// Allows you to define custom error display handler
			return this.options.error_handler(field_name,error);
		}

		var field=
			typeof(field_name)=='string'?
				$('#'+this.id+'_'+field_name):
				field_name;

		if(!field.length){
			field=this.form.find('[name="'+field_name+'"]');
		}
		if(!field.length){
			alert('Field not found: '+field_name+', error is: '+error);
			return;
		}

		if(!error || error=='0')error="must be specified properly";

		field.focus();

		//field.closest('.form_field').find('.field_hint').hide();
		field.closest('form').find('.field_error').remove();

		// highlight field
		var field_highlight=field.closest('.atk-form-row').addClass('has-error').find('.atk-form-field');

		// Clear previous errors
		field_highlight.children('.atk-form-error').remove();

		if(!this.template['field_error'].length){
			// no template, use alert;
			alert(error);
			return;
		}
		var error_bl=this.template['field_error'].clone();

        // One of the below would find the text. This is faster appreach than
        // doing find('*').andSelf().filter('.field-error-text');
		error_bl.find('.field-error-text').
            add(error_bl.filter('.field-error-text')).text(error);

		error_bl.appendTo(field_highlight).fadeIn();

		this.form.addClass('form_has_error');

		/*
		h=$(//'

'+error+'');
		 '

'+
			 error+'

').insertAfter(field_highlight);
		*/

		error_bl.click(function(){ $(this).closest('.has-error').removeClass('has-error'); error_bl.remove(); });

		var self=this;

		// make it remove error automatically when edited
		field.bind('change.errorhide',function(){
			var t=$(this);
			t.unbind('change.errorhide');

			self.form.removeClass('form_has_error');
			field_highlight.closest('.has-error').removeClass('has-error');
			error_bl.fadeOut(function(){ error_bl.remove(); });
		});
	},
	clearError: function(field){
		if(field){
			field=field.closest('.has-error');
		}else{
			field=this.form.find('.has-error');
		}
		field.find('.atk-form-error').remove();
		field.removeClass('has-error');

		//if(!this.form.find('.field_has_error').length)this.form.removeClass('form_has_error');
	},
	submitForm: function(btn){
		var params={}, form=this;
		if(form.loading){
			$.univ().loadingInProgress();
			return false;
		}

		// btn is clicked
		var richtext=this.element.find('.atk4_richtext');
		if(richtext.length)richtext.atk4_richtext('changeHTML');
		params=this.element.find(":input").serializeArray()
		if(btn){
            for (var el in params){
                if (params[el].name == 'ajax_submit'){
                    params[el].value=btn;
                    break;
                }
            }
        }

		var properties={
			type: "POST",
			url: this.form.attr('action')
		};

		form.loading=true;
		$.atk4.get(properties,params,function(res){
			var c=form._getChanged();form._setChanged(false);

			if(!$.atk4._checkSession(res))return;
			/*
			if(res.substr(0,5)=='ERROR'){
				$.univ().dialogOK('Error','There was error with your request. System maintainers have been notified.');
				return;
			}
			*/
			try {
				eval(res);
			}catch(e){
				//while some browsers prevents popup we better use alert
				w=window.open(null,null,'height=400,width=700,location=no,menubar=no,scrollbars=yes,status=no,titlebar=no,toolbar=no');
				if(w){
					w.document.write('
Error in AJAX response: '+e+'
');
					w.document.write(res);
					w.document.write('<input type=button onclick="window.close()" value="Close">');
				}else{
					alert("Error in AJAX response: "+e+"\n"+res);
				}
			}
			form.loading=false;
			form._setChanged(c);
		},function(){
			form.loading=false;
		});
	}
});
<|endoftext|>


<commit_before>$(document).ready(function () {
  function initialize() {
    //set styles for maps with bike routes
    var bikeStyles = [
      {
        "featureType": "road.highway",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "poi",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "administrative",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "water",
        "elementType": "labels",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "water",
        "elementType": "geometry.fill",
        "stylers": [
          { "color": "#f3f3f3" },
          { "visibility": "on" }
        ]
      },{
        "featureType": "transit",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "road",
        "elementType": "labels",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "landscape",
        "elementType": "geometry.fill",
        "stylers": [
          { "color": "#ffffff" }
        ]
      },{
        "featureType": "road",
        "elementType": "geometry.stroke",
        "stylers": [
          { "color": "#ffffff" }
        ]
      },{
        "featureType": "landscape",
        "elementType": "labels",
        "stylers": [
          { "visibility": "off" }
        ]
      }
    ]

    //set styles for maps with car routes
    var carStyles = [
      {
        "featureType": "poi",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "administrative",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "water",
        "elementType": "labels",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "water",
        "elementType": "geometry.fill",
        "stylers": [
          { "color": "#f3f3f3" },
          { "visibility": "on" }
        ]
      },{
        "featureType": "landscape",
        "elementType": "geometry.fill",
        "stylers": [
          { "color": "#ffffff" },
          { "visibility": "on" }
        ]
      },{
        "featureType": "road",
        "elementType": "geometry",
        "stylers": [
          { "color": "#a75d53" }
        ]
      },{
        "featureType": "road",
        "elementType": "labels",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "transit",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "landscape",
        "elementType": "labels",
        "stylers": [
          { "visibility": "off" }
        ]
      }
    ]

    //cities names, coords
    var cities = [
      ['New York', 40.713658, -73.981054],
      ['Los Angeles', 34.0194, -118.4108],
      ['Chicago', 41.8376, -87.6818],
      ['Houston', 29.7805, -95.3863],
      ['Philadelphia', 40.0094, -75.1333],
      ['Phoenix', 33.5722, -112.088],
      ['San Antonio', 29.4724, -98.5251],
      ['San Diego', 29.4724, -98.5251],
      ['Dallas', 32.7757, -96.7967],
      ['San Jose' , 37.2969, -121.8193],
      ['Austin', 30.3072, -97.756],
      ['Indianapolis', 39.7767, -86.1459],
      ['Jacksonville', 30.337, -81.6613],
      ['San Francisco', 37.7751, -122.4193],
      ['Columbus', 39.9848, -82.985],
      ['Charlotte', 35.2087, -80.8307],
      ['Fort Worth', 32.7795, -97.3463],
      ['Detroit', 42.383, -83.1022],
      ['El Paso', 31.8484, -106.427],
      ['Memphis ', 35.1035, -89.9785]
    ]

    //function to set the center of the map for each city and other options
    function setMapOptions(lat, lng) {
      var mapOptions = {
        center: { lat: lat, lng: lng},
        zoom: 12,
        disableDefaultUI: true,
        scrollwheel: false,
        draggable: false,
      };
      return mapOptions
    }

    //load a city recursive wrapper to load them in order/speed up mobile loading perception
    function loadCity(cities, windowWidth) {
      if (cities.length){
        currentLength = cities.length
        addDivs(windowWidth)
        mapOptions = setMapOptions(cities[0][1],cities[0][2])

        //make the bike map
        bikeMap = new google.maps.Map(document.getElementById('bike-'+cities[0][0]),
        mapOptions);
        bikeMap.setOptions({styles: bikeStyles});
        var bikeLayer = new google.maps.BicyclingLayer();
        bikeLayer.setMap(bikeMap);

        //create the car map
        var carMap = new google.maps.Map(document.getElementById('car-'+cities[0][0]),
        mapOptions);
        carMap.setOptions({styles: carStyles});

        var bikeLoaded = false
        var carLoaded = false

        //usually the bike map will finish before the car map, call the next city to load
        google.maps.event.addListenerOnce(bikeMap, 'tilesloaded', function(){
          bikeLoaded = true;
          google.maps.event.addListenerOnce(carMap, 'tilesloaded', function(){
            if (cities.length -1 === currentLength - 1) {
              cities.splice(0, 1);
              loadCity(cities, windowWidth);
            }
          });
        });

        //sometimes car map loads first, call the next city to load
        google.maps.event.addListenerOnce(carMap, 'tilesloaded', function(){
          carLoaded = true;
          google.maps.event.addListenerOnce(bikeMap, 'tilesloaded', function(){
            if (cities.length -1 === currentLength - 1) {
              cities.splice(0, 1);
              loadCity(cities, windowWidth);
            }
          });
        });

        //sometimes a map will not load, call the next city to load
        setTimeout(function(){
          if (!bikeLoaded || !carLoaded) {
            cities.splice(0, 1);
            loadCity(cities, windowWidth);
          }
        }, 2000);

      } else {
        return
      }
    }

    function addDivs(windowWidth) {
      if (window.innerWidth >= 768){
        $("#mainSqueeze").append(
        '
'+
          '

'+cities[0][0]+'

'+
          '

'+
        '
'+
        '
'+
          '

'+
          '

'+
          '

'+
        '
'+
        '
'+
          '

'+
        '
'
        );
      } else {
        $("#mainSqueeze").append(
        '
'+
          '

'+cities[0][0]+'

'+
          '

'+
        '
'+
        '
'+
          '

'+
          '

'+
          '

'+
        '
'+
        '
'+
          '

'+
        '
'
        );
      }
    }

  //run the above
  windowWidth = window.innerWidth;
  loadCity(cities, windowWidth)

  }
  google.maps.event.addDomListener(window, 'load', initialize);
});<commit_msg>disable doubleclick zoom<commit_after>$(document).ready(function () {
  function initialize() {
    //set styles for maps with bike routes
    var bikeStyles = [
      {
        "featureType": "road.highway",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "poi",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "administrative",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "water",
        "elementType": "labels",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "water",
        "elementType": "geometry.fill",
        "stylers": [
          { "color": "#f3f3f3" },
          { "visibility": "on" }
        ]
      },{
        "featureType": "transit",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "road",
        "elementType": "labels",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "landscape",
        "elementType": "geometry.fill",
        "stylers": [
          { "color": "#ffffff" }
        ]
      },{
        "featureType": "road",
        "elementType": "geometry.stroke",
        "stylers": [
          { "color": "#ffffff" }
        ]
      },{
        "featureType": "landscape",
        "elementType": "labels",
        "stylers": [
          { "visibility": "off" }
        ]
      }
    ]

    //set styles for maps with car routes
    var carStyles = [
      {
        "featureType": "poi",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "administrative",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "water",
        "elementType": "labels",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "water",
        "elementType": "geometry.fill",
        "stylers": [
          { "color": "#f3f3f3" },
          { "visibility": "on" }
        ]
      },{
        "featureType": "landscape",
        "elementType": "geometry.fill",
        "stylers": [
          { "color": "#ffffff" },
          { "visibility": "on" }
        ]
      },{
        "featureType": "road",
        "elementType": "geometry",
        "stylers": [
          { "color": "#a75d53" }
        ]
      },{
        "featureType": "road",
        "elementType": "labels",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "transit",
        "stylers": [
          { "visibility": "off" }
        ]
      },{
        "featureType": "landscape",
        "elementType": "labels",
        "stylers": [
          { "visibility": "off" }
        ]
      }
    ]

    //cities names, coords
    var cities = [
      ['New York', 40.713658, -73.981054],
      ['Los Angeles', 34.0194, -118.4108],
      ['Chicago', 41.8376, -87.6818],
      ['Houston', 29.7805, -95.3863],
      ['Philadelphia', 40.0094, -75.1333],
      ['Phoenix', 33.5722, -112.088],
      ['San Antonio', 29.4724, -98.5251],
      ['San Diego', 29.4724, -98.5251],
      ['Dallas', 32.7757, -96.7967],
      ['San Jose' , 37.2969, -121.8193],
      ['Austin', 30.3072, -97.756],
      ['Indianapolis', 39.7767, -86.1459],
      ['Jacksonville', 30.337, -81.6613],
      ['San Francisco', 37.7751, -122.4193],
      ['Columbus', 39.9848, -82.985],
      ['Charlotte', 35.2087, -80.8307],
      ['Fort Worth', 32.7795, -97.3463],
      ['Detroit', 42.383, -83.1022],
      ['El Paso', 31.8484, -106.427],
      ['Memphis ', 35.1035, -89.9785]
    ]

    //function to set the center of the map for each city and other options
    function setMapOptions(lat, lng) {
      var mapOptions = {
        center: { lat: lat, lng: lng},
        zoom: 12,
        disableDoubleClickZoom: true,
        disableDefaultUI: true,
        scrollwheel: false,
        draggable: false,
      };
      return mapOptions
    }

    //load a city recursive wrapper to load them in order/speed up mobile loading perception
    function loadCity(cities, windowWidth) {
      if (cities.length){
        currentLength = cities.length
        addDivs(windowWidth)
        mapOptions = setMapOptions(cities[0][1],cities[0][2])

        //make the bike map
        bikeMap = new google.maps.Map(document.getElementById('bike-'+cities[0][0]),
        mapOptions);
        bikeMap.setOptions({styles: bikeStyles});
        var bikeLayer = new google.maps.BicyclingLayer();
        bikeLayer.setMap(bikeMap);

        //create the car map
        var carMap = new google.maps.Map(document.getElementById('car-'+cities[0][0]),
        mapOptions);
        carMap.setOptions({styles: carStyles});

        var bikeLoaded = false
        var carLoaded = false

        //usually the bike map will finish before the car map, call the next city to load
        google.maps.event.addListenerOnce(bikeMap, 'tilesloaded', function(){
          bikeLoaded = true;
          google.maps.event.addListenerOnce(carMap, 'tilesloaded', function(){
            if (cities.length -1 === currentLength - 1) {
              cities.splice(0, 1);
              loadCity(cities, windowWidth);
            }
          });
        });

        //sometimes car map loads first, call the next city to load
        google.maps.event.addListenerOnce(carMap, 'tilesloaded', function(){
          carLoaded = true;
          google.maps.event.addListenerOnce(bikeMap, 'tilesloaded', function(){
            if (cities.length -1 === currentLength - 1) {
              cities.splice(0, 1);
              loadCity(cities, windowWidth);
            }
          });
        });

        //sometimes a map will not load, call the next city to load
        setTimeout(function(){
          if (!bikeLoaded || !carLoaded) {
            cities.splice(0, 1);
            loadCity(cities, windowWidth);
          }
        }, 2000);

      } else {
        return
      }
    }

    function addDivs(windowWidth) {
      if (window.innerWidth >= 768){
        $("#mainSqueeze").append(
        '
'+
          '

'+cities[0][0]+'

'+
          '

'+
        '
'+
        '
'+
          '

'+
          '

'+
          '

'+
        '
'+
        '
'+
          '

'+
        '
'
        );
      } else {
        $("#mainSqueeze").append(
        '
'+
          '

'+cities[0][0]+'

'+
          '

'+
        '
'+
        '
'+
          '

'+
          '

'+
          '

'+
        '
'+
        '
'+
          '

'+
        '
'
        );
      }
    }

  //run the above
  windowWidth = window.innerWidth;
  loadCity(cities, windowWidth)

  }
  google.maps.event.addDomListener(window, 'load', initialize);
});<|endoftext|>