<commit_before>import TreeSubscription from './TreeSubscription';
import nextTick from 'next-tick';

var NO_INDEX = -1;
var ZERO_LENGTH = 0;
var REMOVE_ONE_ITEM = 1;
var ONE_BEFORE_LAST_INDEX = -1;
var FIRST_INDEX = 0;
var SECOND_INDEX = 1;

var HAS_PROCESS_ENV_NODE_ENV = typeof process !== 'undefined' && Object.prototype.hasOwnProperty(process, 'env') && Object.prototype.hasOwnProperty(process.env, 'NODE_ENV');
var IS_PRODUCTION = HAS_PROCESS_ENV_NODE_ENV && process.env.NODE_ENV === 'production';

function testSelectorValidity(selector, functionName) {
    var selectorToString = Object.prototype.toString.call(selector);
    if (selectorToString !== '[object Array]') {
        try {selectorToString = selector.toString();} catch(e) {} // eslint-disable-line
        console.warn('Insula: invalid selector "' + (selectorToString) + '" pass to ' + functionName); // eslint-disable-line
    }
}

export default function Store(initialState, middleware) {
    this.listeners = {};
    this.subscriptions = new TreeSubscription(this);
    this.eventOptions = this.createEventOptions();
    this.middleware = middleware || [];

    this.callSubscribers = this.callSubscribers.bind(this);
    this.nextSubscriberCalls = [];

    this.setState(initialState !== undefined ? initialState : {});

    // call any middleware constructors
    this.callMiddleware('constructor');
}

Store.prototype.callMiddleware = function callMiddleware(type, args) {
    var currentArgs = args;
    for (var i = 0; i < this.middleware.length; i++) {
        var middlewareItem = this.middleware[i];
        if (middlewareItem.hasOwnProperty(type)) {
            currentArgs = middlewareItem[type].call(this, currentArgs);
        }
    }
    return currentArgs;
};

Store.prototype.getState = function getState() {
    return this.callMiddleware('getState', [this.state])[FIRST_INDEX];
};

Store.prototype.getPartialState = function getPartialState(selector) {
    var processedSelector = this.callMiddleware('getPartialStateParseSelector', [selector])[FIRST_INDEX];

    if (!IS_PRODUCTION) {
        testSelectorValidity(processedSelector, 'getPartialState');
    }

    return this.callMiddleware('getPartialStateReturn', [this.accessStateAtSelector(processedSelector)])[FIRST_INDEX];
};

Store.prototype.accessStateAtSelector = function accessStateAtSelector(selector) {
    var currentValue = this.getState();

    for (var i = 0; i < selector.length; i++) {
        var key = selector[i];
        if (currentValue.hasOwnProperty(key)) {
            currentValue = currentValue[key];
        } else {
            return null;
        }
    }

    return currentValue;
};

Store.prototype.setState = function setState(state) {
    this.state = this.callMiddleware('setState', [state])[FIRST_INDEX];
    this.callSubscribersUnderSelector([]);
};

Store.prototype.setPartialState = function setPartialState(selector, value) {
    var args = this.callMiddleware('setPartialState', [selector, value]);
    var processedSelector = args[FIRST_INDEX];

    if (!IS_PRODUCTION) {
        testSelectorValidity(processedSelector, 'setPartialState');
    }

    var processedValue = args[SECOND_INDEX];
    this.setStateAtSelector(processedSelector, processedValue);
    this.callSubscribersUnderSelector(processedSelector);
};

Store.prototype.setStateAtSelector = function setStateAtSelector(selector, value) {
    var lastKey = selector[selector.length + ONE_BEFORE_LAST_INDEX];

    var currentValue = this.getState();
    for (var i = 0; i < selector.length + ONE_BEFORE_LAST_INDEX; i++) {
        var key = selector[i];
        if (currentValue.hasOwnProperty(key) === false) {
            currentValue[key] = {};
        }
        currentValue = currentValue[key];
    }

    currentValue[lastKey] = value;
};

Store.prototype.on = function on(event, listener) {
    if (this.listeners.hasOwnProperty(event) === false) {
        this.listeners[event] = [];
    }
    this.listeners[event].push(listener);
};

Store.prototype.off = function off(event, listener) {
    if (this.listeners.hasOwnProperty(event)) {
        var eventListeners = this.listeners[event];
        var listenerIdx = eventListeners.indexOf(listener);
        if (listenerIdx !== NO_INDEX) {
            eventListeners.splice(listenerIdx, REMOVE_ONE_ITEM);
        }
    }
};

Store.prototype.dispatch = function dispatch(event, payload) {
    var processed = this.callMiddleware('dispatch', [event, payload]);
    var processedEvent = processed[FIRST_INDEX];
    var processedPayload = processed[SECOND_INDEX];

    var listeners = this.listeners[processedEvent];
    if (listeners !== undefined) {
        var eventOptions = this.getEventOptions();
        for (var i = 0; i < listeners.length; i++) {
            listeners[i](processedPayload, eventOptions);
        }
    }
};

Store.prototype.createEventOptions = function createEventOptions() {
    return {
        dispatch: this.dispatch.bind(this),
        getState: this.getState.bind(this),
        setState: this.setState.bind(this),
        setPartialState: this.setPartialState.bind(this),
        getPartialState: this.getPartialState.bind(this),
    };
};

Store.prototype.getEventOptions = function getEventOptions() {
    return this.eventOptions;
};

Store.prototype.subscribeToState = function subscribeToState(selectors, listener) {
    var processed = this.callMiddleware('subscribeToState', [selectors, listener]);
    var processedSelectors = processed[FIRST_INDEX];
    var processedListener = processed[SECOND_INDEX];

    if (!IS_PRODUCTION) {
        testSelectorValidity(processedSelectors, 'subscribeToState');

        for (var i = 0; i < processedSelectors.length; i++) {
            testSelectorValidity(processedSelectors[i], 'subscribeToState, selector at index ' + i);
        }
    }

    var store = this;
    var stateChangeListener = function() {
        // get state values
        var stateValues = [];
        for (var i = 0; i < processedSelectors.length; i++) {
            stateValues.push(store.getPartialState(processedSelectors[i]));
        }

        // call listener with all the state values
        processedListener(stateValues);
    };

    for (i = 0; i < processedSelectors.length; i++) {
        this.subscriptions.subscribeSelector(processedSelectors[i], stateChangeListener);
    }

    return function unsubscribeToState() {
        for (var i = 0; i < processedSelectors.length; i++) {
            store.subscriptions.unsubscribeSelector(processedSelectors[i], stateChangeListener);
        }
    };
};

Store.prototype.callSubscribersUnderSelector = function callSubscribersUnderSelector(selector) {
    var subscribers = this.subscriptions.collectSubscribers(selector);

    if (this.nextSubscriberCalls.length === ZERO_LENGTH) {
        nextTick(this.callSubscribers);
    }

    for (var i = 0; i < subscribers.length; i++) {
        var subscriber = subscribers[i];
        if (this.nextSubscriberCalls.indexOf(subscriber) === NO_INDEX) {
            this.nextSubscriberCalls.push(subscriber);
        }
    }
};

Store.prototype.callSubscribers = function callSubscribers() {
    for (var i = 0; i < this.nextSubscriberCalls.length; i++) {
        this.nextSubscriberCalls[i]();
    }
    this.nextSubscriberCalls.length = 0;
};<commit_msg>Update for some readability<commit_after>import TreeSubscription from './TreeSubscription';
import nextTick from 'next-tick';

var NO_INDEX = -1;
var ZERO_LENGTH = 0;
var REMOVE_ONE_ITEM = 1;
var ONE_BEFORE_LAST_INDEX = -1;
var FIRST_INDEX = 0;
var SECOND_INDEX = 1;

var HAS_PROCESS_ENV_NODE_ENV = typeof process !== 'undefined' && Object.prototype.hasOwnProperty(process, 'env') && Object.prototype.hasOwnProperty(process.env, 'NODE_ENV');
var IS_PRODUCTION = HAS_PROCESS_ENV_NODE_ENV && process.env.NODE_ENV === 'production';

function testSelectorValidity(selector, functionName) {
    if (!Array.isArray(selector)) {
        var selectorToString = Object.prototype.toString.call(selector);
        try {selectorToString = selector.toString();} catch(e) {} // eslint-disable-line
        console.warn('Insula: invalid selector "' + (selectorToString) + '" pass to ' + functionName); // eslint-disable-line
    }
}

export default function Store(initialState, middleware) {
    this.listeners = {};
    this.subscriptions = new TreeSubscription(this);
    this.eventOptions = this.createEventOptions();
    this.middleware = middleware || [];

    this.callSubscribers = this.callSubscribers.bind(this);
    this.nextSubscriberCalls = [];

    this.setState(initialState !== undefined ? initialState : {});

    // call any middleware constructors
    this.callMiddleware('constructor');
}

Store.prototype.callMiddleware = function callMiddleware(type, args) {
    var currentArgs = args;
    for (var i = 0; i < this.middleware.length; i++) {
        var middlewareItem = this.middleware[i];
        if (middlewareItem.hasOwnProperty(type)) {
            currentArgs = middlewareItem[type].call(this, currentArgs);
        }
    }
    return currentArgs;
};

Store.prototype.getState = function getState() {
    return this.callMiddleware('getState', [this.state])[FIRST_INDEX];
};

Store.prototype.getPartialState = function getPartialState(selector) {
    var processedSelector = this.callMiddleware('getPartialStateParseSelector', [selector])[FIRST_INDEX];

    if (!IS_PRODUCTION) {
        testSelectorValidity(processedSelector, 'getPartialState');
    }

    return this.callMiddleware('getPartialStateReturn', [this.accessStateAtSelector(processedSelector)])[FIRST_INDEX];
};

Store.prototype.accessStateAtSelector = function accessStateAtSelector(selector) {
    var currentValue = this.getState();

    for (var i = 0; i < selector.length; i++) {
        var key = selector[i];
        if (currentValue.hasOwnProperty(key)) {
            currentValue = currentValue[key];
        } else {
            return null;
        }
    }

    return currentValue;
};

Store.prototype.setState = function setState(state) {
    this.state = this.callMiddleware('setState', [state])[FIRST_INDEX];
    this.callSubscribersUnderSelector([]);
};

Store.prototype.setPartialState = function setPartialState(selector, value) {
    var args = this.callMiddleware('setPartialState', [selector, value]);
    var processedSelector = args[FIRST_INDEX];

    if (!IS_PRODUCTION) {
        testSelectorValidity(processedSelector, 'setPartialState');
    }

    var processedValue = args[SECOND_INDEX];
    this.setStateAtSelector(processedSelector, processedValue);
    this.callSubscribersUnderSelector(processedSelector);
};

Store.prototype.setStateAtSelector = function setStateAtSelector(selector, value) {
    var lastKey = selector[selector.length + ONE_BEFORE_LAST_INDEX];

    var currentValue = this.getState();
    for (var i = 0; i < selector.length + ONE_BEFORE_LAST_INDEX; i++) {
        var key = selector[i];
        if (currentValue.hasOwnProperty(key) === false) {
            currentValue[key] = {};
        }
        currentValue = currentValue[key];
    }

    currentValue[lastKey] = value;
};

Store.prototype.on = function on(event, listener) {
    if (this.listeners.hasOwnProperty(event) === false) {
        this.listeners[event] = [];
    }
    this.listeners[event].push(listener);
};

Store.prototype.off = function off(event, listener) {
    if (this.listeners.hasOwnProperty(event)) {
        var eventListeners = this.listeners[event];
        var listenerIdx = eventListeners.indexOf(listener);
        if (listenerIdx !== NO_INDEX) {
            eventListeners.splice(listenerIdx, REMOVE_ONE_ITEM);
        }
    }
};

