<commit_before>
// channel topic
let channelTopic = "";
// channel mode
let channelMode  = "";

/* Hides a join / part / quit message if it was the user's
 *
 * @param message {DOM Element} - the message
 *
 * @return vooid
 */
function hideIfOwn(message) {
	// get the users Nickname
	app.localUserNickname((nickname) => {
		let nicknameRegex = new RegExp(nickname + '_?');
		if($(message).find('b').text().search(nicknameRegex) != -1){
			$(message).remove();
		}
	});
}

/* Updates the channelMode status variable and deletes the mode set message
 * if the mode hasn't changed
 *
 * @param message {DOM Element} - the message
 *
 * @return vooid
 */
function handleModeChange(message) {
	let newMode = $(message).find('b').text();
	if(channelMode === newMode){
		$(message).remove();
	}
	channelMode = newMode;
}

/* Updates the channelTopic status variable and deletes the topic change message
 * if the topic hasn't changed
 *
 * @param message {DOM Element} - the message
 *
 * @return vooid
 */
function handleTopicChange(message) {
	// Set By message
	if(getCommand(message) === '333'){
		let prevMessage = getPreviousMessage(message);
		// Topic is message
		if(getCommand(prevMessage) === '332'){
			let newTopic = $(prevMessage).find('.message').text().replace('Topic is', '').trim();
			// delete the messages if the topic hasn't changed
			if(newTopic === channelTopic){
				$(message).remove()
				$(prevMessage).remove();
			}
			// update the topic state
			channelTopic = newTopic;
		}
	}
}
<commit_msg><Nick> set Topic to message are removed, if the topic has not changed<commit_after>
// channel topic
let channelTopic = "";
// channel mode
let channelMode  = "";

/* Hides a join / part / quit message if it was the user's
 *
 * @param message {DOM Element} - the message
 *
 * @return vooid
 */
function hideIfOwn(message) {
	// get the users Nickname
	app.localUserNickname((nickname) => {
		let nicknameRegex = new RegExp(nickname + '_?');
		if($(message).find('b').text().search(nicknameRegex) != -1){
			$(message).remove();
		}
	});
}

/* Updates the channelMode status variable and deletes the mode set message
 * if the mode hasn't changed
 *
 * @param message {DOM Element} - the message
 *
 * @return vooid
 */
function handleModeChange(message) {
	let newMode = $(message).find('b').text();
	if(channelMode === newMode){
		$(message).remove();
	}
	channelMode = newMode;
}

/* Updates the channelTopic status variable and deletes the topic change message
 * if the topic hasn't changed
 * It also removes <Nick> set Topic to message, if the topic hasn't changed
 *
 * @param message {DOM Element} - the message
 *
 * @return vooid
 */
function handleTopicChange(message) {
	// Set By message
	if(getCommand(message) === '333'){
		let prevMessage = getPreviousMessage(message);
		// Topic is message
		if(getCommand(prevMessage) === '332'){
			let newTopic = $(prevMessage).find('.message').text().replace('Topic is', '').trim();
			// delete the messages if the topic hasn't changed
			if(newTopic === channelTopic){
				console.log(newTopic);
				console.log(channelTopic);
				$(message).remove()
				$(prevMessage).remove();
			}
			// update the topic state
			channelTopic = newTopic;
		}
	}
	// <Nick> changed Topic to messge
	if(getCommand(message) === 'topic'){
		let messageContent = getMessageContent(message);
		// gets the first index of 'topic to', which has 9 characters (indluding the whitepace)
		let topicStartIndex = messageContent.lastIndexOf('topic to') + 9;
		let newTopic = messageContent.substr(topicStartIndex);
		if(newTopic === channelTopic){
			message.remove();
		}
		channelTopic = newTopic;
	}
}
<|endoftext|>


<commit_before>function searchFavorites(query) {
	var feedback = [];
	var resultList = JSON.parse(localStorage.getItem("results"));
	if (resultList == null) {
		return feedback;
	} else {
		_.each(resultList, function(x) {
			if (x.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);
			} else if (x.tags.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);

			} else if (x.notes.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);
			}
		});
	}
	return feedback;
}

function getFavoriteCategories() {

	var feedback = {};
	var resultList = JSON.parse(localStorage.getItem("results"));
	//returns the list of lists (of categories);
	_.each(resultList, function(x) {
		feedback[x.name] = [];
		_.each(x.categories, function(y) {
			feedback[x.name].push(y[1]);
		});
	});
	var answer = {};
	//a temp variable used in getBroadCategories which will be filled which a business's category hierachy
	var cats = [];
	//a list of 'answer' lists; each element in cats is a list containing the hierachy for each business

	_.each(feedback, function(innerCat, ky) {

		//	alert(innerCat); works- shows the strings of the categories
		cats.push(getBroadCategories(answer, innerCat, categories));
		answer = {};
	});
	//alert(cats);
	return cats;
}

//this function needs testing

function getBroadCategories(answers, innerCat, globalCategories) {

	for (var singleCat in innerCat) {
		answers[singleCat] = [];
		var hierarchy = [];
		//alert(globalCategories);
		answers[singleCat] = findStrings(singleCat, hierarchy, globalCategories);

	}
	return answers;
}

function findStrings(singleCat, catsForThisCat, globalCategories) {
	for (var ky in globalCategories) {
		if ( typeof globalCategories == 'object') {
			catsForThisCat.push(globalCategories);
			findStrings(singleCat, catsForThisCat, globalCategories[ky]);
		} else if ( typeof globalCategories == 'string') {

			if (globalCategories.toLowerCase().search(singleCat.toLowerCase()) > -1) {
				alert(singleCat);
				return catsForThisCat;
				//return the list which contains the hierachy of categories for this business
				//first element in the list is the inner most category and the last element is the broad category
			} else {
				catsForThisCat = [];
			}//else, the category of the item is not this one.
		}
	}
}

function getFavoritesWithinCategory(query) {
	var feedback = [];
	var resultList = JSON.parse(localStorage.getItem("results"));

	_.each(resultList, function(x) {
		if (x.categories == query) {
			feedback.push(x);
		}
	});
	return feedback;
}

function addBusinessToFavorite(business) {

	var resultList = JSON.parse(localStorage.getItem("results"));
	if (resultList == null) {
		resultList = [];

	}
	resultList.push(business);
	localStorage.setItem("results", JSON.stringify(resultList));
}

function deleteBusinessFromStorage(business) {
	var resultList = JSON.parse(localStorage.getItem("results"));
	var temp = removeA(resultList, business);
	localStorage.setItem("results", JSON.stringify(temp));
	getBookmarks(lastTerm[0]);
}

function removeA(array, item) {
	 for(var i in array){
    if(array[i].id == item.id) {
            array.splice(i,1);
            break;
            }
    }
	return array;
}

function saveBookmark(business, tags, notes) {
	if (tags == undefined) {
		tags = " ";
	}
	if (notes == undefined) {
		notes = " ";
	}
	business.tags = tags;
	business.notes = notes;
	var d = new Date();
	var day = d.getDate();
	var month = d.getMonth() + 1;
	var time = d.getTime();
	var year = d.getFullYear();
	business.dateAdded = time + " " + month + "/" + day + "/" + year;
	addBusinessToFavorite(business);
}<commit_msg>Add search for location in favorites.<commit_after>function searchFavorites(query) {
	var feedback = [];
	var resultList = JSON.parse(localStorage.getItem("results"));
	if (resultList == null) {
		return feedback;
	} else {
		_.each(resultList, function(x) {
			if (x.name.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);
			} else if (x.tags.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);

			} else if (x.notes.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);
			}
			else if (x.location.display_address.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				feedback.push(x);
			}
		});
	}
	return feedback;
}

function getFavoriteCategories() {

	var feedback = {};
	var resultList = JSON.parse(localStorage.getItem("results"));
	//returns the list of lists (of categories);
	_.each(resultList, function(x) {
		feedback[x.name] = [];
		_.each(x.categories, function(y) {
			feedback[x.name].push(y[1]);
		});
	});
	var answer = {};
	//a temp variable used in getBroadCategories which will be filled which a business's category hierachy
	var cats = [];
	//a list of 'answer' lists; each element in cats is a list containing the hierachy for each business

	_.each(feedback, function(innerCat, ky) {

		//	alert(innerCat); works- shows the strings of the categories
		cats.push(getBroadCategories(answer, innerCat, categories));
		answer = {};
	});
	//alert(cats);
	return cats;
}

//this function needs testing

function getBroadCategories(answers, innerCat, globalCategories) {

	for (var singleCat in innerCat) {
		answers[singleCat] = [];
		var hierarchy = [];
		//alert(globalCategories);
		answers[singleCat] = findStrings(singleCat, hierarchy, globalCategories);

	}
	return answers;
}

function findStrings(singleCat, catsForThisCat, globalCategories) {
	for (var ky in globalCategories) {
		if ( typeof globalCategories == 'object') {
			catsForThisCat.push(globalCategories);
			findStrings(singleCat, catsForThisCat, globalCategories[ky]);
		} else if ( typeof globalCategories == 'string') {

			if (globalCategories.toLowerCase().search(singleCat.toLowerCase()) > -1) {
				alert(singleCat);
				return catsForThisCat;
				//return the list which contains the hierachy of categories for this business
				//first element in the list is the inner most category and the last element is the broad category
			} else {
				catsForThisCat = [];
			}//else, the category of the item is not this one.
		}
	}
}

function getFavoritesWithinCategory(query) {
	var feedback = [];
	var resultList = JSON.parse(localStorage.getItem("results"));

	_.each(resultList, function(x) {
		if (x.categories == query) {
			feedback.push(x);
		}
	});
	return feedback;
}

function addBusinessToFavorite(business) {

	var resultList = JSON.parse(localStorage.getItem("results"));
	if (resultList == null) {
		resultList = [];

	}
	resultList.push(business);
	localStorage.setItem("results", JSON.stringify(resultList));
}