Store.prototype.dispatch = function dispatch(event, payload) {
    var processed = this.callMiddleware('dispatch', [event, payload]);
    var processedEvent = processed[FIRST_INDEX];
    var processedPayload = processed[SECOND_INDEX];

    var listeners = this.listeners[processedEvent];
    if (listeners !== undefined) {
        var eventOptions = this.getEventOptions();
        for (var i = 0; i < listeners.length; i++) {
            listeners[i](processedPayload, eventOptions);
        }
    }
};

Store.prototype.createEventOptions = function createEventOptions() {
    return {
        dispatch: this.dispatch.bind(this),
        getState: this.getState.bind(this),
        setState: this.setState.bind(this),
        setPartialState: this.setPartialState.bind(this),
        getPartialState: this.getPartialState.bind(this),
    };
};

Store.prototype.getEventOptions = function getEventOptions() {
    return this.eventOptions;
};

Store.prototype.subscribeToState = function subscribeToState(selectors, listener) {
    var processed = this.callMiddleware('subscribeToState', [selectors, listener]);
    var processedSelectors = processed[FIRST_INDEX];
    var processedListener = processed[SECOND_INDEX];
    var i;

    if (!IS_PRODUCTION) {
        testSelectorValidity(processedSelectors, 'subscribeToState');

        for (i = 0; i < processedSelectors.length; i++) {
            testSelectorValidity(processedSelectors[i], 'subscribeToState, selector at index ' + i);
        }
    }

    var store = this;
    var stateChangeListener = function() {
        // get state values
        var stateValues = [];
        for (var i = 0; i < processedSelectors.length; i++) {
            stateValues.push(store.getPartialState(processedSelectors[i]));
        }

        // call listener with all the state values
        processedListener(stateValues);
    };

    for (i = 0; i < processedSelectors.length; i++) {
        this.subscriptions.subscribeSelector(processedSelectors[i], stateChangeListener);
    }

    return function unsubscribeToState() {
        for (var i = 0; i < processedSelectors.length; i++) {
            store.subscriptions.unsubscribeSelector(processedSelectors[i], stateChangeListener);
        }
    };
};

Store.prototype.callSubscribersUnderSelector = function callSubscribersUnderSelector(selector) {
    var subscribers = this.subscriptions.collectSubscribers(selector);

    if (this.nextSubscriberCalls.length === ZERO_LENGTH) {
        nextTick(this.callSubscribers);
    }

    for (var i = 0; i < subscribers.length; i++) {
        var subscriber = subscribers[i];
        if (this.nextSubscriberCalls.indexOf(subscriber) === NO_INDEX) {
            this.nextSubscriberCalls.push(subscriber);
        }
    }
};

Store.prototype.callSubscribers = function callSubscribers() {
    for (var i = 0; i < this.nextSubscriberCalls.length; i++) {
        this.nextSubscriberCalls[i]();
    }
    this.nextSubscriberCalls.length = 0;
};<|endoftext|>


<commit_before>Alloy.Globals.extendsBaseRowController($, arguments[0]);

$.onRowTap = function(e){
	if($.$model.xGet("ownerUserId") === Alloy.Models.User.id){
		Alloy.Globals.openWindow("project/projectShareAuthorizationForm", {$model : $.$model});
		return false;
	} else if($.$model.xGet("friendUserId") === Alloy.Models.User.id){
		Alloy.Globals.openWindow("project/projectSharedWithMeAuthorizationForm", {
			$model : $.$model,
			saveableMode : "read"
		});
		return false;
	}else{
		alert("只能查看自己的权限");
	}
};

$.makeContextMenu = function(e, isSelectMode) {
	var menuSection = Ti.UI.createTableViewSection({
		headerTitle : "共享属性操作"
	});
	// menuSection.add($.createContextMenuItem("共享详细", function() {
		// Alloy.Globals.openWindow("project/projectShareAuthorizationForm", {
			// $model : $.$model
		// });
	// },isSelectMode || $.$model.xGet("friendUserId") === Alloy.Models.User.id || $.$model.xGet("ownerUserId") !== Alloy.Models.User.id));
	// menuSection.add($.createContextMenuItem("移除共享", function() {
		// // $.deleteModel();
		// Alloy.Globals.confirm("移除共享", "确定要把好友移除出共享列表？", function() {
			// //如果projectShareAuthorization中的数据都为0说明跟好友间没有账务往来，允许删除
			// // if($.$model.xGet("friendUserId") !== Alloy.Models.User.id){
				// var projectAuthorizationIds = [];
				// var subProjectShareAuthorizations = [];
				// projectAuthorizationIds.push($.$model.xGet("id"));
				// var subProjects = $.$model.xGet("project").xGetDescendents("subProjects");
				// subProjects.forEach(function(subProject) {
					// var subProjectShareAuthorization = Alloy.createModel("ProjectShareAuthorization").xFindInDb({
						// projectId : subProject.xGet("id"),
						// friendUserId : $.$model.xGet("friendUserId"),
						// state : "Accept"
					// });
					// if (subProjectShareAuthorization && subProjectShareAuthorization.id) {
						// subProjectShareAuthorizations.push(subProjectShareAuthorization);
						// projectAuthorizationIds.push(subProjectShareAuthorization.id);
					// }
				// });
				// Alloy.Globals.Server.loadData("ProjectShareAuthorization", projectAuthorizationIds, function(collection) {
					// var projectShareAuthorization = collection.get($.$model.xGet("id"));
					// if (collection.length > 0) {
						// if($.$model.xGet("actualTotalIncome") === 0
						// && $.$model.xGet("actualTotalExpense") === 0
						// && $.$model.xGet("apportionedTotalIncome") === 0
						// && $.$model.xGet("apportionedTotalExpense") === 0
						// && $.$model.xGet("sharedTotalIncome") === 0
						// && $.$model.xGet("sharedTotalExpense") === 0
						// && projectShareAuthorization.xGet("actualTotalIncome") === 0
						// && projectShareAuthorization.xGet("actualTotalExpense") === 0
						// && projectShareAuthorization.xGet("apportionedTotalIncome") === 0
						// && projectShareAuthorization.xGet("apportionedTotalExpense") === 0
						// && projectShareAuthorization.xGet("sharedTotalIncome") === 0
						// && projectShareAuthorization.xGet("sharedTotalExpense") === 0){
							// var editSharePercentageAuthorization = [];
							// var subProjectShareAuthorizationIds = [];
							// //重新计算计算其他成员的占股
							// deleteSharePercentage($.$model,editSharePercentageAuthorization);
							// //把子项目移除共享
							// subProjectShareAuthorizations.forEach(function(subProjectShareAuthorization) {
								// var subProjectShareAuthorizationInServer = collection.get(subProjectShareAuthorization.xGet("id"));
//
								// if(subProjectShareAuthorization.xGet("actualTotalIncome") === 0
								// && subProjectShareAuthorization.xGet("actualTotalExpense") === 0
								// && subProjectShareAuthorization.xGet("apportionedTotalIncome") === 0
								// && subProjectShareAuthorization.xGet("apportionedTotalExpense") === 0
								// && subProjectShareAuthorization.xGet("sharedTotalIncome") === 0
								// && subProjectShareAuthorization.xGet("sharedTotalExpense") === 0
								// && subProjectShareAuthorizationInServer.xGet("actualTotalIncome") === 0
								// && subProjectShareAuthorizationInServer.xGet("actualTotalExpense") === 0
								// && subProjectShareAuthorizationInServer.xGet("apportionedTotalIncome") === 0
								// && subProjectShareAuthorizationInServer.xGet("apportionedTotalExpense") === 0
								// && subProjectShareAuthorizationInServer.xGet("sharedTotalIncome") === 0
								// && subProjectShareAuthorizationInServer.xGet("sharedTotalExpense") === 0){
//
									// subProjectShareAuthorizationIds.push(subProjectShareAuthorization.xGet("id"));
									// subProjectShareAuthorization.xSet("state", "Delete");
									// subProjectShareAuthorization.xSave({
										// syncFromServer : true
									// });
									// //重新计算计算子项目其他成员的占股
									// deleteSharePercentage(subProjectShareAuthorization,editSharePercentageAuthorization);
									// editSharePercentageAuthorization.push(subProjectShareAuthorization.toJSON());
								// }
							// });
//
							// $.$model.xSet("state", "Delete");
							// editSharePercentageAuthorization.push($.$model.toJSON());
							// //去服务器上修改刚刚移除共享的成员
							// Alloy.Globals.Server.putData(editSharePercentageAuthorization, function(data) {
								// //发送移除消息给好友
								// Alloy.Globals.Server.sendMsg({
									// id : guid(),
									// "toUserId" : $.$model.xGet("friendUserId"),
									// "fromUserId" : Alloy.Models.User.xGet("id"),
									// "type" : "Project.Share.Delete",
									// "messageState" : "unread",
									// "messageTitle" : "移除共享",
									// "date" : (new Date()).toISOString(),
									// "detail" : "用户" + Alloy.Models.User.xGet("userName") + "已经将您移除出共享项目：" + $.$model.xGet("project").xGet("name"),
									// "messageBoxId" : $.$model.xGet("friendUser").xGet("messageBoxId"),
									// "messageData" : JSON.stringify({
										// shareAllSubProjects : $.$model.xGet("shareAllSubProjects"),
										// projectShareAuthorizationId : $.$model.xGet("id"),
										// subProjectShareAuthorizationIds : subProjectShareAuthorizationIds
									// })
								// }, function() {
									// $.$model.xSave({
										// syncFromServer : true
									// });
								// }, function(e) {
									// alert(e.__summary.msg);
								// });
							// }, function(e) {
								// alert(e.__summary.msg);
							// });
						// }else{
							// alert("该成员在这个项目下跟其他成员有账务往来，不能移除");
						// }
					// }
				// }, function(e) {
					// alert(e.__summary.msg);
				// });
			// // }
		// });
	// }, isSelectMode || $.$model.xGet("friendUserId") === Alloy.Models.User.id || $.$model.xGet("ownerUserId") !== Alloy.Models.User.id));
	return menuSection;
};