function deleteBusinessFromStorage(business) {
	var resultList = JSON.parse(localStorage.getItem("results"));
	var temp = removeA(resultList, business);
	localStorage.setItem("results", JSON.stringify(temp));
	getBookmarks(lastTerm[0]);
}

function removeA(array, item) {
	 for(var i in array){
    if(array[i].id == item.id) {
            array.splice(i,1);
            break;
            }
    }
	return array;
}

function saveBookmark(business, tags, notes) {
	if (tags == undefined) {
		tags = " ";
	}
	if (notes == undefined) {
		notes = " ";
	}
	business.tags = tags;
	business.notes = notes;
	var d = new Date();
	var day = d.getDate();
	var month = d.getMonth() + 1;
	var time = d.getTime();
	var year = d.getFullYear();
	business.dateAdded = time + " " + month + "/" + day + "/" + year;
	addBusinessToFavorite(business);
}<|endoftext|>


<commit_before>/*
	Dice
	Dice Class
	By Luke Nickerson, 2014
*/

(function(){
	var myFileName = "dice";
	var myClassName = "Dice";

	var Dice = function(){
		this.randSeed = 1;
		this.type = "random";
	}
	// NOT based on random-type
	Dice.prototype.getRandom = Math.random;
	Dice.prototype.getPseudoRandomBySeed = function(seed){
		// http://stackoverflow.com/a/19303725/1766230
		var x = Math.sin(seed) * 10000;
		return x - Math.floor(x);
	};
	Dice.prototype.getPseudoRandom = function(){
		return this.getPseudoRandomBySeed(this.randSeed++);
	};

	//==== Basics: "random" function returns either a
	// true random number or a pseudorandom number based on
	// the random-type that is set.
	Dice.prototype.random = Math.random;
	Dice.prototype.switchToPseudoRandom = function(){
		this.type = "pseudorandom";
		this.random = this.getPseudoRandom;
	}
	Dice.prototype.switchToRandom = function(){
		this.type = "random";
		this.random = Math.random;
	}
	Dice.prototype.setSeed = function(s){
		if (typeof s == "undefined") {
			s = this._normalize(Math.random(), 10000);
		}
		this.randSeed = s;
	}
	Dice.prototype._normalize = function(rand, n){
		return (Math.floor(rand * n) + 1);
	}

	//==== "Roll" functions
	Dice.prototype.roll1d = function (sides) {
		return this._normalize(this.random(), sides);
	}
	Dice.prototype.rollxd = function (num, sides) {
		var sum = 0;
		for (var i = 0; i < num; i++){
			sum += this.roll1d(sides);
		}
		return sum;
	}
	Dice.prototype.roll = function(){
		if (arguments.length == 1) {
			return this.roll1d(arguments[0]);
		} else if (arguments.length == 2) {
			return this.rollxd(arguments[0], arguments[1]);
		} else if (arguments.length == 3) {
			return this.rollxd(arguments[0], arguments[1]) + arguments[2];
		} else {
			console.error("Roll needs 1, 2, or 3 arguments");
		}
	}

	//==== "Get" functions -- Based on random-type
	Dice.prototype.getRandomInteger = Dice.prototype.roll1d;
	Dice.prototype.getRandomIntegerBetween = function (min, max) {
		return Math.floor(this.random() * (max - min + 1) + min);
	}
	Dice.prototype.getRandomAround = function(n){ // BELL
		var a = this.random();
		var b = this.random();
		return (n * (a-b));
	}

	// Install into RocketBoots if it exists, otherwise make global
	if (typeof RocketBoots == "object") {
		RocketBoots.installComponent(myFileName, myClassName, Dice);
	} else window[myClassName] = Dice;
})();<commit_msg>two new functions: flip and selectRandom<commit_after>/*
	Dice
	Dice Class
	By Luke Nickerson, 2014
*/

(function(){
	var myFileName = "dice";
	var myClassName = "Dice";

	var Dice = function(){
		this.randSeed = 1;
		this.type = "random";
	}
	// NOT based on random-type
	Dice.prototype.getRandom = Math.random;
	Dice.prototype.getPseudoRandomBySeed = function(seed){
		// http://stackoverflow.com/a/19303725/1766230
		var x = Math.sin(seed) * 10000;
		return x - Math.floor(x);
	};
	Dice.prototype.getPseudoRandom = function(){
		return this.getPseudoRandomBySeed(this.randSeed++);
	};

	//==== Basics: "random" function returns either a
	// true random number or a pseudorandom number based on
	// the random-type that is set.
	Dice.prototype.random = Math.random;
	Dice.prototype.switchToPseudoRandom = function(){
		this.type = "pseudorandom";
		this.random = this.getPseudoRandom;
	}
	Dice.prototype.switchToRandom = function(){
		this.type = "random";
		this.random = Math.random;
	}
	Dice.prototype.setSeed = function(s){
		if (typeof s == "undefined") {
			s = this._normalize(Math.random(), 10000);
		}
		this.randSeed = s;
	}
	Dice.prototype._normalize = function(rand, n){
		return (Math.floor(rand * n) + 1);
	}

	//==== "Roll" functions
	Dice.prototype.roll1d = function (sides) {
		return this._normalize(this.random(), sides);
	}
	Dice.prototype.rollxd = function (num, sides) {
		var sum = 0;
		for (var i = 0; i < num; i++){
			sum += this.roll1d(sides);
		}
		return sum;
	}
	Dice.prototype.roll = function(){
		if (arguments.length == 1) {
			return this.roll1d(arguments[0]);
		} else if (arguments.length == 2) {
			return this.rollxd(arguments[0], arguments[1]);
		} else if (arguments.length == 3) {
			return this.rollxd(arguments[0], arguments[1]) + arguments[2];
		} else {
			console.error("Roll needs 1, 2, or 3 arguments");
		}
	};
	Dice.prototype.flip = function(heads, tails){
		if (typeof heads === 'undefined' && typeof tails === 'undefined') {
			heads = true;
			tails = false;
		}
		return (this.roll1d(2) == 1) ? heads : tails;
	};
	Dice.prototype.selectRandom = function(arr){
		var r = Math.floor(this.random() * arr.length);
		return arr[r];
	}

	//==== "Get" functions -- Based on random-type
	Dice.prototype.getRandomInteger = Dice.prototype.roll1d;
	Dice.prototype.getRandomIntegerBetween = function (min, max) {
		return Math.floor(this.random() * (max - min + 1) + min);
	}
	Dice.prototype.getRandomAround = function(n){ // BELL
		var a = this.random();
		var b = this.random();
		return (n * (a-b));
	}

	// Install into RocketBoots if it exists, otherwise make global
	if (typeof RocketBoots == "object") {
		RocketBoots.installComponent(myFileName, myClassName, Dice);
	} else window[myClassName] = Dice;
})();<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";
/*
 * scrape_champ_ids.js -- scrape Mobafire for champion name -> ID mapping
 *
 * Copyright (C) 2017 Dan Poggi
 *
 * This software may be modified and distributed under the terms
 * of the MIT license. See the LICENSE file for details.
 */

const https = require("https");

https.get("https://www.mobafire.com/league-of-legends/champions", response => {
  const { statusCode } = response;
  const contentType = response.headers["content-type"];

  if (statusCode !== 200) {
    throw new Error(`HTTP request failed with status ${statusCode}`);
  } else if (!/text\/html/.test(contentType)) {
    throw new Error(`HTTP request failed with invalid Content-Type ${contentType}`);
  }

  let html = "";

  response.setEncoding("utf8");

  response.on("data", chunk => { html += chunk; });

  response.on("end", () => {
    const ids = {};
    const re = /\/champion\/([a-z\-]+)-(\d{1,3})/g;

    for (let match = re.exec(html); match != null; match = re.exec(html)) {
      const name = match[1].replace("-", " ");
      const id = Number.parseInt(match[2]);

      ids[name] = id;
    }

    process.stdout.write(JSON.stringify(ids, undefined, 2));

    if (process.stdout.isTTY) {
      console.error("\n\nSuccess! Redirect (>>) to src/mobafire.js to append champ IDs.");
    } else {
      console.error("Success! Check mobafire.js!");
    }
  });
});
<commit_msg>Console output consistency<commit_after>#!/usr/bin/env node
"use strict";
/*
 * scrape_champ_ids.js -- scrape Mobafire for champion name -> ID mapping
 *
 * Copyright (C) 2017 Dan Poggi
 *
 * This software may be modified and distributed under the terms
 * of the MIT license. See the LICENSE file for details.
 */

const https = require("https");

https.get("https://www.mobafire.com/league-of-legends/champions", response => {
  const { statusCode } = response;
  const contentType = response.headers["content-type"];

  if (statusCode !== 200) {
    throw new Error(`HTTP request failed with status ${statusCode}`);
  } else if (!/text\/html/.test(contentType)) {
    throw new Error(`HTTP request failed with invalid Content-Type ${contentType}`);
  }

  let html = "";

  response.setEncoding("utf8");

  response.on("data", chunk => { html += chunk; });

  response.on("end", () => {
    const ids = {};
    const re = /\/champion\/([a-z\-]+)-(\d{1,3})/g;

    for (let match = re.exec(html); match != null; match = re.exec(html)) {
      const name = match[1].replace("-", " ");
      const id = Number.parseInt(match[2]);

      ids[name] = id;
    }

    process.stdout.write(JSON.stringify(ids, undefined, 2));

    if (process.stdout.isTTY) {
      console.error("\n\nSuccess! Redirect (>>) to src/mobafire.js to append champ IDs.");
    } else {
      console.error("Success! Check src/mobafire.js!");
    }
  });
});
<|endoftext|>


<commit_before>if(typeof(AKHB) == 'undefined'){
	AKHB = {};
}
if(typeof(AKHB.services) == 'undefined'){
	AKHB.services = {};
}
if(typeof(AKHB.services.db) == 'undefined'){
	AKHB.services.db = {};
}

AKHB.services.db.DBSync =  (function(){

	var getLastModified = function(result){
		if(!result){
			return '1900-01-01 00:00:00';
		}else{
			return result.lastUpdatetime;
		}
	}

	Request = function(table,user,lastModified){
		return {
			type:2,
			table:table,
			uuid:user.id,
			os:user.os,
			device:user.deviceName,
			version:user.appVersion,
			last_content_synced:moment(lastModified).format('YYYY-MM-DD')
		}
	};

	return function(appConfig,$http){

		var remoteAddress = appConfig.remoteAddress;
		var dbServices = DB;
		//http://stage.iiuk.homeip.net/Pages/Healthboard_App/webservice.php?type=2&id=[uuid]&os=8.1&device=iphone6s&version=1.0&last_content_synced=2013-12-12

		this.syncArticle = function(callback,tx){
				async.waterfall([
						function(callback){
							dbServices.getTableLastUpdateTime('articles',function(err,result){
								var requestData = Request('articles',AKHB.user,getLastModified(result));
								var url = remoteAddress+'/webservice.php?'+ decodeURIComponent($.param(requestData));
								callback(null,url);
							});
						},
						function(url,callback){
							$.getJSON(url,function(result){
								callback(null,result);
							});
						},
						function(result,callback){
							if(result.response == 1){
								var lastModified;
								async.each(result.content,function(article,callback){
									try{
										dbServices.setArticle(true,article,callback);
									}catch(err){
										callback(err);
									}
								},function(err){
									callback(null,result.content.length,result.last_content_synced);
								});
							}else{
								callback(null,0,result.last_content_synced);
							}
						},function(affectCount,lastModified,callback){
							dbServices.setTableLastUpdateTime(true,'articles',lastModified,function(err,result){
								callback(null,result,affectCount);
							})
						}
					],function(err,result){
						if(err){
							console.log(err,result);
						}else{
							function syncSuccess(){
								console.log("Sync articles success.");
								if(callback && typeof callback == 'function') callback(null,result);
							}
							if(tx || persistence.flushHooks.length == 0){
								syncSuccess();
							}else{
								persistence.flush(null,function() {
								  syncSuccess();
								});
							}

						}
				});

		}

		this.syncMessage = function(callback,tx){
			try{
				async.waterfall([
						function(callback){
							dbServices.getTableLastUpdateTime('messages',function(err,result){
								var requestData = Request('messages',AKHB.user,getLastModified(result));
								var url = remoteAddress+'/webservice.php?'+ decodeURIComponent($.param(requestData));
								callback(null,url);
							});
						},
						function(url,callback){
							jQuery.ajax({
			                    url: url,
			                    type: "get",
			                    dataType: "json",
			                    success: function(msg) {
			                        callback(null,msg);
			                    },
			                    error: function(XMLHttpRequest, textStatus, errorThrown) {
			                    	console.log(errorThrown);
			                        callback(true,null);
			                    },
			                    complete: function(XMLHttpRequest, textStatus) {
			                    }
			                });
						},
						function(result,callback){
							if(result.response == 1){
								var lastModified;
								async.each(result.content,function(_message,callback){
									_message.read = 0;
									try{
										dbServices.setMessage(true,_message,callback);
									}catch(err){
										callback(err);
									}
								},function(err){
									callback(null,result.content.length,result.last_content_synced);
								});
							}else{
								callback(null,0,result.last_content_synced);
							}
						},function(affectCount,lastModified,callback){
							dbServices.setTableLastUpdateTime(true,'messages',lastModified,function(err,result){
								console.log('updated messages last_content_synced');
								callback(false,result,affectCount);
							})
						}
					],function(err,result){
						if(err){
							console.log(err,result);
							callback(null);
						}else{
							function syncSuccess(){
								console.log("Sync messages success.");
								dbServices.getLatestActiveMessage(function(err,messsage){
									console.log(messsage);
									if(messsage){
										AKHB.notification.alert(messsage.content,function(){
											messsage.read = 1;
											persistence.flush(null,function() {
												if(callback && typeof callback == 'function') callback(null,result);
											});
										},messsage.title);
									}else{
										if(callback && typeof callback == 'function') callback(null,result);
									}

								});
							}
							if(tx || persistence.flushHooks.length == 0){
								syncSuccess();
							}else{
								persistence.flush(null,function() {
								  syncSuccess();
								});
							}

						}
				});
			}catch(ex){
				callback(null);
				console.log(ex);
			}

		}
		this.syncNavigation = function(callback,tx){

				async.waterfall([
						function(callback){
							dbServices.getTableLastUpdateTime('navigations',function(err,result){
								var requestData = Request('navigation',AKHB.user,getLastModified(result));
								var url = remoteAddress+'/webservice.php?'+ decodeURIComponent($.param(requestData));
								callback(null,url);
							});
						},
						function(url,callback){
							$.getJSON(url,function(result){
								callback(false,result)
							});
						},
						function(result,callback){
							if(result.response == 1){
								var lastModified;
								async.each(result.content,function(navigation,callback){
									try{
										dbServices.setNavigation(true,navigation,callback);
									}catch(err){
										console.log(err);
										callback(err);
									}
								},function(err){
									callback(null,result.content.length,result.last_content_synced);
								});
							}else{
								callback(null,0,result.last_content_synced);
							}
						},function(affectCount,lastModified,callback){
							dbServices.setTableLastUpdateTime(true,'navigations',lastModified,function(result){
								console.log('updated navigations last_content_synced');
								callback(false,result,affectCount);
							})
						}
					],function(err,result){
						if(err){
							console.log(err,result);
						}else{

							function syncSuccess(){
								console.log("Sync navigation success.");
								if(callback && typeof callback == 'function') callback(null,result);
							}
							if(tx || persistence.flushHooks.length == 0){
								syncSuccess();
							}else{
								persistence.flush(null,function() {
								  syncSuccess();
								});
							}
						}
				});

		}
		this.syncDirectory = function(callback,tx){

				async.waterfall([
						function(callback){
							dbServices.getTableLastUpdateTime('directories',function(err,result){
								var requestData = Request('directory',AKHB.user,getLastModified(result));
								requestData.type = 5;

								var url = remoteAddress+'/webservice.php?'+ decodeURIComponent($.param(requestData));
								callback(null,url);
							});
						},
						function(url,callback){
							$.getJSON(url,function(result){
								callback(false,result)
							});
						},
						function(result,callback){
							if(result.response == 1){
								var lastModified;
								//async.each(result,function(directory,callback){
								async.each(result.content,function(directory,callback){

									try{
										dbServices.setDirectoryCategories(directory,function(err){
											if(!err) {
												callback(null,result.content.length,result.last_modified);
												return;
											}
											callback(err);
										});
									}catch(err){
										console.log("Error - setDirectoryCategories:",err);
										callback(err);
									}
								},function(err){
									console.log('syncing directory');
									//callback(null,result.length,new Date());
									callback(null,result.content.length,result.last_content_synced);
								});
							}else{
								callback(null,0,result.last_modified);
							}
						},function(affectCount,lastModified,callback){
							//
							dbServices.setTableLastUpdateTime(true,'directories',lastModified,function(result){
								console.log('updated directories last_content_synced');
								callback(false,result,affectCount);
							})
						}
					],function(err,result){
						if(err){
							console.log(err,result);
						}else{

							function syncSuccess(){
								console.log("Sync directory success.");
								if(callback && typeof callback == 'function') callback(null,result);
							}
							if(tx || persistence.flushHooks.length == 0){
								syncSuccess();
							}else{
								persistence.flush(null,function() {
								  syncSuccess();
								});
							}
						}
				});

		}
		this.syncCommittees = function(callback,tx){
			var requestData = null;
			async.waterfall([
						function(callback){
							dbServices.getTableLastUpdateTime('committees',function(err,result){
								requestData = Request('committees',AKHB.user,getLastModified(result));
								var url = remoteAddress+'/webservice.php?'+ decodeURIComponent($.param(requestData));
								callback(null,url);
							});
						},
						function(url,callback){
							$.getJSON(url,function(result){
								callback(false,result)
							});
						},
						function(result,callback){
							if(result.response == 1){
								var lastModified;
								async.each(result.content,function(committe,callback){
									committe.last_modified_date = requestData.last_content_synced;
									try{
										dbServices.setCommitte(true,committe,remoteAddress,callback);
									}catch(err){
										console.log(err);
										callback(err);
									}
								},function(err){
									callback(null,result.content.length,result.last_modified );
								});
							}else{
								callback(null,0,result.last_modified );
							}
						},function(affectCount,lastModified,callback){
							dbServices.setTableLastUpdateTime(true,'committees',lastModified,function(result){
								console.log('updated committees last_modified_date',lastModified);
								callback(false,result,affectCount);
							})
						}
					],function(err,result){
						if(err){
							console.log(err,result);
						}else{

							function syncSuccess(){
								console.log("Sync last_modified_date success.");
								if(callback && typeof callback == 'function') callback(null,result);
							}
							if(tx || persistence.flushHooks.length == 0){
								syncSuccess();
							}else{
								persistence.flush(null,function() {
								  syncSuccess();
								});
							}
						}
				});

		};
		this.syncUsage = function(callback,tx){
			var url = remoteAddress+'/webservice.php?type=3';
			function sendUsage(type,callback){
				DB.getUsage(type,function(err,data){
					var request = [];

					if(data.length == 0) {
						callback(null);
						return;
					}

					$.each(data,function(index,_usage){

						request.push({
							type:_usage.type,
							id:AKHB.user.id,
							content_id:_usage.content_id,
							date_time:_usage.date_time
						});
					});
					var postdata = {
						type:type,
						usage:request
					};
					$.post(url,postdata,function(res, textStatus, jqXHR){

						if(textStatus=="success"){
							$.each(data,function(index,_usage){
								persistence.remove(_usage);
							});
						}
					});
					callback(null);
				});
			}
			try{
				async.series([
					function(callback){
						sendUsage(1,callback);
					},
					function(callback){
						sendUsage(2,callback);
					}
				],function(err){
					persistence.flush(null,function() {
					  callback(err);
					});

				});
			}catch(e){
				console.log(e);
				callback(e);
			}

		};
		this.runInBackGround = function(callback){
			var self = this;
			console.log("runInBackGround");
			async.series([

				function(callback){
					console.log("syncArticle");
					self.syncArticle(function(){
						console.log("syncArticle finish");
						callback(null);
					},true);
				},
				function(callback){
					console.log("syncNavigation");
					self.syncNavigation(function(){
						console.log("syncNavigation finish");
						callback(null);
					},true);
				},

				function(callback){
					console.log("syncMessage");
					self.syncMessage(function(){
						console.log("syncMessage finish");
						callback(null);
					},true);
				},
				function(callback){
					console.log("syncUsage");
					self.syncUsage(function(){
						console.log("syncUsage finish");
						callback(null);
					},true);
				},function(callback){
					console.log("syncCommittees");
					self.syncCommittees(function(){
						console.log("syncCommittees finish");
						callback(null);
					},true);
				},
			],function(err){
				console.log("runInBackGround finish");
				persistence.flush(null,function() {
					if(callback && typeof callback == 'function')
						callback(err);
				});
			})
		}
	}
})();