//移除共享时重新计算其他成员的股份
function deleteSharePercentage(projectShareAuthorization,editSharePercentageAuthorization){
	var averageSharePercentageCollections = [];
	var fixedSharePercentageCollections = [];
	var fixedSharePercentage = 0;
	var localProjectShareAuthorization = null;
	var acceptProjectShareAuthorizations = Alloy.createCollection("ProjectShareAuthorization").xSearchInDb({
		projectId : projectShareAuthorization.xGet("project").xGet("id"),
		state : "Accept"
	});
	acceptProjectShareAuthorizations.map(function(acceptProjectShareAuthorization){
		if(acceptProjectShareAuthorization.xGet("friendUserId") === Alloy.Models.User.id){
			localProjectShareAuthorization = acceptProjectShareAuthorization;
		}
		if(acceptProjectShareAuthorization.xGet("id") !== projectShareAuthorization.xGet("id")){
			if(acceptProjectShareAuthorization.xGet("sharePercentageType") === "Fixed"){
				fixedSharePercentage = fixedSharePercentage + acceptProjectShareAuthorization.xGet("sharePercentage");
				fixedSharePercentageCollections.push(acceptProjectShareAuthorization);
			}else{
				averageSharePercentageCollections.push(acceptProjectShareAuthorization);
			}
		}
	});
	var averageLength = averageSharePercentageCollections.length;
	var averageTotalPercentage = 100 - fixedSharePercentage;

	if(averageLength > 0){
		var averagePercentage = Number((averageTotalPercentage/averageLength).toFixed(4));
		var toFixedAveragePercentage = 0;
		averageSharePercentageCollections.map(function(averageSharePercentageCollection){
			toFixedAveragePercentage = toFixedAveragePercentage + averagePercentage;
			averageSharePercentageCollection.xSet("sharePercentage" , averagePercentage);
			editSharePercentageAuthorization.push(averageSharePercentageCollection.toJSON());
			averageSharePercentageCollection.xSave({
							syncFromServer : true
						});
		});
		if(averageTotalPercentage !== toFixedAveragePercentage){
			if(localProjectShareAuthorization){
				localProjectShareAuthorization.xSet("sharePercentage", Number((localProjectShareAuthorization.xGet("sharePercentage") + averageTotalPercentage - toFixedAveragePercentage).toFixed(4)));
				editSharePercentageAuthorization.push(localProjectShareAuthorization.toJSON());
				localProjectShareAuthorization.xSave({
							syncFromServer : true
						});
			}
		}
	}else{
		localProjectShareAuthorization.xSet("sharePercentage" , localProjectShareAuthorization.xGet("sharePercentage") + averageTotalPercentage);
		editSharePercentageAuthorization.push(localProjectShareAuthorization.toJSON());
		localProjectShareAuthorization.xSave({
							syncFromServer : true
						});
	}
}
// function setWaitForAccept() {
	// if ($.$model.xGet("state") === "Wait") {
		// $.checkAccept.setVisible(true);
	// }
// }
// $.onWindowOpenDo(function() {
	// setWaitForAccept();
// });
setActualTotalMoneyColor();
function setActualTotalMoneyColor(){
	if($.$model.getActualTotalText() === "实际支出"){
		$.actualTotalMoney.label.setColor("#c80032");
	}else{
		$.actualTotalMoney.label.setColor("#329600");
	}
	if($.$model.getSettlementText() === "应该支出"){
		$.apportionedTotalMoney.label.setColor("#c80032");
	}else{
		$.apportionedTotalMoney.label.setColor("#329600");
	}
}

$.picture.UIInit($, $.getCurrentWindow());
$.sharePercentage.UIInit($, $.getCurrentWindow());
$.friendDisplayName.UIInit($, $.getCurrentWindow());
$.actualTotalText.UIInit($, $.getCurrentWindow());
$.actualTotalMoney.UIInit($, $.getCurrentWindow());
$.apportionedTotalText.UIInit($, $.getCurrentWindow());
$.apportionedTotalMoney.UIInit($, $.getCurrentWindow());

<commit_msg>fix #867<commit_after>Alloy.Globals.extendsBaseRowController($, arguments[0]);

$.onRowTap = function(e){
	if($.$model.xGet("ownerUserId") === Alloy.Models.User.id){
		Alloy.Globals.openWindow("project/projectShareAuthorizationForm", {$model : $.$model});
		return false;
	} else if($.$model.xGet("friendUserId") === Alloy.Models.User.id){
		Alloy.Globals.openWindow("project/projectSharedWithMeAuthorizationForm", {
			$model : $.$model,
			saveableMode : "read"
		});
		return false;
	}else{
		alert("只能查看自己的权限");
	}
};

$.makeContextMenu = function(e, isSelectMode) {
	var menuSection = Ti.UI.createTableViewSection({
		headerTitle : "共享属性操作"
	});
	// menuSection.add($.createContextMenuItem("共享详细", function() {
		// Alloy.Globals.openWindow("project/projectShareAuthorizationForm", {
			// $model : $.$model
		// });
	// },isSelectMode || $.$model.xGet("friendUserId") === Alloy.Models.User.id || $.$model.xGet("ownerUserId") !== Alloy.Models.User.id));
	// menuSection.add($.createContextMenuItem("移除共享", function() {
		// // $.deleteModel();
		// Alloy.Globals.confirm("移除共享", "确定要把好友移除出共享列表？", function() {
			// //如果projectShareAuthorization中的数据都为0说明跟好友间没有账务往来，允许删除
			// // if($.$model.xGet("friendUserId") !== Alloy.Models.User.id){
				// var projectAuthorizationIds = [];
				// var subProjectShareAuthorizations = [];
				// projectAuthorizationIds.push($.$model.xGet("id"));
				// var subProjects = $.$model.xGet("project").xGetDescendents("subProjects");
				// subProjects.forEach(function(subProject) {
					// var subProjectShareAuthorization = Alloy.createModel("ProjectShareAuthorization").xFindInDb({
						// projectId : subProject.xGet("id"),
						// friendUserId : $.$model.xGet("friendUserId"),
						// state : "Accept"
					// });
					// if (subProjectShareAuthorization && subProjectShareAuthorization.id) {
						// subProjectShareAuthorizations.push(subProjectShareAuthorization);
						// projectAuthorizationIds.push(subProjectShareAuthorization.id);
					// }
				// });
				// Alloy.Globals.Server.loadData("ProjectShareAuthorization", projectAuthorizationIds, function(collection) {
					// var projectShareAuthorization = collection.get($.$model.xGet("id"));
					// if (collection.length > 0) {
						// if($.$model.xGet("actualTotalIncome") === 0
						// && $.$model.xGet("actualTotalExpense") === 0
						// && $.$model.xGet("apportionedTotalIncome") === 0
						// && $.$model.xGet("apportionedTotalExpense") === 0
						// && $.$model.xGet("sharedTotalIncome") === 0
						// && $.$model.xGet("sharedTotalExpense") === 0
						// && projectShareAuthorization.xGet("actualTotalIncome") === 0
						// && projectShareAuthorization.xGet("actualTotalExpense") === 0
						// && projectShareAuthorization.xGet("apportionedTotalIncome") === 0
						// && projectShareAuthorization.xGet("apportionedTotalExpense") === 0
						// && projectShareAuthorization.xGet("sharedTotalIncome") === 0
						// && projectShareAuthorization.xGet("sharedTotalExpense") === 0){
							// var editSharePercentageAuthorization = [];
							// var subProjectShareAuthorizationIds = [];
							// //重新计算计算其他成员的占股
							// deleteSharePercentage($.$model,editSharePercentageAuthorization);
							// //把子项目移除共享
							// subProjectShareAuthorizations.forEach(function(subProjectShareAuthorization) {
								// var subProjectShareAuthorizationInServer = collection.get(subProjectShareAuthorization.xGet("id"));
//
								// if(subProjectShareAuthorization.xGet("actualTotalIncome") === 0
								// && subProjectShareAuthorization.xGet("actualTotalExpense") === 0
								// && subProjectShareAuthorization.xGet("apportionedTotalIncome") === 0
								// && subProjectShareAuthorization.xGet("apportionedTotalExpense") === 0
								// && subProjectShareAuthorization.xGet("sharedTotalIncome") === 0
								// && subProjectShareAuthorization.xGet("sharedTotalExpense") === 0
								// && subProjectShareAuthorizationInServer.xGet("actualTotalIncome") === 0
								// && subProjectShareAuthorizationInServer.xGet("actualTotalExpense") === 0
								// && subProjectShareAuthorizationInServer.xGet("apportionedTotalIncome") === 0
								// && subProjectShareAuthorizationInServer.xGet("apportionedTotalExpense") === 0
								// && subProjectShareAuthorizationInServer.xGet("sharedTotalIncome") === 0
								// && subProjectShareAuthorizationInServer.xGet("sharedTotalExpense") === 0){
//
									// subProjectShareAuthorizationIds.push(subProjectShareAuthorization.xGet("id"));
									// subProjectShareAuthorization.xSet("state", "Delete");
									// subProjectShareAuthorization.xSave({
										// syncFromServer : true
									// });
									// //重新计算计算子项目其他成员的占股
									// deleteSharePercentage(subProjectShareAuthorization,editSharePercentageAuthorization);
									// editSharePercentageAuthorization.push(subProjectShareAuthorization.toJSON());
								// }
							// });
//
							// $.$model.xSet("state", "Delete");
							// editSharePercentageAuthorization.push($.$model.toJSON());
							// //去服务器上修改刚刚移除共享的成员
							// Alloy.Globals.Server.putData(editSharePercentageAuthorization, function(data) {
								// //发送移除消息给好友
								// Alloy.Globals.Server.sendMsg({
									// id : guid(),
									// "toUserId" : $.$model.xGet("friendUserId"),
									// "fromUserId" : Alloy.Models.User.xGet("id"),
									// "type" : "Project.Share.Delete",
									// "messageState" : "unread",
									// "messageTitle" : "移除共享",
									// "date" : (new Date()).toISOString(),
									// "detail" : "用户" + Alloy.Models.User.xGet("userName") + "已经将您移除出共享项目：" + $.$model.xGet("project").xGet("name"),
									// "messageBoxId" : $.$model.xGet("friendUser").xGet("messageBoxId"),
									// "messageData" : JSON.stringify({
										// shareAllSubProjects : $.$model.xGet("shareAllSubProjects"),
										// projectShareAuthorizationId : $.$model.xGet("id"),
										// subProjectShareAuthorizationIds : subProjectShareAuthorizationIds
									// })
								// }, function() {
									// $.$model.xSave({
										// syncFromServer : true
									// });
								// }, function(e) {
									// alert(e.__summary.msg);
								// });
							// }, function(e) {
								// alert(e.__summary.msg);
							// });
						// }else{
							// alert("该成员在这个项目下跟其他成员有账务往来，不能移除");
						// }
					// }
				// }, function(e) {
					// alert(e.__summary.msg);
				// });
			// // }
		// });
	// }, isSelectMode || $.$model.xGet("friendUserId") === Alloy.Models.User.id || $.$model.xGet("ownerUserId") !== Alloy.Models.User.id));
	return menuSection;
};

//移除共享时重新计算其他成员的股份
function deleteSharePercentage(projectShareAuthorization,editSharePercentageAuthorization){
	var averageSharePercentageCollections = [];
	var fixedSharePercentageCollections = [];
	var fixedSharePercentage = 0;
	var localProjectShareAuthorization = null;
	var acceptProjectShareAuthorizations = Alloy.createCollection("ProjectShareAuthorization").xSearchInDb({
		projectId : projectShareAuthorization.xGet("project").xGet("id"),
		state : "Accept"
	});
	acceptProjectShareAuthorizations.map(function(acceptProjectShareAuthorization){
		if(acceptProjectShareAuthorization.xGet("friendUserId") === Alloy.Models.User.id){
			localProjectShareAuthorization = acceptProjectShareAuthorization;
		}
		if(acceptProjectShareAuthorization.xGet("id") !== projectShareAuthorization.xGet("id")){
			if(acceptProjectShareAuthorization.xGet("sharePercentageType") === "Fixed"){
				fixedSharePercentage = fixedSharePercentage + acceptProjectShareAuthorization.xGet("sharePercentage");
				fixedSharePercentageCollections.push(acceptProjectShareAuthorization);
			}else{
				averageSharePercentageCollections.push(acceptProjectShareAuthorization);
			}
		}
	});
	var averageLength = averageSharePercentageCollections.length;
	var averageTotalPercentage = 100 - fixedSharePercentage;

	if(averageLength > 0){
		var averagePercentage = Number((averageTotalPercentage/averageLength).toFixed(4));
		var toFixedAveragePercentage = 0;
		averageSharePercentageCollections.map(function(averageSharePercentageCollection){
			toFixedAveragePercentage = toFixedAveragePercentage + averagePercentage;
			averageSharePercentageCollection.xSet("sharePercentage" , averagePercentage);
			editSharePercentageAuthorization.push(averageSharePercentageCollection.toJSON());
			averageSharePercentageCollection.xSave({
							syncFromServer : true
						});
		});
		if(averageTotalPercentage !== toFixedAveragePercentage){
			if(localProjectShareAuthorization){
				localProjectShareAuthorization.xSet("sharePercentage", Number((localProjectShareAuthorization.xGet("sharePercentage") + averageTotalPercentage - toFixedAveragePercentage).toFixed(4)));
				editSharePercentageAuthorization.push(localProjectShareAuthorization.toJSON());
				localProjectShareAuthorization.xSave({
							syncFromServer : true
						});
			}
		}
	}else{
		localProjectShareAuthorization.xSet("sharePercentage" , localProjectShareAuthorization.xGet("sharePercentage") + averageTotalPercentage);
		editSharePercentageAuthorization.push(localProjectShareAuthorization.toJSON());
		localProjectShareAuthorization.xSave({
							syncFromServer : true
						});
	}
}
// function setWaitForAccept() {
	// if ($.$model.xGet("state") === "Wait") {
		// $.checkAccept.setVisible(true);
	// }