<commit_msg>-----------<commit_after>if(typeof(AKHB) == 'undefined'){
	AKHB = {};
}
if(typeof(AKHB.services) == 'undefined'){
	AKHB.services = {};
}
if(typeof(AKHB.services.db) == 'undefined'){
	AKHB.services.db = {};
}

AKHB.services.db.DBSync =  (function(){

	var getLastModified = function(result){
		if(!result){
			return '1900-01-01 00:00:00';
		}else{
			return result.lastUpdatetime;
		}
	}

	Request = function(table,user,lastModified){
		return {
			type:2,
			table:table,
			uuid:user.id,
			os:user.os,
			device:user.deviceName,
			version:user.appVersion,
			last_content_synced:moment(lastModified).format('YYYY-MM-DD')
		}
	};

	return function(appConfig,$http){

		var remoteAddress = appConfig.remoteAddress;
		var dbServices = DB;
		//http://stage.iiuk.homeip.net/Pages/Healthboard_App/webservice.php?type=2&id=[uuid]&os=8.1&device=iphone6s&version=1.0&last_content_synced=2013-12-12

		this.syncArticle = function(callback,tx){
				async.waterfall([
						function(callback){
							dbServices.getTableLastUpdateTime('articles',function(err,result){
								var requestData = Request('articles',AKHB.user,getLastModified(result));
								var url = remoteAddress+'/webservice.php?'+ decodeURIComponent($.param(requestData));
								callback(null,url);
							});
						},
						function(url,callback){
							$.getJSON(url,function(result){
								callback(null,result);
							});
						},
						function(result,callback){
							if(result.response == 1){
								var lastModified;
								async.each(result.content,function(article,callback){
									try{
										dbServices.setArticle(true,article,callback);
									}catch(err){
										callback(err);
									}
								},function(err){
									callback(null,result.content.length,result.last_content_synced);
								});
							}else{
								callback(null,0,result.last_content_synced);
							}
						},function(affectCount,lastModified,callback){
							dbServices.setTableLastUpdateTime(true,'articles',lastModified,function(err,result){
								callback(null,result,affectCount);
							})
						}
					],function(err,result){
						if(err){
							console.log(err,result);
						}else{
							function syncSuccess(){
								console.log("Sync articles success.");
								if(callback && typeof callback == 'function') callback(null,result);
							}
							if(tx || persistence.flushHooks.length == 0){
								syncSuccess();
							}else{
								persistence.flush(null,function() {
								  syncSuccess();
								});
							}

						}
				});

		}

		this.syncMessage = function(callback,tx){
			try{
				async.waterfall([
						function(callback){
							dbServices.getTableLastUpdateTime('messages',function(err,result){
								var requestData = Request('messages',AKHB.user,getLastModified(result));
								var url = remoteAddress+'/webservice.php?'+ decodeURIComponent($.param(requestData));
								callback(null,url);
							});
						},
						function(url,callback){
							jQuery.ajax({
			                    url: url,
			                    type: "get",
			                    dataType: "json",
			                    success: function(msg) {
			                        callback(null,msg);
			                    },
			                    error: function(XMLHttpRequest, textStatus, errorThrown) {
			                    	console.log(errorThrown);
			                        callback(true,null);
			                    },
			                    complete: function(XMLHttpRequest, textStatus) {
			                    }
			                });
						},
						function(result,callback){
							if(result.response == 1){
								var lastModified;
								async.each(result.content,function(_message,callback){
									_message.read = 0;
									try{
										dbServices.setMessage(true,_message,callback);
									}catch(err){
										callback(err);
									}
								},function(err){
									callback(null,result.content.length,result.last_content_synced);
								});
							}else{
								callback(null,0,result.last_content_synced);
							}
						},function(affectCount,lastModified,callback){
							dbServices.setTableLastUpdateTime(true,'messages',lastModified,function(err,result){
								console.log('updated messages last_content_synced');
								callback(false,result,affectCount);
							})
						}
					],function(err,result){
						if(err){
							console.log(err,result);
							callback(null);
						}else{
							function syncSuccess(){
								console.log("Sync messages success.");
								dbServices.getLatestActiveMessage(function(err,messsage){
									console.log(messsage);
									if(messsage){
										AKHB.notification.alert(messsage.content,function(){
											messsage.read = 1;
											persistence.flush(null,function() {
												if(callback && typeof callback == 'function') callback(null,result);
											});
										},messsage.title);
									}else{
										if(callback && typeof callback == 'function') callback(null,result);
									}

								});
							}
							if(tx || persistence.flushHooks.length == 0){
								syncSuccess();
							}else{
								persistence.flush(null,function() {
								  syncSuccess();
								});
							}

						}
				});
			}catch(ex){
				callback(null);
				console.log(ex);
			}

		}
		this.syncNavigation = function(callback,tx){

				async.waterfall([
						function(callback){
							dbServices.getTableLastUpdateTime('navigations',function(err,result){
								var requestData = Request('navigation',AKHB.user,getLastModified(result));
								var url = remoteAddress+'/webservice.php?'+ decodeURIComponent($.param(requestData));
								callback(null,url);
							});
						},
						function(url,callback){
							$.getJSON(url,function(result){
								callback(false,result)
							});
						},
						function(result,callback){
							if(result.response == 1){
								var lastModified;
								async.each(result.content,function(navigation,callback){
									try{
										dbServices.setNavigation(true,navigation,callback);
									}catch(err){
										console.log(err);
										callback(err);
									}
								},function(err){
									callback(null,result.content.length,result.last_content_synced);
								});
							}else{
								callback(null,0,result.last_content_synced);
							}
						},function(affectCount,lastModified,callback){
							dbServices.setTableLastUpdateTime(true,'navigations',lastModified,function(result){
								console.log('updated navigations last_content_synced');
								callback(false,result,affectCount);
							})
						}
					],function(err,result){
						if(err){
							console.log(err,result);
						}else{

							function syncSuccess(){
								console.log("Sync navigation success.");
								if(callback && typeof callback == 'function') callback(null,result);
							}
							if(tx || persistence.flushHooks.length == 0){
								syncSuccess();
							}else{
								persistence.flush(null,function() {
								  syncSuccess();
								});
							}
						}
				});

		}
		this.syncDirectory = function(callback,tx){

				async.waterfall([
						function(callback){
							dbServices.getTableLastUpdateTime('directories',function(err,result){
								var requestData = Request('directory',AKHB.user,getLastModified(result));
								requestData.type = 5;

								var url = remoteAddress+'/webservice.php?'+ decodeURIComponent($.param(requestData));
								callback(null,url);
							});
						},
						function(url,callback){
							$.getJSON(url,function(result){
								callback(false,result)
							});
						},
						function(result,callback){
							if(result.response == 1){
								var lastModified;
								//async.each(result,function(directory,callback){
								async.each(result.content,function(directory,callback){

									try{
										dbServices.setDirectoryCategories(directory,function(err){
											if(!err) {
												callback(null,result.content.length,result.last_modified);
												return;
											}
											callback(err);
										});
									}catch(err){
										console.log("Error - setDirectoryCategories:",err);
										callback(err);
									}
								},function(err){
									console.log('syncing directory');
									//callback(null,result.length,new Date());
									callback(null,result.content.length,result.last_content_synced);
								});
							}else{
								callback(null,0,result.last_modified);
							}
						},function(affectCount,lastModified,callback){
							//
							dbServices.setTableLastUpdateTime(true,'directories',lastModified,function(result){
								console.log('updated directories last_content_synced');
								callback(false,result,affectCount);
							})
						}
					],function(err,result){
						if(err){
							console.log(err,result);
						}else{

							function syncSuccess(){
								console.log("Sync directory success.");
								if(callback && typeof callback == 'function') callback(null,result);
							}
							if(tx || persistence.flushHooks.length == 0){
								syncSuccess();
							}else{
								persistence.flush(null,function() {
								  syncSuccess();
								});
							}
						}
				});

		}
		this.syncCommittees = function(callback,tx){
			var requestData = null;
			async.waterfall([
						function(callback){
							dbServices.getTableLastUpdateTime('committees',function(err,result){
								requestData = Request('committees',AKHB.user,getLastModified(result));
								var url = remoteAddress+'/webservice.php?'+ decodeURIComponent($.param(requestData));
								callback(null,url);
							});
						},
						function(url,callback){
							$.getJSON(url,function(result){
								callback(false,result)
							});
						},
						function(result,callback){
							if(result.response == 1){
								var lastModified;
								async.each(result.content,function(committe,callback){
									committe.last_modified_date = requestData.last_content_synced;
									try{
										dbServices.setCommitte(true,committe,remoteAddress,callback);
									}catch(err){
										console.log(err);
										callback(err);
									}
								},function(err){
									callback(null,result.content.length,result.last_modified );
								});
							}else{
								callback(null,0,result.last_modified );
							}
						},function(affectCount,lastModified,callback){
							dbServices.setTableLastUpdateTime(true,'committees',lastModified,function(result){
								console.log('updated committees last_modified_date',lastModified);
								callback(false,result,affectCount);
							})
						}
					],function(err,result){
						if(err){
							console.log(err,result);
						}else{

							function syncSuccess(){
								console.log("Sync last_modified_date success.");
								if(callback && typeof callback == 'function') callback(null,result);
							}
							if(tx || persistence.flushHooks.length == 0){
								syncSuccess();
							}else{
								persistence.flush(null,function() {
								  syncSuccess();
								});
							}
						}
				});

		};
		this.syncUsage = function(callback,tx){
			var url = remoteAddress+'/webservice.php?type=3';
			function sendUsage(type,callback){
				DB.getUsage(type,function(err,data){
					var request = [];

					if(data.length == 0) {
						callback(null);
						return;
					}

					$.each(data,function(index,_usage){

						request.push({
							type:_usage.type,
							id:AKHB.user.id,
							content_id:_usage.content_id,
							date_time:_usage.date_time
						});
					});
					var postdata = {
						type:type,
						usage:request
					};
					$.post(url,postdata,function(res, textStatus, jqXHR){
						console.log(arguments);
						if(textStatus=="success"){
							$.each(data,function(index,_usage){
								persistence.remove(_usage);
							});
						}
					});
					callback(null);
				});
			}
			try{
				async.series([
					function(callback){
						sendUsage(1,callback);
					},
					function(callback){
						sendUsage(2,callback);
					}
				],function(err){
					persistence.flush(null,function() {
					  callback(err);
					});

				});
			}catch(e){
				console.log(e);
				callback(e);
			}

		};
		this.runInBackGround = function(callback){
			var self = this;
			console.log("runInBackGround");
			async.series([

				function(callback){
					console.log("syncArticle");
					self.syncArticle(function(){
						console.log("syncArticle finish");
						callback(null);
					},true);
				},
				function(callback){
					console.log("syncNavigation");
					self.syncNavigation(function(){
						console.log("syncNavigation finish");
						callback(null);
					},true);
				},

				function(callback){
					console.log("syncMessage");
					self.syncMessage(function(){
						console.log("syncMessage finish");
						callback(null);
					},true);
				},
				// function(callback){
				// 	console.log("syncUsage");
				// 	self.syncUsage(function(){
				// 		console.log("syncUsage finish");
				// 		callback(null);
				// 	},true);
				},function(callback){
					console.log("syncCommittees");
					self.syncCommittees(function(){
						console.log("syncCommittees finish");
						callback(null);
					},true);
				},
			],function(err){
				console.log("runInBackGround finish");
				persistence.flush(null,function() {
					if(callback && typeof callback == 'function')
						callback(err);
				});
			})
		}
	}
})();