// }
// $.onWindowOpenDo(function() {
	// setWaitForAccept();
// });
setActualTotalMoneyColor();
function setActualTotalMoneyColor(){
	if($.$model.getActualTotalText() === "已经支出"){
		$.actualTotalMoney.label.setColor("#c80032");
	}else{
		$.actualTotalMoney.label.setColor("#329600");
	}
	if($.$model.getSettlementText() === "应该支出"){
		$.apportionedTotalMoney.label.setColor("#c80032");
	}else{
		$.apportionedTotalMoney.label.setColor("#329600");
	}
}

$.picture.UIInit($, $.getCurrentWindow());
$.sharePercentage.UIInit($, $.getCurrentWindow());
$.friendDisplayName.UIInit($, $.getCurrentWindow());
$.actualTotalText.UIInit($, $.getCurrentWindow());
$.actualTotalMoney.UIInit($, $.getCurrentWindow());
$.apportionedTotalText.UIInit($, $.getCurrentWindow());
$.apportionedTotalMoney.UIInit($, $.getCurrentWindow());

<|endoftext|>


<commit_before>//Global variables
var team_list = ""
var individual_key

function dataTableWriter(data_table, d){
    data_table.fnAddData([
        d.key,
        d.formatted_donation_date,
        d.name,
        d.amount_donated,
        d.payment_type,
        d.team_name
    ])

    data_table.fnAdjustColumnSizing()
}

function getTeamTotals(){
	var params = {'individual_key':individual_key}
	var request = ghiapi.get.team_totals(params)

	request.execute(function(response){

		$.each(response.team_totals, function(index, tt){
			html = '
%t - %d
'
			html = html.replace("%t", tt.team_name)
			html = html.replace("%d", tt.donation_total)

			$("#team_totals_div").append(html)
		})

	})
}

function refreshCurrentTeams(){
	$("#current_teams").html("")

	$.each(team_list, function(team_key, values){
	    var new_div = '

'
	    var insert_name = 'name
 Fundraise amount:'
	    var fundraise = '<input type="text" class="small" style="margin-left:15px" value="amount" />'
	    var input = '<input type="button" class="button small" style="margin-left:15px" value="Remove" />'

		$("#current_teams").append(new_div.replace("key", team_key))
		$("#current_teams div[data-id=" + team_key + "]").append(insert_name.replace("name", values[0]))
		$("#current_teams div[data-id=" + team_key + "]").append(fundraise.replace("amount", parseFloat(values[1]).toFixed(2)))
		$("#current_teams div[data-id=" + team_key + "]").append(input)
	})
}

$(document).ready(function(){
	individual_key = $("#individual_key").val()
	var donate_parent = $("input[name=donate_parent]").val()

    var rpc_params = {'individual_key':individual_key}
    var rpc_request = ghiapi.semi.get.individual_donations

    var data_table = initializeTable(5, rpc_request, rpc_params, function(data_table, d){
        dataTableWriter(data_table, d)
    })

	//Team list dictionary parsed from JSON
	team_list = JSON.parse(htmlDecode($("input[name=team_list]").val()))
	var team_names = ""

	if ($("#var_show_donation_page").val() == "True"){
		$("input[name=show_donation_page]").attr("checked", "checked")
	}

	if ($("#var_show_progress_bar").val() == "True"){
		$("input[name=show_progress_bar]").attr("checked", "checked")
	}

	//Formatting team fields
	$.each(team_list, function(team_key, values){
		team_names += values[0] + ", "

        var support_url = 'team_name

'
        support_url = support_url.replace("donate_parent", donate_parent)
        support_url = support_url.replace("team_key", team_key)
        support_url = support_url.replace("individual_key", individual_key)
        support_url = support_url.replace("team_name", values[0])

        $("#support_urls").append(support_url)
	})

	//Populate current teams
	refreshCurrentTeams()

	getTeamTotals()

	$("form").validationEngine()

	$("#team_display input").val(team_names.substr(0, team_names.length-2))

	$("#edit_profile").click(function(){
		//Change the page to edit mode
		$("#edit_profile").hide()
		$("#team_display").hide()
		$(".hidden").fadeIn()

		$(".unlockable").removeAttr("disabled")
	})

    //Set the team selector to current team
    $("#team_selector select").val($("#current_team").val())

    $("#all_teams").delegate("#add_team", "click", function(){
    	var team_key = $("#all_teams select").val()
    	var team_name = $("#all_teams option[value=" + team_key + "]").text()

    	//Add team to dictionary
		team_list[team_key] = [team_name, 2800]

		refreshCurrentTeams()
	})

    $(".current_team input[type=button]").live("click", function(){
        var team_key = $(this).parent().attr("data-id")

        //Remove team from dictionary
        delete team_list[team_key]

        refreshCurrentTeams()
    })

    $("form input[name=delete_individual]").click(function(){
    	var r=confirm("Do you want to delete this person?")
		if (r==true){
	    	var params = {'individual_key':individual_key}
	    	var request = ghiapi.individual.delete(params)

		    request.execute(function(response){
		    	rpcSuccessMessage(response, function(){
                    var home_page = $("#home_page").val()
		            if (home_page == "dashboard"){
		            	window.location.hash = "allteams"
		            }
		            else{
		            	window.location = "/login"
		            }
                })

		    })
		}
		else{
			return
		}
    })

	$("form input[type=submit]").click(function(){
		$("#current_teams input[type=text]").each(function(){
			var team_key = $(this).parent().attr("data-id")

			var number = $(this).val().replace(/[^\d.]/g, "")
			var amount = parseFloat(number)

			if (amount == 0){
				amount = 0.01
			}

			team_list[team_key][1] = amount
		})

		json_list = $.toJSON(team_list)
		$("form input[name=team_list]").val(json_list)

		var validation_result = $("form").validationEngine('validate')
		if (validation_result == true){
			$("form").submit()
		}
	})

    $("#donations").delegate("tr", "click", function(){
        var row_data = data_table.fnGetData(this)
        var clicked_id =  row_data[0]

        var url = "/ajax/reviewdetails?id=" + clicked_id
        loadColorbox(url, "donation_container")
    });

})<commit_msg>Change default raising goal to 2900<commit_after>//Global variables
var team_list = ""
var individual_key

function dataTableWriter(data_table, d){
    data_table.fnAddData([
        d.key,
        d.formatted_donation_date,
        d.name,
        d.amount_donated,
        d.payment_type,
        d.team_name
    ])

    data_table.fnAdjustColumnSizing()
}

function getTeamTotals(){
	var params = {'individual_key':individual_key}
	var request = ghiapi.get.team_totals(params)

	request.execute(function(response){

		$.each(response.team_totals, function(index, tt){
			html = '
%t - %d
'
			html = html.replace("%t", tt.team_name)
			html = html.replace("%d", tt.donation_total)

			$("#team_totals_div").append(html)
		})

	})
}

function refreshCurrentTeams(){
	$("#current_teams").html("")

	$.each(team_list, function(team_key, values){
	    var new_div = '

'
	    var insert_name = 'name
 Fundraise amount:'
	    var fundraise = '<input type="text" class="small" style="margin-left:15px" value="amount" />'
	    var input = '<input type="button" class="button small" style="margin-left:15px" value="Remove" />'

		$("#current_teams").append(new_div.replace("key", team_key))
		$("#current_teams div[data-id=" + team_key + "]").append(insert_name.replace("name", values[0]))
		$("#current_teams div[data-id=" + team_key + "]").append(fundraise.replace("amount", parseFloat(values[1]).toFixed(2)))
		$("#current_teams div[data-id=" + team_key + "]").append(input)
	})
}

$(document).ready(function(){
	individual_key = $("#individual_key").val()
	var donate_parent = $("input[name=donate_parent]").val()

    var rpc_params = {'individual_key':individual_key}
    var rpc_request = ghiapi.semi.get.individual_donations

    var data_table = initializeTable(5, rpc_request, rpc_params, function(data_table, d){
        dataTableWriter(data_table, d)
    })

	//Team list dictionary parsed from JSON
	team_list = JSON.parse(htmlDecode($("input[name=team_list]").val()))
	var team_names = ""

	if ($("#var_show_donation_page").val() == "True"){
		$("input[name=show_donation_page]").attr("checked", "checked")
	}

	if ($("#var_show_progress_bar").val() == "True"){
		$("input[name=show_progress_bar]").attr("checked", "checked")
	}

	//Formatting team fields
	$.each(team_list, function(team_key, values){
		team_names += values[0] + ", "

        var support_url = 'team_name

'
        support_url = support_url.replace("donate_parent", donate_parent)
        support_url = support_url.replace("team_key", team_key)
        support_url = support_url.replace("individual_key", individual_key)
        support_url = support_url.replace("team_name", values[0])

        $("#support_urls").append(support_url)
	})

	//Populate current teams
	refreshCurrentTeams()

	getTeamTotals()

	$("form").validationEngine()

	$("#team_display input").val(team_names.substr(0, team_names.length-2))

	$("#edit_profile").click(function(){
		//Change the page to edit mode
		$("#edit_profile").hide()
		$("#team_display").hide()
		$(".hidden").fadeIn()

		$(".unlockable").removeAttr("disabled")
	})

    //Set the team selector to current team
    $("#team_selector select").val($("#current_team").val())

    $("#all_teams").delegate("#add_team", "click", function(){
    	var team_key = $("#all_teams select").val()
    	var team_name = $("#all_teams option[value=" + team_key + "]").text()

    	//Add team to dictionary
		team_list[team_key] = [team_name, 2900]

		refreshCurrentTeams()
	})

    $(".current_team input[type=button]").live("click", function(){
        var team_key = $(this).parent().attr("data-id")

        //Remove team from dictionary
        delete team_list[team_key]

        refreshCurrentTeams()
    })

    $("form input[name=delete_individual]").click(function(){
    	var r=confirm("Do you want to delete this person?")
		if (r==true){
	    	var params = {'individual_key':individual_key}
	    	var request = ghiapi.individual.delete(params)

		    request.execute(function(response){
		    	rpcSuccessMessage(response, function(){
                    var home_page = $("#home_page").val()
		            if (home_page == "dashboard"){
		            	window.location.hash = "allteams"
		            }
		            else{
		            	window.location = "/login"
		            }
                })

		    })
		}
		else{
			return
		}
    })

	$("form input[type=submit]").click(function(){
		$("#current_teams input[type=text]").each(function(){
			var team_key = $(this).parent().attr("data-id")

			var number = $(this).val().replace(/[^\d.]/g, "")
			var amount = parseFloat(number)

			if (amount == 0){
				amount = 0.01
			}

			team_list[team_key][1] = amount
		})

		json_list = $.toJSON(team_list)
		$("form input[name=team_list]").val(json_list)

		var validation_result = $("form").validationEngine('validate')
		if (validation_result == true){
			$("form").submit()
		}
	})

    $("#donations").delegate("tr", "click", function(){
        var row_data = data_table.fnGetData(this)
        var clicked_id =  row_data[0]

        var url = "/ajax/reviewdetails?id=" + clicked_id
        loadColorbox(url, "donation_container")
    });

})<|endoftext|>