<|endoftext|>


<commit_before>// Copyright (c) E5R Development Team. All rights reserved.
// Licensed under the MIT License. See LICENSE file for license information.

(function(){ 'use strict'

  var su = sys.require('sysutils.js'),
      fs = sys.require('fsutils.js'),

      // Read comment "Runner Plugin Environment API" in <cmdrunner.js> for
      // more information of environment API
      _env;

  /**
   * Set environment configuration
   */
  function _setup(env){
    _env = env;
    return true;
  }

  /**
   * Run command entry point
   */
  function _run(args){
    try {
      var _args = [
        'kvm.ps1',
        'list'
      ].concat(args);

      var _job = su.exec('powershell', _args, function(line){
        if(line && line.length > 0) sys.logAction(line);
      });
    }catch(error){
      sys.logTask('A error ocurred on showing installed runtime.');
      throw error;
    }
  }

  command.api = {
    setup: _setup,
    run: _run
  }
})();
<commit_msg>Showing message if not version found<commit_after>// Copyright (c) E5R Development Team. All rights reserved.
// Licensed under the MIT License. See LICENSE file for license information.

(function(){ 'use strict'

  var su = sys.require('sysutils.js'),
      fs = sys.require('fsutils.js'),

      // Read comment "Runner Plugin Environment API" in <cmdrunner.js> for
      // more information of environment API
      _env;

  /**
   * Set environment configuration
   */
  function _setup(env){
    _env = env;
    return true;
  }

  /**
   * Run command entry point
   */
  function _run(args){
    try {
      var _args = [
            'kvm.ps1',
            'list'
          ].concat(args),
          _found = false;

      var _job = su.exec('powershell', _args, function(line){
        if(line && line.length > 0){
          sys.logAction(line);
          _found = true;
        }
      });

      if(!_found){
        sys.logAction('No version available.');
      }
    }catch(error){
      sys.logTask('A error ocurred on showing installed runtime.');
      throw error;
    }
  }

  command.api = {
    setup: _setup,
    run: _run
  }
})();
<|endoftext|>


<commit_before>if( !window.Readium ) {
	window.Readium = {
		Models: {},
		Collections: {},
		Views: {},
		Routers: {},
		Utils: {}
	};
}

Readium.Views.PaginationViewBase = Backbone.View.extend({

	el: "#readium-book-view-el",
	renderToLastPage: false,

	initialize: function(options) {
		this.model.on("change:current_page", this.changePage, this);
		this.model.on("change:font_size", this.setFontSize, this);
		this.bindingTemplate = _.template( $('#binding-template').html() );

		// TODO: should I break layers here or pass through?
		this.model.packageDocument.on("increased:spine_position", function() {
			this.renderToLastPage = false;
		}, this);
		this.model.packageDocument.on("decreased:spine_position", function() {
			this.renderToLastPage = true;
		}, this);
	},

	linkClickHandler: function(e) {
		e.preventDefault();

		var href = e.srcElement.attributes["href"].value;
		if(href.match(/^http(s)?:/)) {
			chrome.tabs.create({"url": href});
		} else {
			this.model.goToHref(href);
		}
	},

	getBindings: function() {
		var packDoc = this.model.packageDocument;
		var bindings = packDoc.get('bindings');
		return bindings.map(function(binding) {
			binding.selector = 'object[type="' + binding.media_type + '"]';
			binding.url = packDoc.getManifestItemById(binding.handler).get('href');
			binding.url = packDoc.resolveUri(binding.url);
			return binding;
		})
	},

	applyBindings: function(dom) {
		var that = this;
		var bindings = this.getBindings();
		var i = 0;
		for(var i = 0; i < bindings.length; i++) {
			$(bindings[i].selector, dom).each(function() {
				var params = [];
				var $el = $(this);
				var data = $el.attr('data');
				var url;
				params.push("src=" + that.model.packageDocument.resolveUri(data));
				params.push('type=' + bindings[i].media_type);
				url = bindings[i].url + "?" + params.join('&');
				var content = $(that.bindingTemplate({}));
				// must set src attr separately
				content.attr('src', url);
				$el.html(content);
			});
		}
	},

	addStyleSheets: function(bookDom) {
		var link; var href; var $link; var links;

		// first remove anything we already put up there
		$('.readium-dynamic-sh').remove();

		// TODO USE jQUERY for this (bug reported and fixed in master)
		links = bookDom.getElementsByTagName("link");

		for (var j = 0; j < links.length; j++) {
			link = links[j];
			if(typeof link.rel === "string" && link.rel.toUpperCase() === "STYLESHEET") {
				$link = $(link);
				$link.addClass('readium-dynamic-sh');
				$('head').prepend($link);
			}
		}
	},

	setUpMode: function() {
		var two_up = this.model.get("two_up");
		this.$el.toggleClass("two-up", two_up);
		this.$('#spine-divider').toggle(two_up);
	},

	// this doesn't seem to be working...
	events: {

		"click #page-margin": function(e) {
			this.trigger("toggle_ui");
		},

		"click #readium-content-container a": function(e) {
			this.linkClickHandler(e);
		}
	},

	isPageVisible: function(pageNum, currentPages) {

		return currentPages.indexOf(pageNum) !== -1;

	},

	changePage: function() {
		var that = this;
		var currentPage = this.model.get("current_page");
		var two_up = this.model.get("two_up")
		this.$(".page-wrap").each(function(index) {
			if(!two_up) {
				index += 1;
			}
			$(this).toggleClass("hidden-page", !that.isPageVisible(index, currentPage));
		});
	},

	appendContent: function(content) {
		alert('not implemented yet')
	},

	replaceContent: function(content) {
		this.$('#readium-content-container').html(content + "

");
		_contentEnd = $('#content-end');
	},

	toggleTwoUp: function() {

		//this.render();
	},

	setFontSize: function() {
		var size = this.model.get("font_size") / 10;
		$('#readium-content-container').css("font-size", size + "em");
		this.renderPages();
	},

});

Readium.Views.ScrollingPaginationView = Readium.Views.PaginationViewBase.extend({

	initialize: function() {
		// call the super ctor
		Readium.Views.PaginationViewBase.prototype.initialize.call(this);
		this.page_template = _.template( $('#scrolling-page-template').html() );
		this.model.on("change:current_section_url", this.render, this);
	},

	render: function() {
		var that = this;
		var uri = this.model.get("current_section_url");
		this.$('#container').html( this.page_template({uri: uri}) );
		this.$('.content-sandbox').on("load", function(e) {
			// not sure why, on("load", this.applyBindings, this) was not working
			that.applyBindings( $(e.srcElement).contents() );
		});
		return this;
	},

});

Readium.Views.ReflowablePaginationView = Readium.Views.PaginationViewBase.extend({

	initialize: function() {
		// call the super ctor
		Readium.Views.PaginationViewBase.prototype.initialize.call(this);

		this.page_template = _.template( $('#reflowing-page-template').html() );

		this.model.on("repagination_event", this.renderPages, this);
		this.model.on("change:current_content", this.render, this);
		this.model.on("change:two_up", this.renderPages, this);

	},

	render: function() {
		var htmlText = this.model.get("current_content");
		var parser = new window.DOMParser();
		var dom = parser.parseFromString( htmlText, 'text/xml' );
		this.addStyleSheets( dom );
		this.replaceContent( dom.body.innerHTML );
		// need to add one page for calculation to work (TODO: this can be fixed)
		this.$('#container').html( this.page_template({page_num: 1, empty: false}) );

		// we need to let the stylesheets be parsed (TODO use an event?)
		var that = this;
		setTimeout(function() {
			that.renderPages();
			that.toggleTwoUp();
			if(that.renderToLastPage) {
				that.model.goToLastPage();
			}
			else {
				that.model.goToFirstPage();
			}
		}, 3);
		return this;
	},

	guessPageNumber: function() {

		var quotient;
		quotient = $('#readium-content-container').height() / $('.page').first().height();
		if(quotient < 1) {
			return 1;
		}
		return Math.ceil(quotient);
	},

	needsMorePages: function() {
		// this should be part of the regions API but last I checked it wasn't there yet
		// for now we just check if content bottom is lower than page bottom
		var getBotHelper = function( $elem ) {
			return $elem.outerHeight(true) + $elem.offset().top;
		};

		var pageEnd = getBotHelper( this.$('.page').last() );
		var contEnd = getBotHelper( $('#content-end') );
		return pageEnd < contEnd;
		return false;
	},

	renderPages: function() {
		var i; var html; var num;
		var two_up = this.model.get("two_up");
		num = this.guessPageNumber();
		html = "";

		this.setUpMode();

		// start with an empty page in two up mode
		if(two_up) {
			html += this.page_template({page_num: 0, empty: true})
		}

		// added the guessed number of pages
		for( i = 1; i <= num; i++) {
			html += this.page_template({page_num: i, empty: false});
		}
		this.$('#container').html( html );

		// now touch it up
		while( this.needsMorePages() ) {
			this.$('#container').append( this.page_template({page_num: i, empty: false}) )
			i += 1;
		}

		if(two_up && num % 2 === 0) {
			num += 1;
			this.$('#container').append( this.page_template({page_num: i, empty: false}) );
		}

		this.model.changPageNumber(num);

		// dunno that I should be calling this explicitly
		this.changePage();
	},

	// decide if should open in two up based on viewport
	// width
	/*
	var shouldOpenInTwoUp = function() {
		var width = document.documentElement.clientWidth;
		var height = document.documentElement.clientHeight;
		return width > 300 && width / height > 1.3;
	}
*/
});

Readium.Views.FixedPaginationView = Readium.Views.PaginationViewBase.extend({

	initialize: function() {
		// call the super ctor
		this.page_template = _.template( $('#fixed-page-template').html() );
		this.empty_template = _.template( $('#empty-fixed-page-template').html() );
		Readium.Views.PaginationViewBase.prototype.initialize.call(this);
		this.model.on("first_render_ready", this.render, this);
		this.model.on("change:two_up", this.setUpMode, this);
		this.$el.zoomAndScale(); //<= this was a little buggy last I checked but it is a super cool feature
	},

	render: function() {
		// add all the pages
		var sections = this.model.getAllSections();
		$('body').addClass('apple-fixed-layout');
		this.setUpMode();
		this.$el.width(this.model.get("meta_width") * 2);
		this.$el.height(this.model.get("meta_height"));

		for(var i = 0; i < sections.length; i++) {
			sections[i].page_num = i + 1;
			this.$('#container').append(this.page_template(sections[i]));
		}
		this.model.changPageNumber(i);
		return this.renderPages();
	},

	setUpMode: function() {
		// call super
		Readium.Views.PaginationViewBase.prototype.setUpMode.call(this);
		var two_up = this.model.get("two_up");
		var height = this.model.get("meta_height");
		var width = this.model.get("meta_width");
		if(two_up) {
			var content = this.empty_template({page_num: 0, height: height, width: width});
			//this.$('#container').prepend(content);
		} else {
			$('#page-0').remove();
		}
	},

	renderPages: function() {

		// lost myself in the complexity here but this seems right
		this.changePage();
		return this;
	},

	changePage: function() {
		var that = this;
		var currentPage = this.model.get("current_page");
		var two_up = this.model.get("two_up")
		this.$(".fixed-page-wrap").each(function(index) {
			$(this).toggle(that.isPageVisible(index + 1, currentPage));
		});
	},

	events: {
		'click #page-wrap a': function(e) {
			this.linkClickHandler(e)
		}
	}
});

		<commit_msg>bindings activated for apple fixed layout<commit_after>if( !window.Readium ) {
	window.Readium = {
		Models: {},
		Collections: {},
		Views: {},
		Routers: {},
		Utils: {}
	};
}

Readium.Views.PaginationViewBase = Backbone.View.extend({

	el: "#readium-book-view-el",
	renderToLastPage: false,

	initialize: function(options) {
		this.model.on("change:current_page", this.changePage, this);
		this.model.on("change:font_size", this.setFontSize, this);
		this.bindingTemplate = _.template( $('#binding-template').html() );

		// TODO: should I break layers here or pass through?
		this.model.packageDocument.on("increased:spine_position", function() {
			this.renderToLastPage = false;
		}, this);
		this.model.packageDocument.on("decreased:spine_position", function() {
			this.renderToLastPage = true;
		}, this);
	},

	linkClickHandler: function(e) {
		e.preventDefault();

		var href = e.srcElement.attributes["href"].value;
		if(href.match(/^http(s)?:/)) {
			chrome.tabs.create({"url": href});
		} else {
			this.model.goToHref(href);
		}
	},

	getBindings: function() {
		var packDoc = this.model.packageDocument;
		var bindings = packDoc.get('bindings');
		return bindings.map(function(binding) {
			binding.selector = 'object[type="' + binding.media_type + '"]';
			binding.url = packDoc.getManifestItemById(binding.handler).get('href');
			binding.url = packDoc.resolveUri(binding.url);
			return binding;
		})
	},

	applyBindings: function(dom) {
		var that = this;
		var bindings = this.getBindings();
		var i = 0;
		for(var i = 0; i < bindings.length; i++) {
			$(bindings[i].selector, dom).each(function() {
				var params = [];
				var $el = $(this);
				var data = $el.attr('data');
				var url;
				params.push("src=" + that.model.packageDocument.resolveUri(data));
				params.push('type=' + bindings[i].media_type);
				url = bindings[i].url + "?" + params.join('&');
				var content = $(that.bindingTemplate({}));
				// must set src attr separately
				content.attr('src', url);
				$el.html(content);
			});
		}
	},

	addStyleSheets: function(bookDom) {
		var link; var href; var $link; var links;

		// first remove anything we already put up there
		$('.readium-dynamic-sh').remove();

		// TODO USE jQUERY for this (bug reported and fixed in master)
		links = bookDom.getElementsByTagName("link");

		for (var j = 0; j < links.length; j++) {
			link = links[j];
			if(typeof link.rel === "string" && link.rel.toUpperCase() === "STYLESHEET") {
				$link = $(link);
				$link.addClass('readium-dynamic-sh');
				$('head').prepend($link);
			}
		}
	},

	setUpMode: function() {
		var two_up = this.model.get("two_up");
		this.$el.toggleClass("two-up", two_up);
		this.$('#spine-divider').toggle(two_up);
	},

	// this doesn't seem to be working...
	events: {

		"click #page-margin": function(e) {
			this.trigger("toggle_ui");
		},

		"click #readium-content-container a": function(e) {
			this.linkClickHandler(e);
		}
	},

	isPageVisible: function(pageNum, currentPages) {

		return currentPages.indexOf(pageNum) !== -1;

	},

	changePage: function() {
		var that = this;
		var currentPage = this.model.get("current_page");
		var two_up = this.model.get("two_up")
		this.$(".page-wrap").each(function(index) {
			if(!two_up) {
				index += 1;
			}
			$(this).toggleClass("hidden-page", !that.isPageVisible(index, currentPage));
		});
	},

	appendContent: function(content) {
		alert('not implemented yet')
	},

	replaceContent: function(content) {
		this.$('#readium-content-container').html(content + "

");
		_contentEnd = $('#content-end');
	},

	toggleTwoUp: function() {

		//this.render();
	},

	setFontSize: function() {
		var size = this.model.get("font_size") / 10;
		$('#readium-content-container').css("font-size", size + "em");
		this.renderPages();
	},

});

Readium.Views.ScrollingPaginationView = Readium.Views.PaginationViewBase.extend({

	initialize: function() {
		// call the super ctor
		Readium.Views.PaginationViewBase.prototype.initialize.call(this);
		this.page_template = _.template( $('#scrolling-page-template').html() );
		this.model.on("change:current_section_url", this.render, this);
	},

	render: function() {
		var that = this;
		var uri = this.model.get("current_section_url");
		this.$('#container').html( this.page_template({uri: uri}) );
		this.$('.content-sandbox').on("load", function(e) {
			// not sure why, on("load", this.applyBindings, this) was not working
			that.applyBindings( $(e.srcElement).contents() );
		});
		return this;
	},

});

Readium.Views.ReflowablePaginationView = Readium.Views.PaginationViewBase.extend({

	initialize: function() {
		// call the super ctor
		Readium.Views.PaginationViewBase.prototype.initialize.call(this);

		this.page_template = _.template( $('#reflowing-page-template').html() );

		this.model.on("repagination_event", this.renderPages, this);
		this.model.on("change:current_content", this.render, this);
		this.model.on("change:two_up", this.renderPages, this);

	},

	render: function() {
		var htmlText = this.model.get("current_content");
		var parser = new window.DOMParser();
		var dom = parser.parseFromString( htmlText, 'text/xml' );
		this.addStyleSheets( dom );
		this.replaceContent( dom.body.innerHTML );
		// need to add one page for calculation to work (TODO: this can be fixed)
		this.$('#container').html( this.page_template({page_num: 1, empty: false}) );

		// we need to let the stylesheets be parsed (TODO use an event?)
		var that = this;
		setTimeout(function() {
			that.renderPages();
			that.toggleTwoUp();
			if(that.renderToLastPage) {
				that.model.goToLastPage();
			}
			else {
				that.model.goToFirstPage();
			}
		}, 3);
		return this;
	},

	guessPageNumber: function() {

		var quotient;
		quotient = $('#readium-content-container').height() / $('.page').first().height();
		if(quotient < 1) {
			return 1;
		}
		return Math.ceil(quotient);
	},

	needsMorePages: function() {
		// this should be part of the regions API but last I checked it wasn't there yet
		// for now we just check if content bottom is lower than page bottom
		var getBotHelper = function( $elem ) {
			return $elem.outerHeight(true) + $elem.offset().top;
		};

		var pageEnd = getBotHelper( this.$('.page').last() );
		var contEnd = getBotHelper( $('#content-end') );
		return pageEnd < contEnd;
		return false;
	},

	renderPages: function() {
		var i; var html; var num;
		var two_up = this.model.get("two_up");
		num = this.guessPageNumber();
		html = "";

		this.setUpMode();

		// start with an empty page in two up mode
		if(two_up) {
			html += this.page_template({page_num: 0, empty: true})
		}

		// added the guessed number of pages
		for( i = 1; i <= num; i++) {
			html += this.page_template({page_num: i, empty: false});
		}
		this.$('#container').html( html );

		// now touch it up
		while( this.needsMorePages() ) {
			this.$('#container').append( this.page_template({page_num: i, empty: false}) )
			i += 1;
		}

		if(two_up && num % 2 === 0) {
			num += 1;
			this.$('#container').append( this.page_template({page_num: i, empty: false}) );
		}

		this.model.changPageNumber(num);

		// dunno that I should be calling this explicitly
		this.changePage();
	},

	// decide if should open in two up based on viewport
	// width
	/*
	var shouldOpenInTwoUp = function() {
		var width = document.documentElement.clientWidth;
		var height = document.documentElement.clientHeight;
		return width > 300 && width / height > 1.3;
	}
*/
});

Readium.Views.FixedPaginationView = Readium.Views.PaginationViewBase.extend({

	initialize: function() {
		// call the super ctor
		this.page_template = _.template( $('#fixed-page-template').html() );
		this.empty_template = _.template( $('#empty-fixed-page-template').html() );
		Readium.Views.PaginationViewBase.prototype.initialize.call(this);
		this.model.on("first_render_ready", this.render, this);
		this.model.on("change:two_up", this.setUpMode, this);
		this.$el.zoomAndScale(); //<= this was a little buggy last I checked but it is a super cool feature
	},

	render: function() {
		// add all the pages
		var sections = this.model.getAllSections();
		$('body').addClass('apple-fixed-layout');
		this.setUpMode();
		this.$el.width(this.model.get("meta_width") * 2);
		this.$el.height(this.model.get("meta_height"));

		for(var i = 0; i < sections.length; i++) {
			sections[i].page_num = i + 1;
			this.$('#container').append(this.page_template(sections[i]));
		}
		var that = this;
		this.$('.content-sandbox').on("load", function(e) {
			// not sure why, on("load", this.applyBindings, this) was not working
			that.applyBindings( $(e.srcElement).contents() );
		});
		this.model.changPageNumber(i);
		return this.renderPages();
	},

	setUpMode: function() {
		// call super
		Readium.Views.PaginationViewBase.prototype.setUpMode.call(this);
		var two_up = this.model.get("two_up");
		var height = this.model.get("meta_height");
		var width = this.model.get("meta_width");
		if(two_up) {
			var content = this.empty_template({page_num: 0, height: height, width: width});
			//this.$('#container').prepend(content);
		} else {
			$('#page-0').remove();
		}
	},

	renderPages: function() {

		// lost myself in the complexity here but this seems right
		this.changePage();
		return this;
	},

	changePage: function() {
		var that = this;
		var currentPage = this.model.get("current_page");
		var two_up = this.model.get("two_up")
		this.$(".fixed-page-wrap").each(function(index) {
			$(this).toggle(that.isPageVisible(index + 1, currentPage));
		});
	},

	events: {
		'click #page-wrap a': function(e) {
			this.linkClickHandler(e)
		}
	}
});

		<|endoftext|>


<commit_before>/*

    Name: angular-gsapify-router
    Description: Angular UI-Router animation directive allowing configuration of state transitions using [GSAP](http://www.greensock.com/gsap-js/)
    Author: jameshomer85@gmail.com
    Licence: MIT
    Usage: http://github.com/homerjam/angular-gsapify-router

*/
(function() {
    'use strict';

    angular.module('hj.gsapifyRouter', ['ui.router', 'ngAnimate'])

    .constant('TweenMax', TweenMax)

    .provider('gsapifyRouter', function() {
        var self = this;

        self.initialTransitionEnabled = false;

        self.transitions = {};

        self.transitions.above = {
            duration: 1,
            ease: 'Quart.easeInOut',
            css: {
                y: '-100%'
            }
        };

        self.transitions.below = {
            duration: 1,
            ease: 'Quart.easeInOut',
            css: {
                y: '100%'
            }
        };

        self.transitions.left = {
            duration: 1,
            ease: 'Quint.easeInOut',
            css: {
                x: '-100%'
            }
        };

        self.transitions.right = {
            duration: 1,
            ease: 'Quint.easeInOut',
            css: {
                x: '100%'
            }
        };

        self.transitions.fade = {
            duration: 0.5,
            css: {
                opacity: 0
            }
        };

        self.transitions.fadeDelayed = {
            duration: 0.5,
            delay: 0.5,
            css: {
                opacity: 0
            }
        };

        self.transitions.none = {
            duration: 0,
            css: {}
        };

        self.defaults = {
            enter: 'none',
            leave: 'none'
        };

        self.transition = function(transitionName, transitionOptions) {
            self.transitions[transitionName] = transitionOptions;
        };

        self.$get = ['$rootScope', '$state', '$document', '$injector', '$timeout', '$q', '$log', 'TweenMax',
            function($rootScope, $state, $document, $injector, $timeout, $q, $log, TweenMax) {
                $state.history = [];

                $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
                    $state.previous = fromState;
                    $state.previousParams = fromParams;

                    $state.history.push({
                        name: fromState.name,
                        params: fromParams
                    });
                });

                var getOpts = function(state, view, enterLeave, inOut) {
                    var opts = {
                        transition: self.defaults[inOut === 'in' ? 'enter' : 'leave'],
                        priority: 0
                    };

                    if (state.data) {
                        if (state.data['gsapifyRouter.' + view] && state.data['gsapifyRouter.' + view][enterLeave]) {
                            if (state.data['gsapifyRouter.' + view][enterLeave][inOut]) {
                                switch (Object.prototype.toString.call(state.data['gsapifyRouter.' + view][enterLeave][inOut])) {
                                    case '[object Array]':
                                    case '[object Function]':
                                        opts = $injector.invoke(state.data['gsapifyRouter.' + view][enterLeave][inOut]);
                                        break;
                                    case '[object Object]':
                                        opts = angular.extend(opts, state.data['gsapifyRouter.' + view][enterLeave][inOut]);
                                        Object.keys(opts).forEach(function(key) {
                                            switch (Object.prototype.toString.call(opts[key])) {
                                                case '[object Array]':
                                                case '[object Function]':
                                                    opts[key] = $injector.invoke(opts[key]);
                                                    break;
                                            }
                                        });
                                        break;
                                    case '[object String]':
                                        opts.transition = state.data['gsapifyRouter.' + view][enterLeave][inOut];
                                        break;
                                }
                            }
                        }
                    }

                    return opts;
                };

                var getTransition = function(transition) {
                    var result;
                    switch (Object.prototype.toString.call(transition)) {
                        case '[object Object]':
                            result = transition;
                            break;
                        case '[object String]':
                            result = self.transitions[transition];
                            break;
                    }
                    return result;
                };

                var enter = function(element) {
                    var deferred = $q.defer();

                    element.css('visibility', 'hidden');

                    element.addClass('gsapify-router-in-setup');

                    var view = element.attr('ui-view'),

                        current = $state.current,
                        previous = $state.previous,

                        currentOpts = getOpts(current, view, 'enter', 'in'),
                        previousOpts = getOpts(previous, view, 'leave', 'in'),

                        from;

                    if (previousOpts.priority > currentOpts.priority) {
                        from = getTransition(previousOpts.transition);

                        if (!from) {
                            $log.error("gsapifyRouter: Invalid transition '" + previousOpts.transition + "'");
                        }

                    } else {
                        from = getTransition(currentOpts.transition);

                        if (!from) {
                            $log.error("gsapifyRouter: Invalid transition '" + currentOpts.transition + "'");
                        }
                    }

                    var duration = $state.previous.name === '' && !self.initialTransitionEnabled ? 0 : from.duration,
                        vars = angular.copy(from);

                    vars.onStart = function() {
                        element.css('visibility', 'visible');

                        element.removeClass('gsapify-router-in-setup');
                        element.addClass('gsapify-router-in');
                    };

                    vars.onComplete = function() {
                        element.addClass('gsapify-router-in-end');

                        deferred.resolve();
                    };

                    if (!vars.css || Object.keys(vars.css).length === 0 || duration === 0) {
                        vars.onStart();
                    }

                    TweenMax.from(element, duration, vars);

                    return deferred.promise;
                };

                var leave = function(element) {
                    var deferred = $q.defer();

                    element.removeClass('gsapify-router-in gsapify-router-in-end');
                    element.addClass('gsapify-router-out-setup');

                    var view = element.attr('ui-view'),

                        current = $state.current,
                        previous = $state.previous,

                        previousOpts = getOpts(previous, view, 'leave', 'out'),
                        currentOpts = getOpts(current, view, 'enter', 'out'),

                        to;

                    if (currentOpts.priority > previousOpts.priority) {
                        to = getTransition(currentOpts.transition);

                        if (!to) {
                            $log.error("gsapifyRouter: Invalid transition '" + currentOpts.transition + "'");
                        }

                    } else {
                        to = getTransition(previousOpts.transition);

                        if (!to) {
                            $log.error("gsapifyRouter: Invalid transition '" + previousOpts.transition + "'");
                        }
                    }

                    var duration = to.duration,
                        vars = angular.copy(to);

                    vars.onStart = function() {
                        element.removeClass('gsapify-router-out-setup');
                        element.addClass('gsapify-router-out');
                    };

                    vars.onComplete = function() {
                        element.remove();

                        deferred.resolve();
                    };

                    TweenMax.to(element, duration, vars);

                    return deferred.promise;
                };

                return {
                    enter: enter,
                    leave: leave,
                    transitions: self.transitions,
                    defaults: self.defaults
                };
            }
        ];
    })

    .directive('gsapifyRouter', ['$state',
        function($state) {
            return {
                priority: 0,
                restrict: 'C',
                link: function($scope, $element, $attr) {
                    $attr.$set('data-state', $state.current.name);
                }
            };
        }
    ])

    .animation('.gsapify-router', ['$rootScope', 'gsapifyRouter',
        function($rootScope, gsapifyRouter) {
            return {
                enter: function(element, done) {
                    $rootScope.$broadcast('gsapifyRouter:enterStart', element);

                    gsapifyRouter.enter(element).then(function() {
                        $rootScope.$broadcast('gsapifyRouter:enterSuccess', element);

                        done();
                    });

                    return function(cancelled) {
                        if (cancelled) {
                            element.remove();
                        }
                    };
                },
                leave: function(element, done) {
                    $rootScope.$broadcast('gsapifyRouter:leaveStart', element);

                    gsapifyRouter.leave(element).then(function() {
                        $rootScope.$broadcast('gsapifyRouter:leaveSuccess', element);

                        done();
                    });
                }
            };
        }
    ]);

})();
<commit_msg>Added default value for $state.previous<commit_after>/*

    Name: angular-gsapify-router
    Description: Angular UI-Router animation directive allowing configuration of state transitions using [GSAP](http://www.greensock.com/gsap-js/)
    Author: jameshomer85@gmail.com
    Licence: MIT
    Usage: http://github.com/homerjam/angular-gsapify-router

*/
(function() {
    'use strict';

    angular.module('hj.gsapifyRouter', ['ui.router', 'ngAnimate'])

    .constant('TweenMax', TweenMax)

    .provider('gsapifyRouter', function() {
        var self = this;

        self.initialTransitionEnabled = false;

        self.transitions = {};

        self.transitions.above = {
            duration: 1,
            ease: 'Quart.easeInOut',
            css: {
                y: '-100%'
            }
        };

        self.transitions.below = {
            duration: 1,
            ease: 'Quart.easeInOut',
            css: {
                y: '100%'
            }
        };

        self.transitions.left = {
            duration: 1,
            ease: 'Quint.easeInOut',
            css: {
                x: '-100%'
            }
        };

        self.transitions.right = {
            duration: 1,
            ease: 'Quint.easeInOut',
            css: {
                x: '100%'
            }
        };

        self.transitions.fade = {
            duration: 0.5,
            css: {
                opacity: 0
            }
        };

        self.transitions.fadeDelayed = {
            duration: 0.5,
            delay: 0.5,
            css: {
                opacity: 0
            }
        };

        self.transitions.none = {
            duration: 0,
            css: {}
        };

        self.defaults = {
            enter: 'none',
            leave: 'none'
        };

        self.transition = function(transitionName, transitionOptions) {
            self.transitions[transitionName] = transitionOptions;
        };

        self.$get = ['$rootScope', '$state', '$document', '$injector', '$timeout', '$q', '$log', 'TweenMax',
            function($rootScope, $state, $document, $injector, $timeout, $q, $log, TweenMax) {
                $state.history = [];
                $state.previous = {};

                $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
                    $state.previous = fromState;
                    $state.previousParams = fromParams;

                    $state.history.push({
                        name: fromState.name,
                        params: fromParams
                    });
                });

                var getOpts = function(state, view, enterLeave, inOut) {
                    var opts = {
                        transition: self.defaults[inOut === 'in' ? 'enter' : 'leave'],
                        priority: 0
                    };

                    if (state.data) {
                        if (state.data['gsapifyRouter.' + view] && state.data['gsapifyRouter.' + view][enterLeave]) {
                            if (state.data['gsapifyRouter.' + view][enterLeave][inOut]) {
                                switch (Object.prototype.toString.call(state.data['gsapifyRouter.' + view][enterLeave][inOut])) {
                                    case '[object Array]':
                                    case '[object Function]':
                                        opts = $injector.invoke(state.data['gsapifyRouter.' + view][enterLeave][inOut]);
                                        break;
                                    case '[object Object]':
                                        opts = angular.extend(opts, state.data['gsapifyRouter.' + view][enterLeave][inOut]);
                                        Object.keys(opts).forEach(function(key) {
                                            switch (Object.prototype.toString.call(opts[key])) {
                                                case '[object Array]':
                                                case '[object Function]':
                                                    opts[key] = $injector.invoke(opts[key]);
                                                    break;
                                            }
                                        });
                                        break;
                                    case '[object String]':
                                        opts.transition = state.data['gsapifyRouter.' + view][enterLeave][inOut];
                                        break;
                                }
                            }
                        }
                    }

                    return opts;
                };

                var getTransition = function(transition) {
                    var result;
                    switch (Object.prototype.toString.call(transition)) {
                        case '[object Object]':
                            result = transition;
                            break;
                        case '[object String]':
                            result = self.transitions[transition];
                            break;
                    }
                    return result;
                };

                var enter = function(element) {
                    var deferred = $q.defer();

                    element.css('visibility', 'hidden');

                    element.addClass('gsapify-router-in-setup');

                    var view = element.attr('ui-view'),

                        current = $state.current,
                        previous = $state.previous,

                        currentOpts = getOpts(current, view, 'enter', 'in'),
                        previousOpts = getOpts(previous, view, 'leave', 'in'),

                        from;

                    if (previousOpts.priority > currentOpts.priority) {
                        from = getTransition(previousOpts.transition);

                        if (!from) {
                            $log.error("gsapifyRouter: Invalid transition '" + previousOpts.transition + "'");
                        }

                    } else {
                        from = getTransition(currentOpts.transition);

                        if (!from) {
                            $log.error("gsapifyRouter: Invalid transition '" + currentOpts.transition + "'");
                        }
                    }

                    var duration = $state.previous.name === '' && !self.initialTransitionEnabled ? 0 : from.duration,
                        vars = angular.copy(from);

                    vars.onStart = function() {
                        element.css('visibility', 'visible');

                        element.removeClass('gsapify-router-in-setup');
                        element.addClass('gsapify-router-in');
                    };

                    vars.onComplete = function() {
                        element.addClass('gsapify-router-in-end');

                        deferred.resolve();
                    };

                    if (!vars.css || Object.keys(vars.css).length === 0 || duration === 0) {
                        vars.onStart();
                    }

                    TweenMax.from(element, duration, vars);

                    return deferred.promise;
                };

                var leave = function(element) {
                    var deferred = $q.defer();

                    element.removeClass('gsapify-router-in gsapify-router-in-end');
                    element.addClass('gsapify-router-out-setup');

                    var view = element.attr('ui-view'),

                        current = $state.current,
                        previous = $state.previous,

                        previousOpts = getOpts(previous, view, 'leave', 'out'),
                        currentOpts = getOpts(current, view, 'enter', 'out'),

                        to;

                    if (currentOpts.priority > previousOpts.priority) {
                        to = getTransition(currentOpts.transition);

                        if (!to) {
                            $log.error("gsapifyRouter: Invalid transition '" + currentOpts.transition + "'");
                        }

                    } else {
                        to = getTransition(previousOpts.transition);

                        if (!to) {
                            $log.error("gsapifyRouter: Invalid transition '" + previousOpts.transition + "'");
                        }
                    }

                    var duration = to.duration,
                        vars = angular.copy(to);

                    vars.onStart = function() {
                        element.removeClass('gsapify-router-out-setup');
                        element.addClass('gsapify-router-out');
                    };

                    vars.onComplete = function() {
                        element.remove();

                        deferred.resolve();
                    };

                    TweenMax.to(element, duration, vars);

                    return deferred.promise;
                };

                return {
                    enter: enter,
                    leave: leave,
                    transitions: self.transitions,
                    defaults: self.defaults
                };
            }
        ];
    })

    .directive('gsapifyRouter', ['$state',
        function($state) {
            return {
                priority: 0,
                restrict: 'C',
                link: function($scope, $element, $attr) {
                    $attr.$set('data-state', $state.current.name);
                }
            };
        }
    ])

    .animation('.gsapify-router', ['$rootScope', 'gsapifyRouter',
        function($rootScope, gsapifyRouter) {
            return {
                enter: function(element, done) {
                    $rootScope.$broadcast('gsapifyRouter:enterStart', element);

                    gsapifyRouter.enter(element).then(function() {
                        $rootScope.$broadcast('gsapifyRouter:enterSuccess', element);

                        done();
                    });

                    return function(cancelled) {
                        if (cancelled) {
                            element.remove();
                        }
                    };
                },
                leave: function(element, done) {
                    $rootScope.$broadcast('gsapifyRouter:leaveStart', element);

                    gsapifyRouter.leave(element).then(function() {
                        $rootScope.$broadcast('gsapifyRouter:leaveSuccess', element);

                        done();
                    });
                }
            };
        }
    ]);

})();
<|endoftext|>