<commit_before>var Promise = require("bluebird");
var Vimeo   = require("../integrations/vimeo/request-vimeo");
var filter  = require("../integrations/vimeo/filter-vimeo");
<<<<<<< HEAD
=======
// var mongoose = require('mongoose');
>>>>>>> Created a MongoDB Database to store the request from the Vimeo API
var RequestApi = require('../models/model.js');

exports.makeRequest = function(category, callback){

	// Create the query to fetch the Vimeo API
	var queryObj = {
		path : '/categories/' + category + '/videos',
		query : { page : 1, per_page : 20 }
	}

	// Request the Vimeo API
	Vimeo.request(queryObj, function (error, body, status_code, headers) {
	        if (error) {
	            console.log('error', error);
	        } else {
	            callback(false, body);
	        }
	        // console.log('status code', status_code);
	        // console.log('headers', headers);
    });
}

exports.multipleRequests = function(categories, resultJSON, res){

  // Promisify the request function ========================= //
  var makeRequestAsync = Promise.promisify(exports.makeRequest);

  // Multiple Promisify requests ============================ //

  Promise.map(categories, function(gallery) {
      return makeRequestAsync(gallery)
              .then(function(data){
                var dataFiltered = filter(data);
                // increase the number of galleries (categories)
                resultJSON.total++;
                // set the new gallery into the header
                resultJSON.header.push({'name': gallery});
                // set the content for this gallery (category)
                resultJSON.content[gallery] = dataFiltered;
                // return the data (this data is not been used)
                return dataFiltered;
              })
              .catch(function(e){ console.log('error:', e); });
  }).then(function(dataArray) {
      // res.status(200).json({results: resultJSON});
      var dataString = JSON.stringify(resultJSON);

      // Create the new request model
      var newRequestApi = new RequestApi({
        data: dataString,
        api: 'Vimeo'
      });

      // Fetch the Database to check if there's any request stored
      RequestApi.findOne({}, function(err, result){
        if (err) {
          console.log('Failed to fecth the database');
        } else {

          // If the request doesn't exist
          if (result === null) {
            // Create the new request model
            var newRequestApi = new RequestApi({
              data: dataString,
              api: 'Vimeo'
            });

            // Save the new model into the DB
            newRequestApi.save(function(err, result){
              if (err) {
                console.log('Failed to SAVE the request in the Database');
              } else {
                console.log('Request successfuly SAVED in the Database ');
              }
            });
          }

          // If the request exists, just update with the new data
          else {
            // Update the data
            result.data = dataString;
            // Save it
            result.save(function(err, result){
              if (err) {
                console.log('Failed to UPDATE the request in the Database');
              } else {
                console.log('Request successfuly UPDATED in the Database ');
              }
            })
          }

        }
      })

  }).catch(SyntaxError, function(e) {
     console.log("Invalid JSON in file " + e.fileName + ": " + e.message);
  });

  // ========================================================== //

}

exports.createJSON = function(req, res, categories, target){

  // The JSON Object to send to the client
  var resultJSON = {
    total: 0,
    settings: {
      contentWidth: 295,
      contentHeight: 166
    },
    header: [],
    content: {}
  };

  // Invoke all the requests
  exports.multipleRequests(categories, resultJSON, res);

};

exports.updateRequest = function(){
  // setInterval(fun);
}<commit_msg>Implemeted concurrency to Promise.map function to limit the number of request that the server is able to fire at the same time<commit_after>var Promise = require("bluebird");
var Vimeo   = require("../integrations/vimeo/request-vimeo");
var filter  = require("../integrations/vimeo/filter-vimeo");
var RequestApi = require('../models/model.js');

exports.makeRequest = function(category, callback){

	// Create the query to fetch the Vimeo API
	var queryObj = {
		path : '/categories/' + category + '/videos',
		query : { page : 1, per_page : 20 }
	}

	// Request the Vimeo API
	Vimeo.request(queryObj, function (error, body, status_code, headers) {
	        if (error) {
	            console.log('error', error);
	        } else {
	            callback(false, body);
	        }
	        console.log('status code', status_code);
          console.log('headers', headers);
	        console.log('category', category);
    });
}

exports.multipleRequests = function(categories, resultJSON, res){

  // Promisify the request function ========================= //
  var makeRequestAsync = Promise.promisify(exports.makeRequest);

  // Multiple Promisify requests ============================ //

  Promise.map(categories, function(gallery) {
      return makeRequestAsync(gallery)
              .then(function(data){
                var dataFiltered = filter(data);
                // increase the number of galleries (categories)
                resultJSON.total++;
                // set the new gallery into the header
                resultJSON.header.push({'name': gallery});
                // set the content for this gallery (category)
                resultJSON.content[gallery] = dataFiltered;
                // return the data (this data is not been used)
                return dataFiltered;
              })
              .catch(function(e){ console.log('error:', e); });
  }, {concurrency: 1}).then(function(dataArray) {
      // res.status(200).json({results: resultJSON});
      var dataString = JSON.stringify(resultJSON);

      // Create the new request model
      var newRequestApi = new RequestApi({
        data: dataString,
        api: 'Vimeo'
      });

      // Fetch the Database to check if there's any request stored
      RequestApi.findOne({}, function(err, result){
        if (err) {
          console.log('Failed to fecth the database');
        } else {

          // If the request doesn't exist
          if (result === null) {
            // Create the new request model
            var newRequestApi = new RequestApi({
              data: dataString,
              api: 'Vimeo'
            });

            // Save the new model into the DB
            newRequestApi.save(function(err, result){
              if (err) {
                console.log('Failed to SAVE the request in the Database');
              } else {
                console.log('Request successfuly SAVED in the Database ');
              }
            });
          }

          // If the request exists, just update with the new data
          else {
            // Update the data
            result.data = dataString;
            // Save it
            result.save(function(err, result){
              if (err) {
                console.log('Failed to UPDATE the request in the Database');
              } else {
                console.log('Request successfuly UPDATED in the Database ');
              }
            })
          }

        }
      })

  }).catch(SyntaxError, function(e) {
     console.log("Invalid JSON in file " + e.fileName + ": " + e.message);
  });

  // ========================================================== //

}

exports.createJSON = function(req, res, categories, target){

  // The JSON Object to send to the client
  var resultJSON = {
    total: 0,
    settings: {
      contentWidth: 295,
      contentHeight: 166
    },
    header: [],
    content: {}
  };

  // Invoke all the requests
  exports.multipleRequests(categories, resultJSON, res);

};

exports.updateRequest = function(){
  // setInterval(fun);
}<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getAllData = function() {
         $.getJSON('/api/project/getAllData/' + gvm.projectId, function(data) {
            console.log(data);
         });
    }

    gvm.updateIndicator = function(id,subcompetenceId,competenceId,name,description) {
        gvm.indicators.push(new Indicator(this,id,subcompetenceId,competenceId,name,description));
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getAllData();
    fetchProjectStructure();
}

function fetchProjectStructure() {

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            $.each(item.subcompetences, function(i, subcomp){
                $.each(subcomp.indicators, function(i, indic){
                    var indicator = new Indicator(indic.id, subcomp.id, item.id, indic.name, indic.description);
                    viewModel.updateIndicator(this,indic.id,subcomp.id,item.id,indic.name,indic.description);
                });
            });
        })
    });

    console.log(viewModel.indicators());
}

/* Indicators */
function Indicator(viewmodel, id, subcompetenceId, competenceId, name, description) {
    return {
        id: ko.observable(id),
        subcompetenceId: ko.observable(subcompetenceId),
        competenceId: ko.observable(competenceId),
        name: ko.observable(name),
        description : ko.observable(description)
       }
}<commit_msg>assess score<commit_after>var data = null;

function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.indicators = ko.observableArray([]);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getAllData = function() {
         $.getJSON('/api/project/getAllData/' + gvm.projectId, function(data) {
            console.log(data);
             this.data=data;
         });
    }

    gvm.updateIndicator = function(id,subcompetenceId,competenceId,name,description) {
        gvm.indicators.push(new Indicator(this,id,subcompetenceId,competenceId,name,description));
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getAllData();
    displayProject();
}

function displayProject()
{
    console.log(data);
}

<|endoftext|>


<commit_before>/*
 * flatiron-cli-config.js: Top-level include for the `flatiron-cli-config` module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var utile = require('flatiron').common;

var cliConfig = exports;

//
// Expose commands and name this plugin
//
cliConfig.commands = require('./commands');
cliConfig.name = 'cli-config';

//
// ### function attach (options)
// #### @options {Object} Options to use when attaching
// Attaches the `flatiron-cli-config` behavior to the application.
//
cliConfig.attach = function (options) {
  var app = this;
  options = options || {};

  if (!app.plugins.cli) {
    throw new Error('`cli` plugin is required to use `flatiron-cli-config`');
  }
  else if (!app.config) {
    throw new Error('`app.config` must be set to use `flatiron-cli-config`');
  }

  app.config.remove('literal');
  cliConfig.app = app;
  cliConfig.store = options.store || null;
  cliConfig.restricted = options.restricted || [];
  cliConfig.before = options.before || {};
  cliConfig.setUsage();

  app.commands['config'] = app.commands['config'] || {};
  app.commands['config'] = utile.mixin(app.commands['config'], cliConfig.commands);
  app.alias('conf', { resource: 'config', command: 'list' });
};

//
// ### function detach ()
// Detaches this plugin from the application.
//
cliConfig.detach = function () {
  var app = this;

  Object.keys(app.commands['config']).forEach(function (method) {
    if (cliConfig.commands[method]) {
      delete app.commands['config'][method];
    }

    cliConfig.commands.app = null;
  });
};

//
// ### function setUsage ()
// Updates the command usage for the `<app>` this instance
// is attached to.
//
cliConfig.setUsage = function () {
  if (!cliConfig.app.name) {
    return;
  }

  function templateUsage(usage) {
    return usage.map(function (line) {
      return line.replace(/\<app\>/ig, cliConfig.app.name);
    });
  }

  Object.keys(cliConfig.commands).forEach(function (command) {
    if (command === 'usage') {
      cliConfig.commands.usage = templateUsage(cliConfig.commands.usage)
    }
    else if (cliConfig.commands[command].usage) {
      cliConfig.commands[command].usage = templateUsage(cliConfig.commands[command].usage)
    }
  });
};<commit_msg>[minor refactor] Update to use `flatiron.common.templateUsage` now that it has been hoisted into `flatiron/flatiron`<commit_after>/*
 * flatiron-cli-config.js: Top-level include for the `flatiron-cli-config` module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var common = require('flatiron').common;

var cliConfig = exports;

//
// Expose commands and name this plugin
//
cliConfig.commands = require('./commands');
cliConfig.name = 'cli-config';

//
// ### function attach (options)
// #### @options {Object} Options to use when attaching
// Attaches the `flatiron-cli-config` behavior to the application.
//
cliConfig.attach = function (options) {
  var app = this;
  options = options || {};

  if (!app.plugins.cli) {
    throw new Error('`cli` plugin is required to use `flatiron-cli-config`');
  }
  else if (!app.config) {
    throw new Error('`app.config` must be set to use `flatiron-cli-config`');
  }

  app.config.remove('literal');
  cliConfig.app = app;
  cliConfig.store = options.store || null;
  cliConfig.restricted = options.restricted || [];
  cliConfig.before = options.before || {};
  common.templateUsage(app, cliConfig.commands);

  app.commands['config'] = app.commands['config'] || {};
  app.commands['config'] = common.mixin(app.commands['config'], cliConfig.commands);
  app.alias('conf', { resource: 'config', command: 'list' });
};

//
// ### function detach ()
// Detaches this plugin from the application.
//
cliConfig.detach = function () {
  var app = this;

  Object.keys(app.commands['config']).forEach(function (method) {
    if (cliConfig.commands[method]) {
      delete app.commands['config'][method];
    }

    cliConfig.commands.app = null;
  });
};<|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado Boulder

/**
 * String plugin, loads a string using a syntax like:
 * var title = require( 'string!JOHN_TRAVOLTAGE/johnTravoltage.name' );
 *
 * This file conforms to the RequireJS plugin API which is described here: http://requirejs.org/docs/plugins.html#api
 *
 * The reasons we need our own string plugin:
 * So we can only include the (possibly) strings that are needed for a sim
 * So we can enumerate all of the used strings, for purposed of a translation utility
 * For uniformity with image and audio plugin
 *
 * The plugin code itself is excluded from the build by declaring it as a stubModule
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var _ = require( '../../sherpa/lib/lodash-2.4.1.min' ); // 3rd party dependencies, path relative to config.js
  var localeInfo = require( '../../chipper/js/data/localeInfo' ); // for running in browsers
  var text = require( 'text' );

  // constants
  var FALLBACK_LOCALE = 'en';

  var parse = JSON.parse;

  // Cache the loaded strings so they only have to be read once through file.read (for performance)
  var cache = {};

  // If doubleStrings is specified, concatenate each string with itself as a primitive i18n test
  var stringTest = ( typeof window !== 'undefined' && window.phet.chipper.getQueryParameter( 'stringTest' ) ) ?
                   window.phet.chipper.getQueryParameter( 'stringTest' ) :
                   null;

  /**
   * When running in requirejs mode, check to see if we have already loaded the specified file
   * Also parses it so that only happens once per file (instead of once per string key)
   * @param {string} url path for the string
   * @param {function} callback callback when the check succeeds
   * @param {function} errback callback for when an error occurred
   * @param {???} headers
   */
  function getWithCache( url, callback, errback, headers ) {

    // Check for cache hit
    if ( cache[ url ] ) {
      callback( cache[ url ] );
    }
    else {
      // Cache miss: load the file parse, enter into cache and return it
      text.get( url, function( loadedText ) {
        cache[ url ] = parse( loadedText );
        callback( cache[ url ] );
      }, errback, headers );
    }
  }

  return {

    /**
     * load is a function, and it will be called with the following arguments
     * Documentation taken from http://requirejs.org/docs/plugins.html#apiload
     * @param {string} name - The name of the resource to load. This is the part after the ! separator in the name. So,
     *        if a module asks for 'foo!something/for/foo', the foo module's load function will receive
     *        'something/for/foo' as the name.
     * @param {function} parentRequire - A local "require" function to use to load other modules. This require function
     *        has some utilities on it:
     *          parentRequire.toUrl(moduleResource): where moduleResource is a module name plus an extension. For
     *            instance "view/templates/main.html". It will return a full path to the resource, obeying any RequireJS
     *            configuration.
     *          parentRequire.defined(moduleName): Returns true if the module has already been loaded and defined.
     *            Used to be called require.isDefined before RequireJS 0.25.0.
     *          parentRequire.specified(moduleName): Returns true if the module has already been requested or is in the
     *            process of loading and should be available at some point.
     * @param {function} onload - A function to call with the value for name. This tells the loader that the plugin is
     *        done loading the resource. onload.error() can be called, passing an error object to it, if the plugin
     *        detects an error condition that means the resource will fail to load correctly.
     * @param {Object} config - A configuration object. This is a way for the optimizer and the web app to pass
     *        configuration information to the plugin. The i18n! plugin uses this to get the current current locale, if
     *        the web app wants to force a specific locale. The optimizer will set an isBuild property in the config to
     *        true if this plugin (or pluginBuilder) is being called as part of an optimizer build.
     */
    load: function( name, parentRequire, onload, config ) {

      // Extract the key. Eg for 'JOHN_TRAVOLTAGE/johnTravoltage.name', the key is 'johnTravoltage.name'.
      var key = name.substring( name.lastIndexOf( '/' ) + 1 );

      // Apply the cache buster args (but only during requirejs mode)
      var suffix = config.isBuild ? '' : '?' + config.urlArgs;

      var requirePrefix = name.substring( 0, name.indexOf( '/' ) ); // e.g. 'SOME_SIM'
      var requirePath, repositoryPath, repositoryName, locale;

      function getFilenameForLocale( locale ) {
        return repositoryName + '-strings_' + locale + '.json' + suffix;
      }

      // This code block handles the in-browser requirejs version (not the compilation step)
      if ( !config.isBuild ) {
        requirePath = parentRequire.toUrl( requirePrefix );
        if ( requirePath.indexOf( '?' ) >= 0 ) {
          requirePath = requirePath.substring( 0, requirePath.indexOf( '?' ) );
        }
        repositoryPath = requirePath + '/..';
        repositoryName = requirePrefix.toLowerCase().split( '_' ).join( '-' );

        // strings may be specified via the 'strings' query parameter, value is expected to be encoded to avoid URI-reserved characters
        var queryParameterStrings = parse( decodeURIComponent( phet.chipper.getQueryParameter( 'strings' ) || '{}' ) );

        // Read the locale from a query parameter, if it is there, or use english
        locale = phet.chipper.getQueryParameter( 'locale' ) || config.phetLocale || 'en';
        if ( !localeInfo[ locale ] ) {
          onload.error( new Error( 'unsupported locale: ' + locale ) );
        }
        var isRTL = localeInfo[ locale ].direction === 'rtl';

        var fallbackSpecficPath = repositoryPath + '/' + getFilenameForLocale( FALLBACK_LOCALE );
        var localeSpecificPath = ( locale === FALLBACK_LOCALE ) ?
                                 fallbackSpecficPath :
                                 repositoryPath + '/../babel/' + repositoryName + '/' + getFilenameForLocale( locale );

        // In the browser, a string specified via the 'strings' query parameter overrides anything,
        // to match the behavior of the chipper version (for dynamically substituting new strings like in the translation utility)
        var queryParameterStringValue = queryParameterStrings[ name ];
        if ( queryParameterStringValue ) {
          onload( queryParameterStringValue );
        }
        else {

          // Load & parse just once per file, getting the fallback strings first.
          getWithCache( fallbackSpecficPath, function( parsedFallbackStrings ) {
              assert && assert( parsedFallbackStrings[ key ] !== undefined,
                'Missing string: ' + key + ' in ' + fallbackSpecficPath );
              var fallback = parsedFallbackStrings[ key ].value;

              // Now get the primary strings.
              getWithCache( localeSpecificPath, function( parsed ) {
                  // Pad LTR/RTL language values with unicode embedding marks (see https://github.com/phetsims/joist/issues/152)
                  // Uses directional formatting characters: http://unicode.org/reports/tr9/#Directional_Formatting_Characters
                  for ( var stringKey in parsed ) {
                    parsed[ stringKey ].value = ( isRTL ? '\u202b' : '\u202a' ) + parsed[ stringKey ].value + '\u202c';
                  }

                  // Combine the primary and fallback strings into one object hash.
                  var parsedStrings = _.extend( parsedFallbackStrings, parsed );
                  if ( parsedStrings[ key ] !== undefined && parsedStrings[ key ].value.length > 0 ) {
                    onload( window.phet.chipper.mapString( parsedStrings[ key ].value, stringTest ) );
                  }
                  else {
                    throw new Error( 'no entry for string key: ' + key );
                  }
                },
                // Error callback in the text! plugin.  Couldn't load the strings for the specified language, so use a fallback
                function() {

                  if ( !parsedFallbackStrings[ key ] ) {
                    // It would be really strange for there to be no fallback for a certain string, that means it exists in the translation but not the original English
                    throw new Error( 'no fallback for string key:' + key );
                  }
                  // Running in the browser (dynamic requirejs mode) and couldn't find the string file.  Use the fallbacks.
                  console.log( "no string file for " + localeSpecificPath );
                  onload( fallback );
                },
                { accept: 'application/json' }
              );
            },
            onload.error,
            { accept: 'application/json' }
          );
        }
      }
      else {
        // This code block handles the compilation step (not the in-browser requirejs mode).

        // extract information about the repository name, prefix, and path that will be recorded for later in the build
        requirePrefix = name.substring( 0, name.indexOf( '/' ) ); // e.g. 'SOME_SIM'
        requirePath = parentRequire.toUrl( requirePrefix ); // e.g. '/Users/something/phet/git/some-sim/js'
        if ( requirePath.substring( requirePath.lastIndexOf( '/' ) ) !== '/js' ) {
          throw new Error( 'requirejs namespace REPO must resolve to repo/js' );
        }
        repositoryPath = requirePath.substring( 0, requirePath.lastIndexOf( '/' ) ); // e.g. '/Users/something/phet/git/some-sim'
        repositoryName = repositoryPath.substring( repositoryPath.lastIndexOf( '/' ) + 1 ); // e.g. 'some-sim'

        // lazily construct our strings list
        global.phet.strings = global.phet.strings || {};

        // entry saved for later in the build
        global.phet.strings[ name ] = {
          name: name, // 'SOME_SIM/string.name'
          requirePrefix: requirePrefix, // 'SOME_SIM'
          requirePath: requirePath, // '/Users/something/phet/git/some-sim/js'
          repositoryPath: repositoryPath, // '/Users/something/phet/git/some-sim'
          repositoryName: repositoryName // 'some-sim'
        };

        // tell require.js we're done processing
        onload( null );
      }
    },

    /**
     * Write code that will look up the string in the compiled sim, used in the compilation step.  write is only used
     * by the optimizer, and it only needs to be implemented if the plugin can output something that would belong in an
     * optimized layer.
     *
     * Documentation taken from http://requirejs.org/docs/plugins.html#apiwrite
     *
     * It is called with the following arguments:
     * @param {string} pluginName - The normalized name for the plugin. Most plugins will not be authored with a name
     *          (they will be anonymous plugins) so it is useful to know the normalized name for the plugin module for use
     *          in the optimized file.
     * @param {string} moduleName - The normalized resource name.
     * @param {function} write - A function to be called with a string of output to write to the optimized file. This
     *          function also contains a property function, write.asModule(moduleName, text). asModule can be used to
     *          write out a module that may have an anonymous define call in there that needs name insertion or/and
     *          contains implicit require("") dependencies that need to be pulled out for the optimized file. asModule
     *          is useful for text transform plugins, like a CoffeeScript plugin.
     */
    write: function( pluginName, moduleName, write ) {
      write( 'define("' + pluginName + '!' + moduleName + '",function(){return window.phet.chipper.strings.get(\"' + moduleName + '\");});\n' );
    }
  };
} );
<commit_msg>report if-else so that build is handled in if, requirejs in else (like other plugins), closes #257<commit_after>// Copyright 2002-2013, University of Colorado Boulder

/**
 * String plugin, loads a string using a syntax like:
 * var title = require( 'string!JOHN_TRAVOLTAGE/johnTravoltage.name' );
 *
 * This file conforms to the RequireJS plugin API which is described here: http://requirejs.org/docs/plugins.html#api
 *
 * The reasons we need our own string plugin:
 * So we can only include the (possibly) strings that are needed for a sim
 * So we can enumerate all of the used strings, for purposed of a translation utility
 * For uniformity with image and audio plugin
 *
 * The plugin code itself is excluded from the build by declaring it as a stubModule
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var _ = require( '../../sherpa/lib/lodash-2.4.1.min' ); // 3rd party dependencies, path relative to config.js
  var localeInfo = require( '../../chipper/js/data/localeInfo' ); // for running in browsers
  var text = require( 'text' );

  // constants
  var FALLBACK_LOCALE = 'en';

  var parse = JSON.parse;

  // Cache the loaded strings so they only have to be read once through file.read (for performance)
  var cache = {};

  // If doubleStrings is specified, concatenate each string with itself as a primitive i18n test
  var stringTest = ( typeof window !== 'undefined' && window.phet.chipper.getQueryParameter( 'stringTest' ) ) ?
                   window.phet.chipper.getQueryParameter( 'stringTest' ) :
                   null;

  /**
   * When running in requirejs mode, check to see if we have already loaded the specified file
   * Also parses it so that only happens once per file (instead of once per string key)
   * @param {string} url path for the string
   * @param {function} callback callback when the check succeeds
   * @param {function} errback callback for when an error occurred
   * @param {???} headers
   */
  function getWithCache( url, callback, errback, headers ) {

    // Check for cache hit
    if ( cache[ url ] ) {
      callback( cache[ url ] );
    }
    else {
      // Cache miss: load the file parse, enter into cache and return it
      text.get( url, function( loadedText ) {
        cache[ url ] = parse( loadedText );
        callback( cache[ url ] );
      }, errback, headers );
    }
  }

  return {

    /**
     * load is a function, and it will be called with the following arguments
     * Documentation taken from http://requirejs.org/docs/plugins.html#apiload
     * @param {string} name - The name of the resource to load. This is the part after the ! separator in the name. So,
     *        if a module asks for 'foo!something/for/foo', the foo module's load function will receive
     *        'something/for/foo' as the name.
     * @param {function} parentRequire - A local "require" function to use to load other modules. This require function
     *        has some utilities on it:
     *          parentRequire.toUrl(moduleResource): where moduleResource is a module name plus an extension. For
     *            instance "view/templates/main.html". It will return a full path to the resource, obeying any RequireJS
     *            configuration.
     *          parentRequire.defined(moduleName): Returns true if the module has already been loaded and defined.
     *            Used to be called require.isDefined before RequireJS 0.25.0.
     *          parentRequire.specified(moduleName): Returns true if the module has already been requested or is in the
     *            process of loading and should be available at some point.
     * @param {function} onload - A function to call with the value for name. This tells the loader that the plugin is
     *        done loading the resource. onload.error() can be called, passing an error object to it, if the plugin
     *        detects an error condition that means the resource will fail to load correctly.
     * @param {Object} config - A configuration object. This is a way for the optimizer and the web app to pass
     *        configuration information to the plugin. The i18n! plugin uses this to get the current current locale, if
     *        the web app wants to force a specific locale. The optimizer will set an isBuild property in the config to
     *        true if this plugin (or pluginBuilder) is being called as part of an optimizer build.
     */
    load: function( name, parentRequire, onload, config ) {

      // Extract the key. Eg for 'JOHN_TRAVOLTAGE/johnTravoltage.name', the key is 'johnTravoltage.name'.
      var key = name.substring( name.lastIndexOf( '/' ) + 1 );

      // Apply the cache buster args (but only during requirejs mode)
      var suffix = config.isBuild ? '' : '?' + config.urlArgs;

      var requirePrefix = name.substring( 0, name.indexOf( '/' ) ); // e.g. 'SOME_SIM'
      var requirePath, repositoryPath, repositoryName, locale;

      function getFilenameForLocale( locale ) {
        return repositoryName + '-strings_' + locale + '.json' + suffix;
      }

      // This code block handles the in-browser requirejs version (not the compilation step)
      if ( config.isBuild ) {

        // This code block handles the compilation step (not the in-browser requirejs mode).

        // extract information about the repository name, prefix, and path that will be recorded for later in the build
        requirePrefix = name.substring( 0, name.indexOf( '/' ) ); // e.g. 'SOME_SIM'
        requirePath = parentRequire.toUrl( requirePrefix ); // e.g. '/Users/something/phet/git/some-sim/js'
        if ( requirePath.substring( requirePath.lastIndexOf( '/' ) ) !== '/js' ) {
          throw new Error( 'requirejs namespace REPO must resolve to repo/js' );
        }
        repositoryPath = requirePath.substring( 0, requirePath.lastIndexOf( '/' ) ); // e.g. '/Users/something/phet/git/some-sim'
        repositoryName = repositoryPath.substring( repositoryPath.lastIndexOf( '/' ) + 1 ); // e.g. 'some-sim'

        // lazily construct our strings list
        global.phet.strings = global.phet.strings || {};

        // entry saved for later in the build
        global.phet.strings[ name ] = {
          name: name, // 'SOME_SIM/string.name'
          requirePrefix: requirePrefix, // 'SOME_SIM'
          requirePath: requirePath, // '/Users/something/phet/git/some-sim/js'
          repositoryPath: repositoryPath, // '/Users/something/phet/git/some-sim'
          repositoryName: repositoryName // 'some-sim'
        };

        // tell require.js we're done processing
        onload( null );
      }
      else {
        requirePath = parentRequire.toUrl( requirePrefix );
        if ( requirePath.indexOf( '?' ) >= 0 ) {
          requirePath = requirePath.substring( 0, requirePath.indexOf( '?' ) );
        }
        repositoryPath = requirePath + '/..';
        repositoryName = requirePrefix.toLowerCase().split( '_' ).join( '-' );

        // strings may be specified via the 'strings' query parameter, value is expected to be encoded to avoid URI-reserved characters
        var queryParameterStrings = parse( decodeURIComponent( phet.chipper.getQueryParameter( 'strings' ) || '{}' ) );

        // Read the locale from a query parameter, if it is there, or use english
        locale = phet.chipper.getQueryParameter( 'locale' ) || config.phetLocale || 'en';
        if ( !localeInfo[ locale ] ) {
          onload.error( new Error( 'unsupported locale: ' + locale ) );
        }
        var isRTL = localeInfo[ locale ].direction === 'rtl';

        var fallbackSpecficPath = repositoryPath + '/' + getFilenameForLocale( FALLBACK_LOCALE );
        var localeSpecificPath = ( locale === FALLBACK_LOCALE ) ?
                                 fallbackSpecficPath :
                                 repositoryPath + '/../babel/' + repositoryName + '/' + getFilenameForLocale( locale );

        // In the browser, a string specified via the 'strings' query parameter overrides anything,
        // to match the behavior of the chipper version (for dynamically substituting new strings like in the translation utility)
        var queryParameterStringValue = queryParameterStrings[ name ];
        if ( queryParameterStringValue ) {
          onload( queryParameterStringValue );
        }
        else {

          // Load & parse just once per file, getting the fallback strings first.
          getWithCache( fallbackSpecficPath, function( parsedFallbackStrings ) {
              assert && assert( parsedFallbackStrings[ key ] !== undefined,
                'Missing string: ' + key + ' in ' + fallbackSpecficPath );
              var fallback = parsedFallbackStrings[ key ].value;

              // Now get the primary strings.
              getWithCache( localeSpecificPath, function( parsed ) {
                  // Pad LTR/RTL language values with unicode embedding marks (see https://github.com/phetsims/joist/issues/152)
                  // Uses directional formatting characters: http://unicode.org/reports/tr9/#Directional_Formatting_Characters
                  for ( var stringKey in parsed ) {
                    parsed[ stringKey ].value = ( isRTL ? '\u202b' : '\u202a' ) + parsed[ stringKey ].value + '\u202c';
                  }

                  // Combine the primary and fallback strings into one object hash.
                  var parsedStrings = _.extend( parsedFallbackStrings, parsed );
                  if ( parsedStrings[ key ] !== undefined && parsedStrings[ key ].value.length > 0 ) {
                    onload( window.phet.chipper.mapString( parsedStrings[ key ].value, stringTest ) );
                  }
                  else {
                    throw new Error( 'no entry for string key: ' + key );
                  }
                },
                // Error callback in the text! plugin.  Couldn't load the strings for the specified language, so use a fallback
                function() {

                  if ( !parsedFallbackStrings[ key ] ) {
                    // It would be really strange for there to be no fallback for a certain string, that means it exists in the translation but not the original English
                    throw new Error( 'no fallback for string key:' + key );
                  }
                  // Running in the browser (dynamic requirejs mode) and couldn't find the string file.  Use the fallbacks.
                  console.log( "no string file for " + localeSpecificPath );
                  onload( fallback );
                },
                { accept: 'application/json' }
              );
            },
            onload.error,
            { accept: 'application/json' }
          );
        }
      }
    },

    /**
     * Write code that will look up the string in the compiled sim, used in the compilation step.  write is only used
     * by the optimizer, and it only needs to be implemented if the plugin can output something that would belong in an
     * optimized layer.
     *
     * Documentation taken from http://requirejs.org/docs/plugins.html#apiwrite
     *
     * It is called with the following arguments:
     * @param {string} pluginName - The normalized name for the plugin. Most plugins will not be authored with a name
     *          (they will be anonymous plugins) so it is useful to know the normalized name for the plugin module for use
     *          in the optimized file.
     * @param {string} moduleName - The normalized resource name.
     * @param {function} write - A function to be called with a string of output to write to the optimized file. This
     *          function also contains a property function, write.asModule(moduleName, text). asModule can be used to
     *          write out a module that may have an anonymous define call in there that needs name insertion or/and
     *          contains implicit require("") dependencies that need to be pulled out for the optimized file. asModule
     *          is useful for text transform plugins, like a CoffeeScript plugin.
     */
    write: function( pluginName, moduleName, write ) {
      write( 'define("' + pluginName + '!' + moduleName + '",function(){return window.phet.chipper.strings.get(\"' + moduleName + '\");});\n' );
    }
  };
} );
<|endoftext|>


<commit_before>(function(){

  /*
   * Temporary workaround for old bookmarklet users

                     .-"""-.
                   _/-=-.   \
                  (_|a a/   |_
                   / "  \   ,_)
              _    \`=' /__/
             / \_  .;--'  `-.
             \___)//      ,  \
              \ \/;        \  \
               \_.|         | |
                .-\ '     _/_/
              .'  _;.    (_  \
             /  .'   `\   \\_/
            |_ /       |  |\\
           /  _)       /  / ||
      jgs /  /       _/  /  //
          \_/       ( `-/  ||
                    /  /   \\ .-.
                    \_/     \'-'/
                             `"`

   */
  if (FactlinkConfig.lib.substr(-4, FactlinkConfig.lib.length) === "/lib") {
    FactlinkConfig.lib += "/dist";
  }
  if (FactlinkConfig.srcPath.substr(0, 5) === "/dist") {
    FactlinkConfig.srcPath = FactlinkConfig.srcPath.substr(5, FactlinkConfig.srcPath.length);
  }
  // end of old bookmarklet users patches.

  var iframe = document.createElement("iframe"),
      div = document.createElement("div"),
      hasReadyState = "readyState" in iframe,
      flScript = document.createElement('script'),
      scriptLoaded = false, iframeLoaded = false,
      iframeDoc;

  iframe.style.display = "block";
  iframe.style.border = "0px solid transparent";
  iframe.id = "factlink-iframe";

  flScript.src = FactlinkConfig.lib + (FactlinkConfig.srcPath || "/factlink.core.min.js");
  flScript.onload = flScript.onreadystatechange = function () {
    if ((flScript.readyState && flScript.readyState !== "complete" && flScript.readyState !== "loaded") || scriptLoaded) {
      return false;
    }
    flScript.onload = flScript.onreadystatechange = null;
    scriptLoaded = true;

    window.FACTLINK.on = function() {
      iframe.contentWindow.Factlink.on.apply(iframe.contentWindow.Factlink, arguments);
    };

    window.FACTLINK.off = function() {
      iframe.contentWindow.Factlink.off.apply(iframe.contentWindow.Factlink, arguments);
    };

    if ( window.jQuery ) {
      jQuery(window).trigger('factlink.libraryLoaded');
    }
  };

  if ( window.FACTLINK === undefined ) { window.FACTLINK = {}; }

  window.FACTLINK.iframeLoaded = function () {
    iframe.contentWindow.document.head.appendChild(flScript);
  };

  div.id = "fl";

  document.body.appendChild(div);
  div.insertBefore(iframe, div.firstChild);

  iframeDoc = iframe.contentWindow.document;

  iframeDoc.open();
  iframeDoc.write("<!DOCTYPE html>");
  iframeDoc.close();
}());
<commit_msg>Add proxy function add proxy hideDimmer as well<commit_after>(function(){

  /*
   * Temporary workaround for old bookmarklet users

                     .-"""-.
                   _/-=-.   \
                  (_|a a/   |_
                   / "  \   ,_)
              _    \`=' /__/
             / \_  .;--'  `-.
             \___)//      ,  \
              \ \/;        \  \
               \_.|         | |
                .-\ '     _/_/
              .'  _;.    (_  \
             /  .'   `\   \\_/
            |_ /       |  |\\
           /  _)       /  / ||
      jgs /  /       _/  /  //
          \_/       ( `-/  ||
                    /  /   \\ .-.
                    \_/     \'-'/
                             `"`

   */
  if (FactlinkConfig.lib.substr(-4, FactlinkConfig.lib.length) === "/lib") {
    FactlinkConfig.lib += "/dist";
  }
  if (FactlinkConfig.srcPath.substr(0, 5) === "/dist") {
    FactlinkConfig.srcPath = FactlinkConfig.srcPath.substr(5, FactlinkConfig.srcPath.length);
  }
  // end of old bookmarklet users patches.

  var iframe = document.createElement("iframe"),
      div = document.createElement("div"),
      hasReadyState = "readyState" in iframe,
      flScript = document.createElement('script'),
      scriptLoaded = false, iframeLoaded = false,
      iframeDoc;

  iframe.style.display = "block";
  iframe.style.border = "0px solid transparent";
  iframe.id = "factlink-iframe";

  flScript.src = FactlinkConfig.lib + (FactlinkConfig.srcPath || "/factlink.core.min.js");
  flScript.onload = flScript.onreadystatechange = function () {
    if ((flScript.readyState && flScript.readyState !== "complete" && flScript.readyState !== "loaded") || scriptLoaded) {
      return false;
    }
    flScript.onload = flScript.onreadystatechange = null;
    scriptLoaded = true;

    function proxy(func) {
      window.FACTLINK[func] = function () {
        iframe.contentWindow.Factlink[func].apply(iframe.contentWindow.Factlink, arguments);
      };
    }

    proxy('on');
    proxy('off');
    proxy('hideDimmer');

    if ( window.jQuery ) {
      jQuery(window).trigger('factlink.libraryLoaded');
    }
  };

  if ( window.FACTLINK === undefined ) { window.FACTLINK = {}; }

  window.FACTLINK.iframeLoaded = function () {
    iframe.contentWindow.document.head.appendChild(flScript);
  };

  div.id = "fl";

  document.body.appendChild(div);
  div.insertBefore(iframe, div.firstChild);

  iframeDoc = iframe.contentWindow.document;

  iframeDoc.open();
  iframeDoc.write("<!DOCTYPE html>");
  iframeDoc.close();
}());
<|endoftext|>


<commit_before>const {stream} = require('sepal/httpServer')

const sceneAreas$ = require('root/jobs/ee/image/sceneAreas')
const preview$ = require('root/jobs/ee/image/preview')
const loadCCDCSegments$ = require('root/jobs/ee/ccdc/loadSegments')
const loadTimeSeriesbservations$ = require('root/jobs/ee/timeSeries/loadObservations')
const nextReferenceDataPoints$ = require('root/jobs/ee/classification/nextReferenceDataPoints')
const assetVisualizations$ = require('root/jobs/ee/image/assetVisualizations')
const imageBands$ = require('root/jobs/ee/image/bands')
const imageHistogram$ = require('root/jobs/ee/image/histogram')
const distinctBandValues$ = require('root/jobs/ee/image/distinctBandValues')
const imageMetadata$ = require('root/jobs/ee/image/metadata')
const imageBounds$ = require('root/jobs/ee/image/bounds')
const imageGeometry$ = require('root/jobs/ee/image/geometry')
const sampleImage$ = require('root/jobs/ee/image/sample')
const aoiBounds$ = require('root/jobs/ee/aoi/bounds')
const tableColumns$ = require('root/jobs/ee/table/columns')
const tableColumnValues$ = require('root/jobs/ee/table/columnValues')
const tableRows$ = require('root/jobs/ee/table/rows')
const tableQuery$ = require('root/jobs/ee/table/query')
const tableMap$ = require('root/jobs/ee/table/map')
const check$ = require('root/jobs/ee/check')
const testHttp$ = require('root/jobs/test/http')
const testHttpDirect$ = require('root/jobs/test/http/test')
const testWs$ = require('root/jobs/test/ws')

module.exports = router =>
    router
        .post('/sceneareas', stream(ctx => sceneAreas$(ctx)))
        .post('/preview', stream(ctx => preview$(ctx)))
        .post('/bands', stream(ctx => imageBands$(ctx)))
        .post('/image/assetVisualizations', stream(ctx => assetVisualizations$(ctx)))
        .post('/image/histogram', stream(ctx => imageHistogram$(ctx)))
        .post('/image/distinctBandValues', stream(ctx => distinctBandValues$(ctx)))
        .get('/image/sample', stream(ctx => sampleImage$(ctx)))
        .post('/imageMetadata', stream(ctx => imageMetadata$(ctx)))
        .post('/recipe/geometry', stream(ctx => imageGeometry$(ctx)))
        .post('/recipe/bounds', stream(ctx => imageBounds$(ctx)))
        .post('/aoi/bounds', stream(ctx => aoiBounds$(ctx)))
        .post('/ccdc/loadSegments', stream(ctx => loadCCDCSegments$(ctx)))
        .post('/timeSeries/loadObservations', stream(ctx => loadTimeSeriesbservations$(ctx)))
        .post('/nextReferenceDataPoints', stream(ctx => nextReferenceDataPoints$(ctx)))
        .get('/table/rows', stream(ctx => tableRows$(ctx)))
        .get('/table/columns', stream(ctx => tableColumns$(ctx)))
        .get('/table/columnValues', stream(ctx => tableColumnValues$(ctx)))
        .post('/table/query', stream(ctx => tableQuery$(ctx)))
        .get('/table/map', stream(ctx => tableMap$(ctx)))
        .get('/test/worker/:min/:max/:errorProbability', stream(ctx => testHttp$(ctx)))
        .get('/test/direct/:min/:max/:errorProbability', stream(
            ({params: {min, max, errorProbability}}) => testHttpDirect$(parseInt(min), parseInt(max), parseInt(errorProbability))
        ))
        .get('/ws/:name', stream(ctx => testWs$(ctx)))
        .get('/healthcheck', stream(ctx => check$(ctx)))
<commit_msg>Added http test endpoint.<commit_after>const {stream} = require('sepal/httpServer')

const sceneAreas$ = require('root/jobs/ee/image/sceneAreas')
const preview$ = require('root/jobs/ee/image/preview')
const loadCCDCSegments$ = require('root/jobs/ee/ccdc/loadSegments')
const loadTimeSeriesbservations$ = require('root/jobs/ee/timeSeries/loadObservations')
const nextReferenceDataPoints$ = require('root/jobs/ee/classification/nextReferenceDataPoints')
const assetVisualizations$ = require('root/jobs/ee/image/assetVisualizations')
const imageBands$ = require('root/jobs/ee/image/bands')
const imageHistogram$ = require('root/jobs/ee/image/histogram')
const distinctBandValues$ = require('root/jobs/ee/image/distinctBandValues')
const imageMetadata$ = require('root/jobs/ee/image/metadata')
const imageBounds$ = require('root/jobs/ee/image/bounds')
const imageGeometry$ = require('root/jobs/ee/image/geometry')
const sampleImage$ = require('root/jobs/ee/image/sample')
const aoiBounds$ = require('root/jobs/ee/aoi/bounds')
const tableColumns$ = require('root/jobs/ee/table/columns')
const tableColumnValues$ = require('root/jobs/ee/table/columnValues')
const tableRows$ = require('root/jobs/ee/table/rows')
const tableQuery$ = require('root/jobs/ee/table/query')
const tableMap$ = require('root/jobs/ee/table/map')
const check$ = require('root/jobs/ee/check')
const testHttp$ = require('root/jobs/test/http')
const testHttpDirect$ = require('root/jobs/test/http/test')
const testWs$ = require('root/jobs/test/ws')

module.exports = router =>
    router
        .post('/sceneareas', stream(ctx => sceneAreas$(ctx)))
        .post('/preview', stream(ctx => preview$(ctx)))
        .post('/bands', stream(ctx => imageBands$(ctx)))
        .post('/image/assetVisualizations', stream(ctx => assetVisualizations$(ctx)))
        .post('/image/histogram', stream(ctx => imageHistogram$(ctx)))
        .post('/image/distinctBandValues', stream(ctx => distinctBandValues$(ctx)))
        .get('/image/sample', stream(ctx => sampleImage$(ctx)))
        .post('/imageMetadata', stream(ctx => imageMetadata$(ctx)))
        .post('/recipe/geometry', stream(ctx => imageGeometry$(ctx)))
        .post('/recipe/bounds', stream(ctx => imageBounds$(ctx)))
        .post('/aoi/bounds', stream(ctx => aoiBounds$(ctx)))
        .post('/ccdc/loadSegments', stream(ctx => loadCCDCSegments$(ctx)))
        .post('/timeSeries/loadObservations', stream(ctx => loadTimeSeriesbservations$(ctx)))
        .post('/nextReferenceDataPoints', stream(ctx => nextReferenceDataPoints$(ctx)))
        .get('/table/rows', stream(ctx => tableRows$(ctx)))
        .get('/table/columns', stream(ctx => tableColumns$(ctx)))
        .get('/table/columnValues', stream(ctx => tableColumnValues$(ctx)))
        .post('/table/query', stream(ctx => tableQuery$(ctx)))
        .get('/table/map', stream(ctx => tableMap$(ctx)))
        .get('/test/worker/:min/:max/:errorProbability', stream(ctx => testHttp$(ctx)))
        .post('/test/worker/:min/:max/:errorProbability', stream(ctx => testHttp$(ctx)))
        .get('/test/direct/:min/:max/:errorProbability', stream(
            ({params: {min, max, errorProbability}}) => testHttpDirect$(parseInt(min), parseInt(max), parseInt(errorProbability))
        ))
        .get('/ws/:name', stream(ctx => testWs$(ctx)))
        .get('/healthcheck', stream(ctx => check$(ctx)))
<|endoftext|>


<commit_before>(function(){

})();
<commit_msg>Remove useless file<commit_after><|endoftext|>