<commit_before>/*global define $ requestAnimationFrame*/

define(function (require) {

	var MovieClip,
		Utils = require('app/utils');

	require('tweenmax');

	MovieClip = function (root, el, commandTimeline, resourceManager, transform) {
		var i,
			transformMat;

		this.root = root;
    	this.el = el;
		this.m_transform = transform;

		this.m_timeline = commandTimeline;
		this.m_currentFrameNo = 0;
		this.m_frameCount = this.m_timeline.Frame.length;
		this.m_children = [];

		if(this.m_transform !== undefined)
		{
			//Apply the transformation on the parent MC
			var transformData =  this.m_transform;
			var transformArray = transformData.split(",");
			transformMat = new Snap.Matrix(transformArray[0],transformArray[1],transformArray[2],transformArray[3],transformArray[4],transformArray[5]);
			this.el.transform(transformMat);
		}

	}

	MovieClip.prototype.play = function (resourceManager) {
		var children = this.m_children;
    	var commandList = [];

		for(var i=0; i<children.length; ++i)
		{
			children[i].play(resourceManager);
		}

		// Handle Looping
		if(this.m_currentFrameNo == this.m_frameCount) {
			this.m_currentFrameNo = 0;

	    	var frame = this.m_timeline.Frame[this.m_currentFrameNo];

	    	if (!frame) {
	    		return;
	    	}

	    	//Get the commands for the first frame
	    	var commands = frame.Command;

	    	// Iterate through all the elements in the display list (maintained by CreateJS) and
		    // check if same instance exists in the first frame

		    var children = this.root.selectAll('*');

		    for (var i = 0; i < children.length; i += 1) {
		    	if (children[i].parent().id == this.el.id) {

		    		var found = false;
		        	var elementId = children[i].attr('token');

		        	for (var c = 0; c < commands.length; ++c) {
			            var cmdData = commands[c];
			            var type = cmdData.cmdType;

			            if (type == "Place") {
			                if (parseInt(elementId) == parseInt(cmdData.objectId)) {
			                    found = true;
			                    break;
			                }
			            }
			        }

			        if (found == false) {
			            command = new RemoveObjectCommand(elementId);
			            commandList.push(command);
			        }

		    	}
		    }
		}

		//run commands
		var frame = this.m_timeline.Frame[this.m_currentFrameNo];
	  	if (!frame) {
	  		return;
    	}
		var commands = frame.Command;

		for(var c=0; c<commands.length; ++c)
		{
			var cmdData = commands[c];
			var type = cmdData.cmdType;
			var command = undefined;

			switch(type)
			{
				case "Place":

					var found = false;
					var items = this.root.selectAll('[token="' + cmdData.objectId + '"]');
					for (var i = 0; i < items.length; i += 1) {
						if (items[i].parent() == this.el || items[i].parent().type == 'mask') {
							found = true;
						}
					}

			        if (!found) {
			            command = new PlaceObjectCommand(cmdData.charid, cmdData.objectId, cmdData.placeAfter, cmdData.transformMatrix);
			            commandList.push(command);
			        } else {
	                    // It is already present (Possible for looping case)
			            command = new MoveObjectCommand(cmdData.objectId, cmdData.transformMatrix);
			            commandList.push(command);
			            command = new UpdateObjectCommand(cmdData.objectId, cmdData.placeAfter);
			            commandList.push(command);
			        }

				break;
				case "Move":
					command = new MoveObjectCommand(cmdData.objectId, cmdData.transformMatrix);
					commandList.push(command);
				break;
				case "Remove":
					command = new RemoveObjectCommand(cmdData.objectId);
					commandList.push(command);
				break;
				case "UpdateZOrder":
					command = new UpdateObjectCommand(cmdData.objectId , cmdData.placeAfter);
					commandList.push(command);
				break;
				case "UpdateVisibility":
					command = new UpdateVisibilityCommand(cmdData.objectId , cmdData.visibility);
					commandList.push(command);
				break;
				case "UpdateColorTransform":
					command = new UpdateColorTransformCommand(cmdData.objectId , cmdData.colorMatrix);
					commandList.push(command);
				break;
				case "UpdateMask":
					command = new UpdateMaskCommand(cmdData.objectId , cmdData.maskTill);
					commandList.push(command);
				break;
			}

		}

		for (var i = 0; i < commandList.length ; i++)
		{
	  		//Execute it
			if (commandList[i] !== undefined) {
			     commandList[i].execute(this, resourceManager);
			}
		}

		//Increment the current frame no
		this.m_currentFrameNo++;

		this.cleanupUnusedDefs(); //perf hit
	}

	/**
	* clean up unused defs
	* TODO:: perf hit, optimize
	**/
	MovieClip.prototype.cleanupUnusedDefs = function () {
		var that = this,
			defs = this.el.selectAll('defs>*'),
			j,
			i,
			id,
			toRemove;

		for (j = 0; j < defs.length; j += 1) {
			id = defs[j].attr('id');

			if (!id) {
				continue;
			}

			url = "url('#" + id + "')";
			fill = that.el.select('[fill="' + url + '"]');
			mask = that.el.select('[mask="' + url + '"]');

			if (!fill && !mask) {
				console.log('remove');
				defs[j].remove();
			}
		}

		//clear all groups moved to defs
		defGroups = this.el.selectAll('defs>g');
		for (i = 0; i < defGroups.length; i += 1) {
			defGroups[i].remove();
		}

		//clear all unused masks
		masks = this.el.selectAll('defs>mask');
		for (i = 0; i < masks.length; i += 1) {
			if (!masks[i].attr('id')) {
				masks[i].remove();
			}
		}

	}

	//PlaceObjectCommand Class
	var PlaceObjectCommand = function(charID, objectID, placeAfter, transform)
	{
		this.m_charID = charID;
		this.m_objectID = objectID;
		this.m_placeAfter = placeAfter;
		this.m_transform = transform;
	}

	//Execute function for PlaceObjectCommand
	PlaceObjectCommand.prototype.execute = function(stage, resourceManager)
	{

		var shape = resourceManager.getShape(this.m_charID),
			bitmap = resourceManager.getBitmap(this.m_charID),
			text = resourceManager.getText(this.m_charID),
			parentMC = stage.el,
			root = stage.root,
			movieclipTimeline,
			movieclip,
			children,
			i,
			childMC,
			index;

		if(shape !== null && shape !== undefined)
		{
			Utils.CreateShape(root, parentMC, resourceManager, this.m_charID, this.m_objectID, this.m_placeAfter, this.m_transform);
		}
		else if(bitmap !== null && bitmap !== undefined)
		{
			Utils.CreateBitmap(root, parentMC, resourceManager, this.m_charID, this.m_objectID, this.m_placeAfter, this.m_transform);
		}
		else if (text !== null && text !== undefined)
		{
			Utils.CreateText(root, parentMC, resourceManager, this.m_charID, this.m_objectID, this.m_placeAfter, this.m_transform);
		}
		else
		{
			// Movie clip logic starts here
			movieclipTimeline = resourceManager.getMovieClip(this.m_charID);

			if(parentMC != undefined)
			{

				//Create a  MC
				childMC = parentMC.g();
				childMC.attr({class: 'movieclip', token: this.m_objectID});

				if(this.m_placeAfter != 0)
				{
					children = parentMC.selectAll('[token="' + this.m_placeAfter + '"]');
					for (i = 0; i < children.length; i += 1) {
						if (children[i].parent().id == parentMC.id) { //ensure child of current movie clip
							children[i].before(childMC);
							break;
						}
					}
				}
				else
				{
					parentMC.add(childMC);
				}

				//Create a corresponding TimelineAnimator
				if(movieclipTimeline)
				{
					movieclip = new MovieClip(root, childMC, movieclipTimeline, resourceManager, this.m_transform);
					stage.m_children.push(movieclip);
					movieclip.play(resourceManager);
				}
			}
		}

	}

	//MoveObjectCommand Class
	var MoveObjectCommand = function(objectID, transform)
	{
		this.m_objectID = objectID;
		//this.m_placeAfter = placeAfter;
		this.m_transform = transform;
	}

	//Execute function for PlaceObjectCommand
	MoveObjectCommand.prototype.execute = function(stage, resourceManager)
	{
		var parentMC,
			transform,
			transformArray,
			transformMat,
			children,
			i;

		parentMC = stage.el;
		transform =  this.m_transform;
		transformArray = transform.split(",");
		transformMat = new Snap.Matrix(transformArray[0],transformArray[1],transformArray[2],transformArray[3],transformArray[4],transformArray[5]);

		if(parentMC != undefined)
		{
			children = parentMC.selectAll('[token="' + this.m_objectID + '"]');

			for (i = 0; i < children.length; i += 1) {
				if (children[i].parent().id == parentMC.id) { //ensure child of current movie clip
					children[i].transform(transformMat);
				}
			}
		}

	}

	//UpdateObjectCommand Class
	var UpdateObjectCommand = function(objectID, placeAfter)
	{
		this.m_objectID = objectID;
		this.m_placeAfter = placeAfter;
	}

	//Execute function for UpdateObjectCommand
	UpdateObjectCommand.prototype.execute = function(timelineAnimator, resourceManager)
	{
		/*
		var parentMC = timelineAnimator.s;

		if(parentMC != undefined)
		{
			//Change the Z order of the targetMC
			var index;
			for(var indexz=0; indexz<parentMC.children.length; indexz++)
			{
				if(parentMC.children[indexz].id == parseInt(this.m_objectID))
				{
					var child = parentMC.getChildAt(indexz);
					if(this.m_placeAfter != 0)
					{
						for(var index=0; index<parentMC.children.length; index++)
						{
							if(parentMC.children[index].id == parseInt(this.m_placeAfter))
							{
								//child.addChildAt(childMC,index);
								parentMC.setChildIndex(child,index - 1)
								break;
							}
						}
					}
					break;
				}
			}
		}
		*/
	}

	//RemoveObjectCommand Class
	var RemoveObjectCommand = function(objectID)
	{
		this.m_objectID = objectID;
	}

	//Execute function for RemoveObjectCommand
	RemoveObjectCommand.prototype.execute = function(stage, resourceManager)
	{
		var parentMC = stage.el,
			child;

		if(parentMC != undefined)
		{
			children = parentMC.selectAll('[token="' + this.m_objectID + '"]');

			for (i = 0; i < children.length; i += 1) {
				if (children[i].parent() == parentMC) { //ensure child of current movie clip
					children[i].remove();
				}
			}
		}
	}

	//UpdateVisbilityCommand Class
	var UpdateVisibilityCommand = function(objectID,visibility)
	{
		this.m_objectID = objectID;
		this.m_visibilty = visibility;
	}

	//Execute function for UpdateVisbilityCommand
	UpdateVisibilityCommand.prototype.execute = function(timelineAnimator, resourceManager)
	{
		/*
		var parentMC = timelineAnimator.m_targetMC;
		if(parentMC != undefined)
		{
			//Remove the targetMC
			var index,visibleBool;
			for(var index=0; index<parentMC.children.length; index++)
			{
				if(parentMC.children[index].id == parseInt(this.m_objectID))
				{
					if(this.m_visibilty == "true")
						visibleBool = true;
						else
						visibleBool = false;

					parentMC.getChildAt(index).visible = visibleBool;

				}
			}
		}
		*/
	}

	var UpdateMaskCommand = function (objectID,maskTill)
	{
		this.m_objectID = objectID;
		this.m_maskTill = maskTill;
	}

	UpdateMaskCommand.prototype.execute = function (stage, resourceManager)
	{
		var parentMC = stage.el,
			root = stage.root,
			mask,
			maskContent,
			masked,
			i,
			def,
			clone;

		if(parentMC != undefined)
		{
			maskContent = parentMC.select('[token="' + this.m_objectID + '"]');
			mask = root.mask();
			mask.attr('mask-type', 'alpha');
			mask.append(maskContent);

			def = mask.toDefs();

			for (i = parseInt(this.m_maskTill); i > parseInt(this.m_objectID); i -= 1) {
				//clone = def.clone(); //issue with reusing def ??
				masked = parentMC.select('[token="' + i + '"]');
				masked.attr({mask: def});
			}

		}
	}

	var UpdateColorTransformCommand = function (objectID, colorMatrix)
	{
		this.m_objectID = objectID;
		this.m_colorMatrix = colorMatrix;
	}

	UpdateColorTransformCommand.prototype.execute = function (stage, resourceManager)
	{
		var parentMC = stage.el,
			object;

		if (parentMC != undefined) {
			object = parentMC.select('[token="' + this.m_objectID + '"]');
			matrix = this.m_colorMatrix.split(',', 7);
			object.attr({opacity: parseFloat(matrix[6])}); //currently only alpha
		}
	}

	return MovieClip;

});<commit_msg>remove comment<commit_after>/*global define $ requestAnimationFrame*/

define(function (require) {

	var MovieClip,
		Utils = require('app/utils');

	require('tweenmax');

	MovieClip = function (root, el, commandTimeline, resourceManager, transform) {
		var i,
			transformMat;

		this.root = root;
    	this.el = el;
		this.m_transform = transform;

		this.m_timeline = commandTimeline;
		this.m_currentFrameNo = 0;
		this.m_frameCount = this.m_timeline.Frame.length;
		this.m_children = [];

		if(this.m_transform !== undefined)
		{
			//Apply the transformation on the parent MC
			var transformData =  this.m_transform;
			var transformArray = transformData.split(",");
			transformMat = new Snap.Matrix(transformArray[0],transformArray[1],transformArray[2],transformArray[3],transformArray[4],transformArray[5]);
			this.el.transform(transformMat);
		}

	}

	MovieClip.prototype.play = function (resourceManager) {
		var children = this.m_children;
    	var commandList = [];

		for(var i=0; i<children.length; ++i)
		{
			children[i].play(resourceManager);
		}

		// Handle Looping
		if(this.m_currentFrameNo == this.m_frameCount) {
			this.m_currentFrameNo = 0;

	    	var frame = this.m_timeline.Frame[this.m_currentFrameNo];

	    	if (!frame) {
	    		return;
	    	}

	    	//Get the commands for the first frame
	    	var commands = frame.Command;

	    	// Iterate through all the elements in the display list (maintained by CreateJS) and
		    // check if same instance exists in the first frame

		    var children = this.root.selectAll('*');

		    for (var i = 0; i < children.length; i += 1) {
		    	if (children[i].parent().id == this.el.id) {

		    		var found = false;
		        	var elementId = children[i].attr('token');

		        	for (var c = 0; c < commands.length; ++c) {
			            var cmdData = commands[c];
			            var type = cmdData.cmdType;

			            if (type == "Place") {
			                if (parseInt(elementId) == parseInt(cmdData.objectId)) {
			                    found = true;
			                    break;
			                }
			            }
			        }

			        if (found == false) {
			            command = new RemoveObjectCommand(elementId);
			            commandList.push(command);
			        }

		    	}
		    }
		}

		//run commands
		var frame = this.m_timeline.Frame[this.m_currentFrameNo];
	  	if (!frame) {
	  		return;
    	}
		var commands = frame.Command;

		for(var c=0; c<commands.length; ++c)
		{
			var cmdData = commands[c];
			var type = cmdData.cmdType;
			var command = undefined;

			switch(type)
			{
				case "Place":

					var found = false;
					var items = this.root.selectAll('[token="' + cmdData.objectId + '"]');
					for (var i = 0; i < items.length; i += 1) {
						if (items[i].parent() == this.el || items[i].parent().type == 'mask') {
							found = true;
						}
					}

			        if (!found) {
			            command = new PlaceObjectCommand(cmdData.charid, cmdData.objectId, cmdData.placeAfter, cmdData.transformMatrix);
			            commandList.push(command);
			        } else {
	                    // It is already present (Possible for looping case)
			            command = new MoveObjectCommand(cmdData.objectId, cmdData.transformMatrix);
			            commandList.push(command);
			            command = new UpdateObjectCommand(cmdData.objectId, cmdData.placeAfter);
			            commandList.push(command);
			        }

				break;
				case "Move":
					command = new MoveObjectCommand(cmdData.objectId, cmdData.transformMatrix);
					commandList.push(command);
				break;
				case "Remove":
					command = new RemoveObjectCommand(cmdData.objectId);
					commandList.push(command);
				break;
				case "UpdateZOrder":
					command = new UpdateObjectCommand(cmdData.objectId , cmdData.placeAfter);
					commandList.push(command);
				break;
				case "UpdateVisibility":
					command = new UpdateVisibilityCommand(cmdData.objectId , cmdData.visibility);
					commandList.push(command);
				break;
				case "UpdateColorTransform":
					command = new UpdateColorTransformCommand(cmdData.objectId , cmdData.colorMatrix);
					commandList.push(command);
				break;
				case "UpdateMask":
					command = new UpdateMaskCommand(cmdData.objectId , cmdData.maskTill);
					commandList.push(command);
				break;
			}

		}

		for (var i = 0; i < commandList.length ; i++)
		{
	  		//Execute it
			if (commandList[i] !== undefined) {
			     commandList[i].execute(this, resourceManager);
			}
		}

		//Increment the current frame no
		this.m_currentFrameNo++;

		this.cleanupUnusedDefs(); //perf hit
	}

	/**
	* clean up unused defs
	**/
	MovieClip.prototype.cleanupUnusedDefs = function () {
		var that = this,
			defs = this.el.selectAll('defs>*'),
			j,
			i,
			id,
			toRemove;

		for (j = 0; j < defs.length; j += 1) {
			id = defs[j].attr('id');

			if (!id) {
				continue;
			}

			url = "url('#" + id + "')";
			fill = that.el.select('[fill="' + url + '"]');
			mask = that.el.select('[mask="' + url + '"]');

			if (!fill && !mask) {
				console.log('remove');
				defs[j].remove();
			}
		}

		//clear all groups moved to defs
		defGroups = this.el.selectAll('defs>g');
		for (i = 0; i < defGroups.length; i += 1) {
			defGroups[i].remove();
		}

		//clear all unused masks
		masks = this.el.selectAll('defs>mask');
		for (i = 0; i < masks.length; i += 1) {
			if (!masks[i].attr('id')) {
				masks[i].remove();
			}
		}

	}

	//PlaceObjectCommand Class
	var PlaceObjectCommand = function(charID, objectID, placeAfter, transform)
	{
		this.m_charID = charID;
		this.m_objectID = objectID;
		this.m_placeAfter = placeAfter;
		this.m_transform = transform;
	}

	//Execute function for PlaceObjectCommand
	PlaceObjectCommand.prototype.execute = function(stage, resourceManager)
	{

		var shape = resourceManager.getShape(this.m_charID),
			bitmap = resourceManager.getBitmap(this.m_charID),
			text = resourceManager.getText(this.m_charID),
			parentMC = stage.el,
			root = stage.root,
			movieclipTimeline,
			movieclip,
			children,
			i,
			childMC,
			index;

		if(shape !== null && shape !== undefined)
		{
			Utils.CreateShape(root, parentMC, resourceManager, this.m_charID, this.m_objectID, this.m_placeAfter, this.m_transform);
		}
		else if(bitmap !== null && bitmap !== undefined)
		{
			Utils.CreateBitmap(root, parentMC, resourceManager, this.m_charID, this.m_objectID, this.m_placeAfter, this.m_transform);
		}
		else if (text !== null && text !== undefined)
		{
			Utils.CreateText(root, parentMC, resourceManager, this.m_charID, this.m_objectID, this.m_placeAfter, this.m_transform);
		}
		else
		{
			// Movie clip logic starts here
			movieclipTimeline = resourceManager.getMovieClip(this.m_charID);

			if(parentMC != undefined)
			{

				//Create a  MC
				childMC = parentMC.g();
				childMC.attr({class: 'movieclip', token: this.m_objectID});

				if(this.m_placeAfter != 0)
				{
					children = parentMC.selectAll('[token="' + this.m_placeAfter + '"]');
					for (i = 0; i < children.length; i += 1) {
						if (children[i].parent().id == parentMC.id) { //ensure child of current movie clip
							children[i].before(childMC);
							break;
						}
					}
				}
				else
				{
					parentMC.add(childMC);
				}

				//Create a corresponding TimelineAnimator
				if(movieclipTimeline)
				{
					movieclip = new MovieClip(root, childMC, movieclipTimeline, resourceManager, this.m_transform);
					stage.m_children.push(movieclip);
					movieclip.play(resourceManager);
				}
			}
		}

	}

	//MoveObjectCommand Class
	var MoveObjectCommand = function(objectID, transform)
	{
		this.m_objectID = objectID;
		//this.m_placeAfter = placeAfter;
		this.m_transform = transform;
	}

	//Execute function for PlaceObjectCommand
	MoveObjectCommand.prototype.execute = function(stage, resourceManager)
	{
		var parentMC,
			transform,
			transformArray,
			transformMat,
			children,
			i;

		parentMC = stage.el;
		transform =  this.m_transform;
		transformArray = transform.split(",");
		transformMat = new Snap.Matrix(transformArray[0],transformArray[1],transformArray[2],transformArray[3],transformArray[4],transformArray[5]);

		if(parentMC != undefined)
		{
			children = parentMC.selectAll('[token="' + this.m_objectID + '"]');

			for (i = 0; i < children.length; i += 1) {
				if (children[i].parent().id == parentMC.id) { //ensure child of current movie clip
					children[i].transform(transformMat);
				}
			}
		}

	}

	//UpdateObjectCommand Class
	var UpdateObjectCommand = function(objectID, placeAfter)
	{
		this.m_objectID = objectID;
		this.m_placeAfter = placeAfter;
	}

	//Execute function for UpdateObjectCommand
	UpdateObjectCommand.prototype.execute = function(timelineAnimator, resourceManager)
	{
		/*
		var parentMC = timelineAnimator.s;

		if(parentMC != undefined)
		{
			//Change the Z order of the targetMC
			var index;
			for(var indexz=0; indexz<parentMC.children.length; indexz++)
			{
				if(parentMC.children[indexz].id == parseInt(this.m_objectID))
				{
					var child = parentMC.getChildAt(indexz);
					if(this.m_placeAfter != 0)
					{
						for(var index=0; index<parentMC.children.length; index++)
						{
							if(parentMC.children[index].id == parseInt(this.m_placeAfter))
							{
								//child.addChildAt(childMC,index);
								parentMC.setChildIndex(child,index - 1)
								break;
							}
						}
					}
					break;
				}
			}
		}
		*/
	}

	//RemoveObjectCommand Class
	var RemoveObjectCommand = function(objectID)
	{
		this.m_objectID = objectID;
	}

	//Execute function for RemoveObjectCommand
	RemoveObjectCommand.prototype.execute = function(stage, resourceManager)
	{
		var parentMC = stage.el,
			child;

		if(parentMC != undefined)
		{
			children = parentMC.selectAll('[token="' + this.m_objectID + '"]');

			for (i = 0; i < children.length; i += 1) {
				if (children[i].parent() == parentMC) { //ensure child of current movie clip
					children[i].remove();
				}
			}
		}
	}

	//UpdateVisbilityCommand Class
	var UpdateVisibilityCommand = function(objectID,visibility)
	{
		this.m_objectID = objectID;
		this.m_visibilty = visibility;
	}

	//Execute function for UpdateVisbilityCommand
	UpdateVisibilityCommand.prototype.execute = function(timelineAnimator, resourceManager)
	{
		/*
		var parentMC = timelineAnimator.m_targetMC;
		if(parentMC != undefined)
		{
			//Remove the targetMC
			var index,visibleBool;
			for(var index=0; index<parentMC.children.length; index++)
			{
				if(parentMC.children[index].id == parseInt(this.m_objectID))
				{
					if(this.m_visibilty == "true")
						visibleBool = true;
						else
						visibleBool = false;

					parentMC.getChildAt(index).visible = visibleBool;

				}
			}
		}
		*/
	}

	var UpdateMaskCommand = function (objectID,maskTill)
	{
		this.m_objectID = objectID;
		this.m_maskTill = maskTill;
	}

	UpdateMaskCommand.prototype.execute = function (stage, resourceManager)
	{
		var parentMC = stage.el,
			root = stage.root,
			mask,
			maskContent,
			masked,
			i,
			def,
			clone;

		if(parentMC != undefined)
		{
			maskContent = parentMC.select('[token="' + this.m_objectID + '"]');
			mask = root.mask();
			mask.attr('mask-type', 'alpha');
			mask.append(maskContent);

			def = mask.toDefs();

			for (i = parseInt(this.m_maskTill); i > parseInt(this.m_objectID); i -= 1) {
				//clone = def.clone(); //issue with reusing def ??
				masked = parentMC.select('[token="' + i + '"]');
				masked.attr({mask: def});
			}

		}
	}

	var UpdateColorTransformCommand = function (objectID, colorMatrix)
	{
		this.m_objectID = objectID;
		this.m_colorMatrix = colorMatrix;
	}

	UpdateColorTransformCommand.prototype.execute = function (stage, resourceManager)
	{
		var parentMC = stage.el,
			object;

		if (parentMC != undefined) {
			object = parentMC.select('[token="' + this.m_objectID + '"]');
			matrix = this.m_colorMatrix.split(',', 7);
			object.attr({opacity: parseFloat(matrix[6])}); //currently only alpha
		}
	}

	return MovieClip;

});<|endoftext|>


<commit_before>Cards.module('Set.Details', function(Details, App) {
	Details.ItemView = Backbone.Marionette.ItemView.extend({
		template: "#set-details-item",
		className: "item",
		events: {
			"click a": "linkClicked",
			"click div.box": "cardClicked"
		},
		cardClicked: function(ev) {
			ev.preventDefault();

			console.log(ev.target.nodeName);

			var front = $(ev.currentTarget).find('div.front');
			var back = $(ev.currentTarget).find('div.back');

			if(ev.target.nodeName == "DIV" || ev.target.nodeName == "SPAN") {
				front.toggle();
				back.toggle();
				this.$el.find("div.cardContent.back").toggleClass('active');
				this.$el.find("div.cardContent.front").toggleClass('active');
			}

			console.log(this.$el.find("div.cardContent.front"));
		},
		linkClicked: function(ev) {
			ev.preventDefault();
			console.log("link");
		}
	});

	Details.EmptyView = Backbone.Marionette.ItemView.extend({
		template: "#set-details-item-empty",
		className: "empty-item"
	});

	Details.DetailsView = Backbone.Marionette.CompositeView.extend({
		emptyView: Details.EmptyView,
		itemView: Details.ItemView,
		itemViewContainer: "div.carousel-inner",
		template: "#set-details-collection",
		ui: {
			modalView: "#pictureModal"
		},
		events: {
			"click a.carousel-control": "cycleCarousel",
			"click button.learn": "learnClicked",
			"click button.memo": "memoClicked",
			"click button.play-meteor": "playMeteor",
			"click a.btn-editCard": "editClicked",
			"click a.btn-showPictureModal": "showModal",
			"click a.btn-deleteCard": "deleteClicked"
		},
		playMeteor: function(ev) {
			App.trigger("play:meteor", this.model.get("id"));
		},
		showModal: function(ev) {
			ev.preventDefault();

			this.showPictureModal();
		},
		editClicked: function(ev) {
			ev.preventDefault();

			//cardid holen
			var cardId = $("div.item.active").children(".box").attr("data-id");

			App.trigger("set:details:edit", this.model.get("_id"), cardId);
		},
		deleteClicked: function(ev) {
			ev.preventDefault();
			var cardId = $("div.item.active").children(".box").attr("data-id");

			var actualCard = this.collection.get(cardId);
			console.log(this.collection);
			actualCard.destroy({
			    success : function(resp){
			    	console.log("card deleted");
			    },
			    error : function(err) {
			        console.log('error callback');
			        // this error message for dev only
			        alert('There was an error. See console for details');
			        console.log(err);
				}
			});
		},
		cycleCarousel: function(ev) {
			ev.preventDefault();

			if($(ev.currentTarget).hasClass("left")) {
				this.$el.find(":first-child").carousel("prev");
			} else if($(ev.currentTarget).hasClass("right")) {
				this.$el.find(":first-child").carousel("next");
			}
		},
		showPictureModal: function() {
			var cardId = $("div.item.active").children(".box").attr("data-id");
			var actualCard = this.collection.get(cardId);
			var cardContent = null;

			if(this.$el.find("div.cardContent.front").hasClass('active')){
				cardContent = actualCard.get("front");
			} else if(this.$el.find("div.cardContent.back").hasClass('active')) {
				cardContent = actualCard.get("back");
			}

			var imgElem = $(document.createElement('img'));
			imgElem.attr('src', cardContent.picture);
			imgElem.attr('title', cardContent.text);
			imgElem.attr('alt', cardContent.text);
			imgElem.attr('width', "538px");

			console.log(imgElem);

			$("#setdetails-pictureModal-body").empty();
			$("#setdetails-pictureModal-body").append(imgElem);

			this.ui.modalView.modal('show');
		},
		learnClicked: function(ev) {
			App.trigger("set:learn", this.model.get("_id"));
		},
		memoClicked: function(ev) {
			App.trigger("set:memo", this.model.get("_id"));
		},
		onRender: function() {

			if(this.collection.length == 0) {
				this.$el.find("a.carousel-control").hide();
				this.$el.find("button.play-meteor").prop('disabled', true);
				this.$el.find("button.learn").prop('disabled', true);
				this.$el.find("button.memo").prop('disabled', true);
			}

			this.$el.find("div.item").first().addClass("active");

			var pickerContainer = this.$el.find("ol.carousel-indicators").first();
			for(var i = 0; i < this.collection.length; i++) {
				var indicatorElem = $("

").attr("data-slide-to", i);
				if(i === 0) indicatorElem.addClass("active");

				pickerContainer.append(indicatorElem);
			}

			this.$el.find(':first-child').carousel({ interval: false });

			$('#btnToCardLayout').addClass("active");
			$('#btnToListLayout').removeClass("active");

			this.$el.find("div.cardContent.back").removeClass('active');
			this.$el.find("div.cardContent.front").addClass('active');

			//...
			if(this.collection.length !== 0) {
				var cardId = $("div.item.active").children(".box").attr("data-id");
				var actualCard = this.collection.get(cardId);
				//if(actualCard.)
				//console.log(actualCard.get("front"));
				this.$el.find("a.btn-showPictureModal").show();
			}

			var usr = $.cookie('usr');
			$("#usr-name").text();
			$.get("/score/"+usr.username+"/"+this.model.get("_id"), function( data ) {
				$("#meteor-set-points").text(data.score);
			}).fail(function(){
				console.log("yeah");
			});
		},
		onShow: function() {
		var that = this;
		var tweak = 200;

		    $.fn.resizeText = function(){
		      var size = parseInt($(this).css("fontSize"));
		      var html = $(this).html();
		      var textLength = html.length;
		      var span = "" + html + "";
		      that.$el.append(span);
		      var width = that.$el.find('span:last').width();
		      console.log(that.$el.find('span:last'));
		      console.log(width);
		      console.log($(this).width());
		      var newSize = ($(this).width()-tweak)/(width)*size;
		      console.log(newSize);
		      if (newSize < "45"){
		      	console.log("edited size enabled");
		      	$(this).css("fontSize", newSize);
		      }
		      return width;
		    };

		    this.$el.find("div.front").resizeText();
		}
	});

	Details.ListItem = Backbone.Marionette.ItemView.extend({
		tagName: "tr",
	    template: "#set-details-listitem"
	});

	Details.ListEmptyView = Backbone.Marionette.ItemView.extend({
		tagName: "tr",
		template: "#set-details-listitem-empty",
		className: "empty-listitem"
	});

	Details.DetailsListView = Backbone.Marionette.CompositeView.extend({
		emptyView: Details.ListEmptyView,
		tagName: "table",
		className: "table table-bordered table-striped table-hover",
		itemView: Details.ListItem,
		itemViewContainer: "tbody",
		template: "#set-details-list",
		events: {
			"click a.btn-listEditCard": "editClicked",
			"click a.btn-listDeleteCard": "deleteClicked"
		},
		editClicked: function(ev) {
			ev.preventDefault();

			var cardId = $(ev.currentTarget).attr("data-id")
			App.trigger("set:details:edit", this.model.get("_id"), cardId);
		},
		deleteClicked: function(ev) {
			ev.preventDefault();
			var cardId = $(ev.currentTarget).attr("data-id")

			var actualCard = this.collection.get(cardId);
			console.log(this.collection);
			actualCard.destroy({
			    success : function(resp){
			    	console.log("card deleted");
			    },
			    error : function(err) {
			        console.log('error callback');
			        // this error message for dev only
			        alert('There was an error. See console for details');
			        console.log(err);
				}
			});
		},
		onRender: function(ev) {
			$('#btnToListLayout').addClass("active");
			$('#btnToCardLayout').removeClass("active");
		}
	});
});<commit_msg>turn card to front when cycle<commit_after>Cards.module('Set.Details', function(Details, App) {
	Details.ItemView = Backbone.Marionette.ItemView.extend({
		template: "#set-details-item",
		className: "item",
		events: {
			"click a": "linkClicked",
			"click div.box": "cardClicked"
		},
		cardClicked: function(ev) {
			ev.preventDefault();

			var front = $(ev.currentTarget).find('div.front');
			var back = $(ev.currentTarget).find('div.back');

			if(ev.target.nodeName == "DIV" || ev.target.nodeName == "SPAN") {
				front.toggle();
				back.toggle();
				this.$el.find("div.cardContent.back").toggleClass('active');
				this.$el.find("div.cardContent.front").toggleClass('active');
			}

			console.log(this.$el.find("div.cardContent.front"));
		},
		linkClicked: function(ev) {
			ev.preventDefault();
			console.log("link");
		}
	});

	Details.EmptyView = Backbone.Marionette.ItemView.extend({
		template: "#set-details-item-empty",
		className: "empty-item"
	});

	Details.DetailsView = Backbone.Marionette.CompositeView.extend({
		emptyView: Details.EmptyView,
		itemView: Details.ItemView,
		itemViewContainer: "div.carousel-inner",
		template: "#set-details-collection",
		ui: {
			modalView: "#pictureModal"
		},
		events: {
			"click a.carousel-control": "cycleCarousel",
			"click button.learn": "learnClicked",
			"click button.memo": "memoClicked",
			"click button.play-meteor": "playMeteor",
			"click a.btn-editCard": "editClicked",
			"click a.btn-showPictureModal": "showModal",
			"click a.btn-deleteCard": "deleteClicked"
		},
		playMeteor: function(ev) {
			App.trigger("play:meteor", this.model.get("id"));
		},
		showModal: function(ev) {
			ev.preventDefault();

			this.showPictureModal();
		},
		editClicked: function(ev) {
			ev.preventDefault();

			//cardid holen
			var cardId = $("div.item.active").children(".box").attr("data-id");

			App.trigger("set:details:edit", this.model.get("_id"), cardId);
		},
		deleteClicked: function(ev) {
			ev.preventDefault();
			var cardId = $("div.item.active").children(".box").attr("data-id");

			var actualCard = this.collection.get(cardId);
			console.log(this.collection);
			actualCard.destroy({
			    success : function(resp){
			    	console.log("card deleted");
			    },
			    error : function(err) {
			        console.log('error callback');
			        // this error message for dev only
			        alert('There was an error. See console for details');
			        console.log(err);
				}
			});
		},
		cycleCarousel: function(ev) {
			ev.preventDefault();
			this.turnCardtoFront(ev);

			if($(ev.currentTarget).hasClass("left")) {
				this.$el.find(":first-child").carousel("prev");
			} else if($(ev.currentTarget).hasClass("right")) {
				this.$el.find(":first-child").carousel("next");
			}
		},

		turnCardtoFront: function(ev) {
			ev.preventDefault();

			var front = this.$el.find("div.cardContent.front");
			var back = this.$el.find("div.cardContent.back");

			if(back.hasClass('active')){
				console.log("togglme");
				front.toggle();
				back.toggle();
				front.toggleClass('active');
				back.toggleClass('active');
			}
		},

		showPictureModal: function() {
			var cardId = $("div.item.active").children(".box").attr("data-id");
			var actualCard = this.collection.get(cardId);
			var cardContent = null;

			if(this.$el.find("div.cardContent.front").hasClass('active')){
				cardContent = actualCard.get("front");
			} else if(this.$el.find("div.cardContent.back").hasClass('active')) {
				cardContent = actualCard.get("back");
			}

			var imgElem = $(document.createElement('img'));
			imgElem.attr('src', cardContent.picture);
			imgElem.attr('title', cardContent.text);
			imgElem.attr('alt', cardContent.text);
			imgElem.attr('width', "538px");

			console.log(imgElem);

			$("#setdetails-pictureModal-body").empty();
			$("#setdetails-pictureModal-body").append(imgElem);

			this.ui.modalView.modal('show');
		},
		learnClicked: function(ev) {
			App.trigger("set:learn", this.model.get("_id"));
		},
		memoClicked: function(ev) {
			App.trigger("set:memo", this.model.get("_id"));
		},
		onRender: function() {

			if(this.collection.length == 0) {
				this.$el.find("a.carousel-control").hide();
				this.$el.find("button.play-meteor").prop('disabled', true);
				this.$el.find("button.learn").prop('disabled', true);
				this.$el.find("button.memo").prop('disabled', true);
			}

			this.$el.find("div.item").first().addClass("active");

			var pickerContainer = this.$el.find("ol.carousel-indicators").first();
			for(var i = 0; i < this.collection.length; i++) {
				var indicatorElem = $("

").attr("data-slide-to", i);
				if(i === 0) indicatorElem.addClass("active");

				pickerContainer.append(indicatorElem);
			}

			this.$el.find(':first-child').carousel({ interval: false });

			$('#btnToCardLayout').addClass("active");
			$('#btnToListLayout').removeClass("active");

			this.$el.find("div.cardContent.back").removeClass('active');
			this.$el.find("div.cardContent.front").addClass('active');

			//...
			if(this.collection.length !== 0) {
				var cardId = $("div.item.active").children(".box").attr("data-id");
				var actualCard = this.collection.get(cardId);
				//if(actualCard.)
				//console.log(actualCard.get("front"));
				this.$el.find("a.btn-showPictureModal").show();
			}

			var usr = $.cookie('usr');
			$("#usr-name").text();
			$.get("/score/"+usr.username+"/"+this.model.get("_id"), function( data ) {
				$("#meteor-set-points").text(data.score);
			}).fail(function(){
				console.log("yeah");
			});
		},
		onShow: function() {
		var that = this;
		var tweak = 200;

		    $.fn.resizeText = function(){
		      var size = parseInt($(this).css("fontSize"));
		      var html = $(this).html();
		      var textLength = html.length;
		      var span = "" + html + "";
		      that.$el.append(span);
		      var width = that.$el.find('span:last').width();
		      console.log(that.$el.find('span:last'));
		      console.log(width);
		      console.log($(this).width());
		      var newSize = ($(this).width()-tweak)/(width)*size;
		      console.log(newSize);
		      if (newSize < "45"){
		      	console.log("edited size enabled");
		      	$(this).css("fontSize", newSize);
		      }
		      return width;
		    };

		    this.$el.find("div.front").resizeText();
		}
	});

	Details.ListItem = Backbone.Marionette.ItemView.extend({
		tagName: "tr",
	    template: "#set-details-listitem"
	});

	Details.ListEmptyView = Backbone.Marionette.ItemView.extend({
		tagName: "tr",
		template: "#set-details-listitem-empty",
		className: "empty-listitem"
	});

	Details.DetailsListView = Backbone.Marionette.CompositeView.extend({
		emptyView: Details.ListEmptyView,
		tagName: "table",
		className: "table table-bordered table-striped table-hover",
		itemView: Details.ListItem,
		itemViewContainer: "tbody",
		template: "#set-details-list",
		events: {
			"click a.btn-listEditCard": "editClicked",
			"click a.btn-listDeleteCard": "deleteClicked"
		},
		editClicked: function(ev) {
			ev.preventDefault();

			var cardId = $(ev.currentTarget).attr("data-id")
			App.trigger("set:details:edit", this.model.get("_id"), cardId);
		},
		deleteClicked: function(ev) {
			ev.preventDefault();
			var cardId = $(ev.currentTarget).attr("data-id")

			var actualCard = this.collection.get(cardId);
			console.log(this.collection);
			actualCard.destroy({
			    success : function(resp){
			    	console.log("card deleted");
			    },
			    error : function(err) {
			        console.log('error callback');
			        // this error message for dev only
			        alert('There was an error. See console for details');
			        console.log(err);
				}
			});
		},
		onRender: function(ev) {
			$('#btnToListLayout').addClass("active");
			$('#btnToCardLayout').removeClass("active");
		}
	});
});<|endoftext|>


<commit_before>define(['q'], function(Q) {

    'use strict';

	return ['$scope', '$location', 'Rest', 'AbsenceEdit', '$routeParams', '$rootScope',
            function($scope, $location, Rest, AbsenceEdit, $routeParams, $rootScope) {

        AbsenceEdit.initScope($scope);

        // resources
        var calendars = Rest.account.calendars.getResource();
        var calendarEvents = Rest.account.calendarevents.getResource();
        var personalEvents = Rest.account.personalevents.getResource();
        var accountCollection = Rest.account.collection.getResource();
        var accountRights = Rest.account.accountrights.getResource();
        var users = Rest.user.user.getResource();

        $scope.request = Rest.account.requests.getFromUrl().loadRouteId();

        var userPromise =  users.get().$promise;
        var requestUser = null;

        if ($scope.request.$promise) {
            $scope.request.$promise.then(function() {
                // edit this request
                $scope.editRequest = true;
                AbsenceEdit.setSelectionFromRequest($scope);
                $scope.loadWorkingTimes = AbsenceEdit.getLoadWorkingTimes(userPromise, calendarEvents, $scope.request.events);
            });
        } else {

            // create a new request
            $scope.newRequest = true;

            $scope.request.events = [];
            $scope.request.timeCreated = new Date();
            $scope.request.absence = {
                    distribution: []
            };

            $scope.loadWorkingTimes = AbsenceEdit.getLoadWorkingTimes(userPromise, calendarEvents);
        }

        userPromise.then(function(user) {

            requestUser = user;
            AbsenceEdit.onceUserLoaded($scope, user, calendarEvents);

            $scope.request.user = {
                id: user._id,
                name: user.lastname+' '+user.firstname
            };
        });

        $scope.loadScholarHolidays = AbsenceEdit.getLoadScholarHolidays(calendars, calendarEvents);

        var loadEvents = AbsenceEdit.getLoadEvents(userPromise, personalEvents, calendars, calendarEvents);

        if (undefined === $routeParams.id) {
            $scope.loadEvents = loadEvents;

        } else {

            $scope.loadEvents = function(interval) {
                var deferred = Q.defer();
                loadEvents(interval).then(function(events) {

                    events = events.filter(function(e) {
                        return (e.request !== $routeParams.id);
                    });

                    deferred.resolve(events);
                });

                return deferred.promise;
            };
        }

        /**
         * Go back to requests list, admin view
         */
        $scope.back = function() {
            $location.path('/account/requests');
        };

        /**
         * Go from the period selection to the right assignments step
         */
        $scope.next = function() {

            /**
             * Load collection
             * The collection available on the selected period
             */
            $scope.collection = accountCollection.get({
                user: $scope.sessionUser.id,
                dtstart: $scope.selection.begin,
                dtend: $scope.selection.end
            });

            var serviceAction = AbsenceEdit.getNextButtonJob($scope, requestUser, accountRights);

            serviceAction();
        };

        $scope.saveAbsence = function() {

            var rights = $scope.distribution.right;
            var periods = $scope.selection.periods;

            try {
                $scope.request.absence.distribution = AbsenceEdit.createDistribution(rights, periods, $scope.accountRights);
                $scope.request.ingaSave($scope.back);
            } catch(e) {
                $rootScope.pageAlerts.push({
                    message: e.message,
                    type: 'danger'
                });
            }
        };

	}];
});

<commit_msg>Fix request entity too large bug<commit_after>define(['q'], function(Q) {

    'use strict';

	return ['$scope', '$location', 'Rest', 'AbsenceEdit', '$routeParams', '$rootScope',
            function($scope, $location, Rest, AbsenceEdit, $routeParams, $rootScope) {

        AbsenceEdit.initScope($scope);

        // resources
        var calendars = Rest.account.calendars.getResource();
        var calendarEvents = Rest.account.calendarevents.getResource();
        var personalEvents = Rest.account.personalevents.getResource();
        var accountCollection = Rest.account.collection.getResource();
        var accountRights = Rest.account.accountrights.getResource();
        var users = Rest.user.user.getResource();

        $scope.request = Rest.account.requests.getFromUrl().loadRouteId();

        var userPromise =  users.get().$promise;
        var requestUser = null;

        if ($scope.request.$promise) {
            $scope.request.$promise.then(function() {
                // edit this request
                $scope.editRequest = true;
                AbsenceEdit.setSelectionFromRequest($scope);
                $scope.loadWorkingTimes = AbsenceEdit.getLoadWorkingTimes(userPromise, calendarEvents, $scope.request.events);
            });
        } else {

            // create a new request
            $scope.newRequest = true;

            $scope.request.events = [];
            $scope.request.timeCreated = new Date();
            $scope.request.absence = {
                    distribution: []
            };

            $scope.loadWorkingTimes = AbsenceEdit.getLoadWorkingTimes(userPromise, calendarEvents);
        }

        userPromise.then(function(user) {

            requestUser = user;
            AbsenceEdit.onceUserLoaded($scope, user, calendarEvents);

            $scope.request.user = {
                id: user._id,
                name: user.lastname+' '+user.firstname
            };
        });

        $scope.loadScholarHolidays = AbsenceEdit.getLoadScholarHolidays(calendars, calendarEvents);

        var loadEvents = AbsenceEdit.getLoadEvents(userPromise, personalEvents, calendars, calendarEvents);

        if (undefined === $routeParams.id) {
            $scope.loadEvents = loadEvents;

        } else {

            $scope.loadEvents = function(interval) {
                var deferred = Q.defer();
                loadEvents(interval).then(function(events) {

                    events = events.filter(function(e) {
                        return (e.request !== $routeParams.id);
                    });

                    deferred.resolve(events);
                });

                return deferred.promise;
            };
        }

        /**
         * Go back to requests list, admin view
         */
        $scope.back = function() {
            $location.path('/account/requests');
        };

        /**
         * Go from the period selection to the right assignments step
         */
        $scope.next = function() {

            /**
             * Load collection
             * The collection available on the selected period
             */
            $scope.collection = accountCollection.get({
                user: $scope.sessionUser.id,
                dtstart: $scope.selection.begin,
                dtend: $scope.selection.end
            });

            var serviceAction = AbsenceEdit.getNextButtonJob($scope, requestUser, accountRights);

            serviceAction();
        };

        $scope.saveAbsence = function() {

            var rights = $scope.distribution.right;
            var periods = $scope.selection.periods;

            // cleanup object
            delete $scope.request.requestLog;
            delete $scope.request.approvalSteps;

            try {
                $scope.request.absence.distribution = AbsenceEdit.createDistribution(rights, periods, $scope.accountRights);
                $scope.request.ingaSave($scope.back);
            } catch(e) {
                $rootScope.pageAlerts.push({
                    message: e.message,
                    type: 'danger'
                });
            }
        };

	}];
});

<|endoftext|>


<commit_before>// SSO login, register modal iframe
// --------------------------------

(function(){

	$( document ).ready(function(){

		if (!window.amnestySSO) {
			window.amnestySSO = {
				init : false
			}
		} else {
			window.amnestySSO.init = false;
		}

		if (!window.amnestySSO.init) {
			var html = '\

\

\

\

\
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>\

BECOME AN AMNESTY DECODER
\

\

\

\

\

Registering allows you to participate in discussions, track your progress and helps the research teams make the best use of the data you provide.
\

\

\
					<button class="btn-secondary--alt--md--fullwidth btn-register login-modal" id="register-btn">REGISTER</button>\

\
					<button class="btn-secondary--alt--md--fullwidth btn-sign-in login-modal" id="login-btn">SIGN IN</button>\

\
					<button class="btn-link btn-skip-registration login-modal" id="skip-btn">Skip registration</button>\

\

\

Loading ...
\
				Loading\

\

\

\

\
			';

			//modal html
			$('body').append(html);

			window.amnestySSO.showImModalContent = function(loginModalMode) {

				if (loginModalMode == 'register') {
					$("#amnestySSOModal .modal-title").html('Register');
				} else if (loginModalMode == 'login') {
					$("#amnestySSOModal .modal-title").html('Sign in');
				} else {
					$("#amnestySSOModal .modal-title").html('');
				}

				if (loginModalMode == 'register' || loginModalMode == 'login') {
					$("#amnestySSOModal .option").hide();

					var iframeLink = {
						'login' : window.amnestySSO.imServerUrl + '/login/modal',
						'register': window.amnestySSO.imServerUrl + '/register/modal'
					}

					$("#amnestySSOModal .loading").show();

					//hide current iframe content
					$('#amnestySSOModal iframe').hide();

					//link IM's login form with modal's content
					$('#amnestySSOModal iframe').attr('src', iframeLink[loginModalMode]);
				} else {
					//show register, login, skip options again
					$("#amnestySSOModal .loading").hide();
					$('#amnestySSOModal iframe').hide();
					$("#amnestySSOModal .option").show();
				}
			};

			$('#amnestySSOModal iframe').load(function(){
			      $("#amnestySSOModal .loading").hide();
			      //only show iframe content after it finishes loading
			      $('#amnestySSOModal iframe').show();
			});

			$('#amnestySSOModal #register-btn').click(function(){
				//update for later redirect to tutorial page
				window.amnestySSO.loginModalMode = 'register';

				//set bigger height
				$('#amnestySSOModal .modal-body iframe').height('80vh');

				window.amnestySSO.showImModalContent('register');
			});

			$('#amnestySSOModal #login-btn').click(function(){
				window.amnestySSO.showImModalContent('login');
			});

			$('#amnestySSOModal #skip-btn').click(function(){
				$('#amnestySSOModal').modal('hide');
			});

			//wait IM login form to return token
			window.addEventListener("message", receiveMessage, false);
			function receiveMessage(event)
			{
				var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
				if (origin !== window.amnestySSO.imServerUrl)
					return;

				$.post('/amnesty/oauth-authorized-with-password', {
						'access_token': event.data['access_token'],
						'csrf_token': $('#ajax_csrf_token').val()
					})
					.done(function(data){
						//if user hasn't tried tutorial yet then show it
						if (!window.pybossaTutorial.isSkippedOrComplete()) {
							window.location = '/project/decode-darfur/tutorial';
						}
						//other case, just reload current window
						else {
							location.reload();
						}
					})
					.fail(function(data){
        				console.log('failed');
        				console.log(data);
        			})
        			.always(function(){
        			});
			}
		}
	});

})();

// Bootstrap login/register modal if query string has ?modal=login/register/all
// ---
(function(){
	$( document ).ready(function(){

		window.amnestySSO.bootstrapLoginRegister = function() {
			//only show modal when user is not logged in
			if ( window.amnestySSO.isAnonymous != 'True') {
				return;
			}

			//not valid mode
			var validModalMode = ['login', 'register', 'all'];
			if ( !( validModalMode.indexOf(window.amnestySSO.loginModalMode) > -1 ) ) {
				return;
			}

			switch (window.amnestySSO.loginModalMode) {
				case 'login' :
					$('#amnestySSOModal').modal('show');
					window.amnestySSO.showImModalContent('login');

					break;

				case 'register' :
					//set bigger height
					$('#amnestySSOModal .modal-body iframe').height('80vh');

					//show register modal
					$('#amnestySSOModal').modal('show');
					window.amnestySSO.showImModalContent('register');

					break;

				case 'all' :
					$('#amnestySSOModal').modal('show');

					break;
			}
		}

		window.amnestySSO.bootstrapLoginRegister();
	});
})();
// Flag modal
// ----------
(function(){
	$( document ).ready(function(){
		//we rename flagModal to flagModal2 so external "data-target='#flagModal'" element can't open that modal directly
		var html = '\

\

\

\

\

\

Comment on this area
\
	          <button type="button" class="close pull-right" data-dismiss="modal" aria-label="Close">×</button>\

\

\

\

\
	          <textarea class="form-control" rows="3" id="flag-content" placeholder="Tell us if you see something in this area that our researchers and other Decoders should take a closer look at."></textarea>\

\

\
	            <button type="button" class="btn-primary--md--fullwidth btn-flag" id="flag-btn">\
	              \
	              Flag this section\
	            </button>\

\
	            Your comment will appear in the Amnesty Decoders community forum\

\

\

\

Thanks for your comments and suggestions
\

\
	          View comment on forum\

\

\
	          <button type="button" class="btn btn-primary" data-dismiss="modal" id="flag-btn-close">Close</button>\

\

\

\

\

\
	\
			';

		$('body').append(html);

		$("[data-target='#flagModal']").click(function(){
			if(!window.isInTutorial){
				//only logged-in user can comment
				if (window.amnestySSO.isAnonymous != 'True') {
					$('#flagModal2').modal('show');
				}
				//show register/login modal for new user
				else {
					window.amnestySSO.loginModalMode = 'all';
					var flagFormDescriptionHtml = '\

Sign in to help us make the most out of your hard work.
\

Signing in allows you to participate in discussions and allows us to give you credit for your work and make the best use of the data you provide.
\
					\
					';
					$('#amnestySSOModal .description').html(flagFormDescriptionHtml);
					window.amnestySSO.showImModalContent('all');
					$('#amnestySSOModal').modal('show');
				}
			}
		});

		$(".btn-flag").click(function(){
			var comment = $('#flag-content').val();
			comment = comment.trim();

			if (!comment) {
				$("#flagModal2 .message").html("Please enter your comment");
				return;
			}

			//loading effect
			$('#flagModal2').waitMe();

			$.get('/discourse/create-comment', {
					"comment": comment,
					"task-id": pybossa.task.id
				})
				.done(function(data){
					$('#flagModal2 .view-comment-on-forum').attr('href', data.topic_url);
					//clear error message
					$("#flagModal2 .message").html("");
					//hide comment input
					$('#flagModal2 .submit-comment-container').hide();
					//show forum link
					$('#flagModal2 .after-submit-sucess').show();
				})
				.fail(function(data){
					var message = "There is error";
					if (data && data.responseText) {
						var error = $.parseJSON(data.responseText);
						if (error && error.errors) {
							message = error.errors.join('
');
						}
					}
					$("#flagModal2 .message").html(message);
				})
				.always(function() {
					//remove loading effect
					$('#flagModal2').waitMe('hide');
				});
		});

		$('#flagModal2').on('hidden.bs.modal', function (e) {
			//reset
			//show comment input
			$('#flagModal2 .submit-comment-container').show();
			$('#flag-content').val("")
			//hide forum link
			$('#flagModal2 .after-submit-sucess').hide();
			//clear error message
			$("#flagModal2 .message").html("");
		});

		$('#flagModal2').on('show.bs.modal', function (e) {
			$('.btn-flag .glyphicon-refresh').hide();
		});
	});

})();<commit_msg>update close button style in flag modal<commit_after>// SSO login, register modal iframe
// --------------------------------

(function(){

	$( document ).ready(function(){

		if (!window.amnestySSO) {
			window.amnestySSO = {
				init : false
			}
		} else {
			window.amnestySSO.init = false;
		}

		if (!window.amnestySSO.init) {
			var html = '\

\

\

\

\
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>\

BECOME AN AMNESTY DECODER
\

\

\

\

\

Registering allows you to participate in discussions, track your progress and helps the research teams make the best use of the data you provide.
\

\

\
					<button class="btn-secondary--alt--md--fullwidth btn-register login-modal" id="register-btn">REGISTER</button>\

\
					<button class="btn-secondary--alt--md--fullwidth btn-sign-in login-modal" id="login-btn">SIGN IN</button>\

\
					<button class="btn-link btn-skip-registration login-modal" id="skip-btn">Skip registration</button>\

\

\

Loading ...
\
				Loading\

\

\

\

\
			';

			//modal html
			$('body').append(html);

			window.amnestySSO.showImModalContent = function(loginModalMode) {

				if (loginModalMode == 'register') {
					$("#amnestySSOModal .modal-title").html('Register');
				} else if (loginModalMode == 'login') {
					$("#amnestySSOModal .modal-title").html('Sign in');
				} else {
					$("#amnestySSOModal .modal-title").html('');
				}

				if (loginModalMode == 'register' || loginModalMode == 'login') {
					$("#amnestySSOModal .option").hide();

					var iframeLink = {
						'login' : window.amnestySSO.imServerUrl + '/login/modal',
						'register': window.amnestySSO.imServerUrl + '/register/modal'
					}

					$("#amnestySSOModal .loading").show();

					//hide current iframe content
					$('#amnestySSOModal iframe').hide();

					//link IM's login form with modal's content
					$('#amnestySSOModal iframe').attr('src', iframeLink[loginModalMode]);
				} else {
					//show register, login, skip options again
					$("#amnestySSOModal .loading").hide();
					$('#amnestySSOModal iframe').hide();
					$("#amnestySSOModal .option").show();
				}
			};

			$('#amnestySSOModal iframe').load(function(){
			      $("#amnestySSOModal .loading").hide();
			      //only show iframe content after it finishes loading
			      $('#amnestySSOModal iframe').show();
			});

			$('#amnestySSOModal #register-btn').click(function(){
				//update for later redirect to tutorial page
				window.amnestySSO.loginModalMode = 'register';

				//set bigger height
				$('#amnestySSOModal .modal-body iframe').height('80vh');

				window.amnestySSO.showImModalContent('register');
			});

			$('#amnestySSOModal #login-btn').click(function(){
				window.amnestySSO.showImModalContent('login');
			});

			$('#amnestySSOModal #skip-btn').click(function(){
				$('#amnestySSOModal').modal('hide');
			});

			//wait IM login form to return token
			window.addEventListener("message", receiveMessage, false);
			function receiveMessage(event)
			{
				var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
				if (origin !== window.amnestySSO.imServerUrl)
					return;

				$.post('/amnesty/oauth-authorized-with-password', {
						'access_token': event.data['access_token'],
						'csrf_token': $('#ajax_csrf_token').val()
					})
					.done(function(data){
						//if user hasn't tried tutorial yet then show it
						if (!window.pybossaTutorial.isSkippedOrComplete()) {
							window.location = '/project/decode-darfur/tutorial';
						}
						//other case, just reload current window
						else {
							location.reload();
						}
					})
					.fail(function(data){
        				console.log('failed');
        				console.log(data);
        			})
        			.always(function(){
        			});
			}
		}
	});

})();

// Bootstrap login/register modal if query string has ?modal=login/register/all
// ---
(function(){
	$( document ).ready(function(){

		window.amnestySSO.bootstrapLoginRegister = function() {
			//only show modal when user is not logged in
			if ( window.amnestySSO.isAnonymous != 'True') {
				return;
			}

			//not valid mode
			var validModalMode = ['login', 'register', 'all'];
			if ( !( validModalMode.indexOf(window.amnestySSO.loginModalMode) > -1 ) ) {
				return;
			}

			switch (window.amnestySSO.loginModalMode) {
				case 'login' :
					$('#amnestySSOModal').modal('show');
					window.amnestySSO.showImModalContent('login');

					break;

				case 'register' :
					//set bigger height
					$('#amnestySSOModal .modal-body iframe').height('80vh');

					//show register modal
					$('#amnestySSOModal').modal('show');
					window.amnestySSO.showImModalContent('register');

					break;

				case 'all' :
					$('#amnestySSOModal').modal('show');

					break;
			}
		}

		window.amnestySSO.bootstrapLoginRegister();
	});
})();
// Flag modal
// ----------
(function(){
	$( document ).ready(function(){
		//we rename flagModal to flagModal2 so external "data-target='#flagModal'" element can't open that modal directly
		var html = '\

\

\

\

\

\

Comment on this area
\
	          <button type="button" class="close pull-right" data-dismiss="modal" aria-label="Close">×</button>\

\

\

\

\
	          <textarea class="form-control" rows="3" id="flag-content" placeholder="Tell us if you see something in this area that our researchers and other Decoders should take a closer look at."></textarea>\

\

\
	            <button type="button" class="btn-primary--md--fullwidth btn-flag" id="flag-btn">\
	              \
	              Flag this section\
	            </button>\

\
	            Your comment will appear in the Amnesty Decoders community forum\

\

\

\

Thanks for your comments and suggestions
\

\
	          View comment on forum\

\

\
	          <button type="button" class="btn-secondary--alt--md--fullwidth" data-dismiss="modal" id="flag-btn-close" style="width: 150px;">Close</button>\

\

\

\

\

\
	\
			';

		$('body').append(html);

		$("[data-target='#flagModal']").click(function(){
			if(!window.isInTutorial){
				//only logged-in user can comment
				if (window.amnestySSO.isAnonymous != 'True') {
					$('#flagModal2').modal('show');
				}
				//show register/login modal for new user
				else {
					window.amnestySSO.loginModalMode = 'all';
					var flagFormDescriptionHtml = '\

Sign in to help us make the most out of your hard work.
\

Signing in allows you to participate in discussions and allows us to give you credit for your work and make the best use of the data you provide.
\
					\
					';
					$('#amnestySSOModal .description').html(flagFormDescriptionHtml);
					window.amnestySSO.showImModalContent('all');
					$('#amnestySSOModal').modal('show');
				}
			}
		});

		$(".btn-flag").click(function(){
			var comment = $('#flag-content').val();
			comment = comment.trim();

			if (!comment) {
				$("#flagModal2 .message").html("Please enter your comment");
				return;
			}

			//loading effect
			$('#flagModal2').waitMe();

			$.get('/discourse/create-comment', {
					"comment": comment,
					"task-id": pybossa.task.id
				})
				.done(function(data){
					$('#flagModal2 .view-comment-on-forum').attr('href', data.topic_url);
					//clear error message
					$("#flagModal2 .message").html("");
					//hide comment input
					$('#flagModal2 .submit-comment-container').hide();
					//show forum link
					$('#flagModal2 .after-submit-sucess').show();
				})
				.fail(function(data){
					var message = "There is error";
					if (data && data.responseText) {
						var error = $.parseJSON(data.responseText);
						if (error && error.errors) {
							message = error.errors.join('
');
						}
					}
					$("#flagModal2 .message").html(message);
				})
				.always(function() {
					//remove loading effect
					$('#flagModal2').waitMe('hide');
				});
		});

		$('#flagModal2').on('hidden.bs.modal', function (e) {
			//reset
			//show comment input
			$('#flagModal2 .submit-comment-container').show();
			$('#flag-content').val("")
			//hide forum link
			$('#flagModal2 .after-submit-sucess').hide();
			//clear error message
			$("#flagModal2 .message").html("");
		});

		$('#flagModal2').on('show.bs.modal', function (e) {
			$('.btn-flag .glyphicon-refresh').hide();
		});
	});

})();<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import ReactPaginate from 'react-paginate'
import { push } from 'react-router-redux'
import shallowEqual from 'fbjs/lib/shallowEqual'
import { injectIntl, intlShape, defineMessages } from 'react-intl'

import * as SearchActions from '../actions/SearchActions'
import * as SearchFilterActions from '../actions/SearchFilterActions'
import * as ResourceActions from '../actions/ResourceActions'
import SearchResults from '../components/SearchResults'
import SearchFilters from '../components/SearchFilters'
import Constants from '../constants/Constants'
import SearchResultsText from '../components/SearchResultsText'
import SearchFilterBox from '../components/SearchFilterBox'

class Search extends React.Component {
  constructor (props) {
    super(props)
    this.handlePageClick = this.handlePageClick.bind(this)
  }

  componentWillMount () {
    this.props.searchActions.search()
  }

  componentDidUpdate (prevProps) {
    if (!shallowEqual(this.filterLocationQuery(this.props.locationQuery), this.filterLocationQuery(prevProps.locationQuery))) {
      this.props.searchActions.search()
    }
  }

  filterLocationQuery (locationQuery) {
    const filteredLocationQuery = {}
    Object.keys(locationQuery).filter(key => [ 'query', 'filter' ].includes(key)).forEach(key => {
      filteredLocationQuery[ key ] = locationQuery[ key ]
    })
    return filteredLocationQuery
  }

  handlePageClick (data) {
    let page = String(data.selected + 1)
    if (page !== this.props.location.query.page) {
      let newQuery = {
        ...this.props.location.query,
        page: page
      }
      this.props.dispatch(push({ pathname: '/search', query: newQuery }))
    }
  }

  renderPagination () {
    if ((this.props.totalHits > Constants.maxSearchResultsPerPage) && this.props.location.query.query) {
      return (

            <ReactPaginate
              previousLabel={<}
              nextLabel={>}
              breakLabel={
...
}
              forceSelected={this.props.location.query.page - 1 || 0}
              marginPagesDisplayed={1}
              pageRangeDisplayed={5}
              pageNum={Math.ceil(Math.min(this.props.totalHits, Constants.maxSearchResults) / Constants.maxSearchResultsPerPage)}
              clickCallback={this.handlePageClick}
              containerClassName={'pagination'}
              subContainerClassName={'pages pagination'}
              activeClassName={'active'} />

      )
    }
  }

  render () {
    return (

          {this.props.locationQuery.query
            ? (

              <SearchResultsText totalHits={this.props.totalHits}
                                 totalHitsPublications={this.props.totalHitsPublications}
                                 locationQuery={this.props.locationQuery}
                                 isSearching={this.props.isSearching} />
              <SearchFilterBox query={this.props.locationQuery}
                               toggleFilter={this.props.searchFilterActions.toggleFilter} />

            {this.props.totalHits > 0
              ? (

Sorter treff på

                <select>
                  <option defaultValue>Årstall</option>
                  <option>Nyeste</option>
                  <option>Eldre</option>
                </select>

) : null}

)
            : null}
          {this.props.totalHits > 0
            ? [ <SearchFilters key="searchFilters"
                               filters={this.props.filters}
                               locationQuery={this.props.location.query}
                               toggleFilter={this.props.searchFilterActions.toggleFilter}
                               toggleFilterVisibility={this.props.searchFilterActions.toggleFilterVisibility}
                               toggleAllFiltersVisibility={this.props.searchFilterActions.toggleAllFiltersVisibility}
                               toggleCollapseFilter={this.props.searchFilterActions.toggleCollapseFilter} />,
            <SearchResults key="searchResults"
                           locationQuery={this.props.location.query}
                           searchActions={this.props.searchActions}
                           searchResults={this.props.searchResults}
                           totalHits={this.props.totalHits}
                           searchError={this.props.searchError}
                           fetchWorkResource={this.props.resourceActions.fetchWorkResource}
                           resources={this.props.resources}
                           page={this.props.location.query.page}
            /> ]
            : null}
          {this.renderPagination()}

    )
  }
}

Search.propTypes = {
  searchActions: PropTypes.object.isRequired,
  searchFilterActions: PropTypes.object.isRequired,
  searchResults: PropTypes.array.isRequired,
  isSearching: PropTypes.bool.isRequired,
  dispatch: PropTypes.func.isRequired,
  searchError: PropTypes.any.isRequired,
  filters: PropTypes.array.isRequired,
  location: PropTypes.object.isRequired,
  searchFieldInput: PropTypes.string,
  totalHits: PropTypes.number.isRequired,
  totalHitsPublications: PropTypes.number.isRequired,
  locationQuery: PropTypes.object.isRequired,
  resources: PropTypes.object.isRequired,
  resourceActions: PropTypes.object.isRequired,
  intl: intlShape.isRequired
}

const i18nSearch = injectIntl(Search)
export { i18nSearch as Search }

function mapStateToProps (state) {
  return {
    searchResults: state.search.searchResults,
    totalHits: state.search.totalHits,
    totalHitsPublications: state.search.totalHitsPublications,
    isSearching: state.search.isSearching,
    searchError: state.search.searchError,
    filters: state.search.filters,
    locationQuery: state.routing.locationBeforeTransitions.query,
    resources: state.resources.resources
  }
}

function mapDispatchToProps (dispatch) {
  return {
    searchActions: bindActionCreators(SearchActions, dispatch),
    searchFilterActions: bindActionCreators(SearchFilterActions, dispatch),
    resourceActions: bindActionCreators(ResourceActions, dispatch),
    dispatch: dispatch
  }
}

const messages = defineMessages({
  paginationLabel: {
    id: 'Search.paginationLabel',
    description: 'The ARIA label for the pagination bar',
    defaultMessage: 'Pagination'
  },
  paginationNext: {
    id: 'Search.paginationNext',
    description: 'The ARIA label for the "next" link',
    defaultMessage: 'Next'
  },
  paginationPrevious: {
    id: 'Search.paginationPrevious',
    description: 'The ARIA label frot the "previous" link',
    defaultMessage: 'Previous'
  }
})

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Search)
<commit_msg>injet intl<commit_after>import React, { PropTypes } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import ReactPaginate from 'react-paginate'
import { push } from 'react-router-redux'
import shallowEqual from 'fbjs/lib/shallowEqual'
import { injectIntl, intlShape, defineMessages } from 'react-intl'

import * as SearchActions from '../actions/SearchActions'
import * as SearchFilterActions from '../actions/SearchFilterActions'
import * as ResourceActions from '../actions/ResourceActions'
import SearchResults from '../components/SearchResults'
import SearchFilters from '../components/SearchFilters'
import Constants from '../constants/Constants'
import SearchResultsText from '../components/SearchResultsText'
import SearchFilterBox from '../components/SearchFilterBox'

class Search extends React.Component {
  constructor (props) {
    super(props)
    this.handlePageClick = this.handlePageClick.bind(this)
  }

  componentWillMount () {
    this.props.searchActions.search()
  }

  componentDidUpdate (prevProps) {
    if (!shallowEqual(this.filterLocationQuery(this.props.locationQuery), this.filterLocationQuery(prevProps.locationQuery))) {
      this.props.searchActions.search()
    }
  }

  filterLocationQuery (locationQuery) {
    const filteredLocationQuery = {}
    Object.keys(locationQuery).filter(key => [ 'query', 'filter' ].includes(key)).forEach(key => {
      filteredLocationQuery[ key ] = locationQuery[ key ]
    })
    return filteredLocationQuery
  }

  handlePageClick (data) {
    let page = String(data.selected + 1)
    if (page !== this.props.location.query.page) {
      let newQuery = {
        ...this.props.location.query,
        page: page
      }
      this.props.dispatch(push({ pathname: '/search', query: newQuery }))
    }
  }

  renderPagination () {
    if ((this.props.totalHits > Constants.maxSearchResultsPerPage) && this.props.location.query.query) {
      return (

            <ReactPaginate
              previousLabel={<}
              nextLabel={>}
              breakLabel={
...
}
              forceSelected={this.props.location.query.page - 1 || 0}
              marginPagesDisplayed={1}
              pageRangeDisplayed={5}
              pageNum={Math.ceil(Math.min(this.props.totalHits, Constants.maxSearchResults) / Constants.maxSearchResultsPerPage)}
              clickCallback={this.handlePageClick}
              containerClassName={'pagination'}
              subContainerClassName={'pages pagination'}
              activeClassName={'active'} />

      )
    }
  }

  render () {
    return (

          {this.props.locationQuery.query
            ? (

              <SearchResultsText totalHits={this.props.totalHits}
                                 totalHitsPublications={this.props.totalHitsPublications}
                                 locationQuery={this.props.locationQuery}
                                 isSearching={this.props.isSearching} />
              <SearchFilterBox query={this.props.locationQuery}
                               toggleFilter={this.props.searchFilterActions.toggleFilter} />

            {this.props.totalHits > 0
              ? (

Sorter treff på

                <select>
                  <option defaultValue>Årstall</option>
                  <option>Nyeste</option>
                  <option>Eldre</option>
                </select>

) : null}

)
            : null}
          {this.props.totalHits > 0
            ? [ <SearchFilters key="searchFilters"
                               filters={this.props.filters}
                               locationQuery={this.props.location.query}
                               toggleFilter={this.props.searchFilterActions.toggleFilter}
                               toggleFilterVisibility={this.props.searchFilterActions.toggleFilterVisibility}
                               toggleAllFiltersVisibility={this.props.searchFilterActions.toggleAllFiltersVisibility}
                               toggleCollapseFilter={this.props.searchFilterActions.toggleCollapseFilter} />,
            <SearchResults key="searchResults"
                           locationQuery={this.props.location.query}
                           searchActions={this.props.searchActions}
                           searchResults={this.props.searchResults}
                           totalHits={this.props.totalHits}
                           searchError={this.props.searchError}
                           fetchWorkResource={this.props.resourceActions.fetchWorkResource}
                           resources={this.props.resources}
                           page={this.props.location.query.page}
            /> ]
            : null}
          {this.renderPagination()}

    )
  }
}

Search.propTypes = {
  searchActions: PropTypes.object.isRequired,
  searchFilterActions: PropTypes.object.isRequired,
  searchResults: PropTypes.array.isRequired,
  isSearching: PropTypes.bool.isRequired,
  dispatch: PropTypes.func.isRequired,
  searchError: PropTypes.any.isRequired,
  filters: PropTypes.array.isRequired,
  location: PropTypes.object.isRequired,
  searchFieldInput: PropTypes.string,
  totalHits: PropTypes.number.isRequired,
  totalHitsPublications: PropTypes.number.isRequired,
  locationQuery: PropTypes.object.isRequired,
  resources: PropTypes.object.isRequired,
  resourceActions: PropTypes.object.isRequired,
  intl: intlShape.isRequired
}

const i18nSearch = injectIntl(Search)
export { i18nSearch as Search }

function mapStateToProps (state) {
  return {
    searchResults: state.search.searchResults,
    totalHits: state.search.totalHits,
    totalHitsPublications: state.search.totalHitsPublications,
    isSearching: state.search.isSearching,
    searchError: state.search.searchError,
    filters: state.search.filters,
    locationQuery: state.routing.locationBeforeTransitions.query,
    resources: state.resources.resources
  }
}

function mapDispatchToProps (dispatch) {
  return {
    searchActions: bindActionCreators(SearchActions, dispatch),
    searchFilterActions: bindActionCreators(SearchFilterActions, dispatch),
    resourceActions: bindActionCreators(ResourceActions, dispatch),
    dispatch: dispatch
  }
}

const messages = defineMessages({
  paginationLabel: {
    id: 'Search.paginationLabel',
    description: 'The ARIA label for the pagination bar',
    defaultMessage: 'Pagination'
  },
  paginationNext: {
    id: 'Search.paginationNext',
    description: 'The ARIA label for the "next" link',
    defaultMessage: 'Next'
  },
  paginationPrevious: {
    id: 'Search.paginationPrevious',
    description: 'The ARIA label frot the "previous" link',
    defaultMessage: 'Previous'
  }
})

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(injectIntl(Search))
<|endoftext|>


<commit_before>$(function () {
	$(document).ready(function () {
		var server = $('input[name="hwaddr"]').val();
		var csrf = $('input[name="csrfmiddlewaretoken"]').val();
		var secret = $('input[name="secret"]').val();

		cpu_usage_set(csrf, server, secret);
		processes(csrf, server, secret);
//		loadavg_set (csrf, server, secret);
	});
});

function processes(csrf, server, secret) {
	var address = '/ajax/server/' + server + '/metrics/processes/';

	$('#running_processes_table').dataTable({
		lengthMenu: [[15, 50, 100], [15, 50, 100]],
		order: [[ 2, "desc" ]],
		draw: 1,
		processing: true,
		serverSide: true,
		ajax: {
			url: address,
			type: 'POST',
			dataType: 'json',
			dataSrc: function(json) {
				var data = [];
				for (var i = 0; i < json.length; i++) {

					var user = '';
					if (json[i]['cp']  > 50) {
						user += '';
					} else {
						user += '';
					}
					user += json[i]['user'];
					user += '';

					data.push([
						json[i]['pid'],
						user,
						json[i]['cp'],
						json[i]['mem'],
						json[i]['command'][0],
						json[i]['command'].join(' ')
					]);
				}
				console.log(data);
				return data;
			},
			headers: {
				'X-CSRFToken': csrf
			},
			cache: false,
			data: {
				'server': server,
				'secret': secret
			}
		}
	}); //dataTable function end
}

function cpu_usage_set (csrf, server, secret) {
	var address = '/ajax/server/' + server + '/metrics/cpu_usage/';
	var lastValue = null;

	function requestCpuUsageData(series, lastValue, csrf, server, secret) {
		var address = '/ajax/server/' + server + '/metrics/cpu_usage/';
		$.ajax({
			url: address,
			type: 'POST',
			dataType: 'json',
			headers: {
				'X-CSRFToken': csrf
			},
			cache: false,
			data: {
				'server': server,
				'secret': secret,
				'lastvalue': lastValue
			},
			success: function(data) {
				if (typeof element === 'undefined') {
					var element = [null, null];
				}

				if (data[0] != element[0]) {
					series.addPoint(data[0], true, true);
					element[0] = data[0];
				}
			},
			error: function(data, textStatus, errorThrown) {
				console.log('error: ' + textStatus);
				console.log('error: ' + errorThrown);
			}
		});
	}

	function updateCpuUsageChart(series, lastValue, csrf, server, secret) {
		setInterval(function() {
			requestCpuUsageData(series, lastValue, csrf, server, secret);
		}, 1000);
	}

	Highcharts.setOptions({
		global: {
			useUTC: false
		}
	});

	$.ajax({
		url: address,
		type: 'POST',
		dataType: 'json',
		headers: {
			'X-CSRFToken': csrf
		},
		cache: false,
		data: {
			'server': server,
			'secret': secret,
			'lastvalue': lastValue
		},
		success: function(data) {
			console.log('naplneni daty');
			if (data != null) {
				var optionalData = [];
				var optionalLength = 30;
				console.log(data);
				var dataLength = data.length;
				data.reverse();
				for(var i = 0; i < (optionalLength - dataLength); i++) {
					optionalData.push([
							(data[0][0] - (i + 1) * 5),
							null
						]);
				}
				optionalData = optionalData.concat(data);
				var cpuUsageChart = new Highcharts.Chart({
					chart: {
						renderTo: 'cpu_usage',
						events: {
							load: function() {
								updateCpuUsageChart(
									this.series[0],
									data[0][0],
									csrf,
									server,
									secret
								);
							}
						}
					},
					title: {
						text: 'CPU Usage'
					},
					xAxis: {
						type: 'datetime',
						labels: {
							formatter: function() {
								return Highcharts.dateFormat('%H:%M:%S', this.value * 1000);
							}
						}
					},
					yAxis: {
						title: {
							text: 'Value'
						},
					plotLines: [{
						value: 0,
						width: 1,
						color: '#808080'
					}]
					},
					tooltip: {
						formatter: function () {
							return '' + Highcharts.numberFormat(this.y, 0) + this.series.name + '
' +
								Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x*1000);

						}
					},
					legend: {
						enabled: false
					},
					exporting: {
						enabled: false
					},
					series: [{
						name: '% CPU used',
						data: optionalData,
						zones: [{
								value: 10,
								color: '#7cb5ec'
							}, {
								value: 80,
								color: '#90ed7d'
							},{
								value: 95,
								color: 'orange'
							},{
								color: 'red'
							}
						]
					}]
				});
			}
		},
		error: function(data, textStatus, errorThrown) {
			console.log('error: ' + textStatus);
			console.log('error: ' + errorThrown);
		}
	});
}

function loadavg_set (csrf, server, secret)
{
	/*
	function requestLoadAvgData(series, csrf, server, secret) {
		var address = '/ajax/server/' + server + '/metrics/loadavg/';
		$.ajax({
			url: address,
			type: 'POST',
			dataType: 'json',
			headers: {
				'X-CSRFToken': csrf
			},
			cache: false,
			data: {
				'server': server,
			'secret': secret
			},
			success: function(data) {
				if (typeof element === 'undefined') {
					var element = [null,null];
				}

				if (element[0] != data[0]) {
					series.addPoint(data[0], true, true);
				}

				element [0] = data [0];
			},
			error: function(data, textStatus, errorThrown) {
				console.log('error: ' + textStatus);
				console.log('error: ' + errorThrown);
			}
		});
	}

	function updateLoadAvgChart(series, csrf, server, secret) {
		setInterval(function() {
			requestLoadAvgData(series, csrf, server, secret);
		}, 1000);
	}

	$.ajax({
		url: address,
		type: 'POST',
		dataType: 'json',
		headers: {
			'X-CSRFToken': csrf
		},
		cache: false,
		data: {
			'server': server,
			'secret': secret
		},
		success: function(data) {
			var cpuUsageChart = new Highcharts.Chart({
				chart: {
					renderTo: 'cpu_usage',
			events: {
				load: function() {
					updateChart(this.series[0], csrf, server, secret);
				}
			}
				},
			title: {
				text: 'CPU Usage'
			},
			xAxis: {
				type: 'datetime',
			tickPixelInterval: 1000
			},
			yAxis: {
				title: {
					text: 'Value'
				},
			plotLines: [{
				value: 0,
				width: 1,
				color: '#808080'
			}]
			},
			tooltip: {
				formatter: function () {
					return '' + this.series.name + '
' +
						Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '
' +
						Highcharts.numberFormat(this.y, 2);
				}
			},
			legend: {
				enabled: false
			},
			exporting: {
				enabled: false
			},
			series: [{
				name: '%CPU Usage',
				data: data.reverse()
			}]
			});
		},
		error: function(data, textStatus, errorThrown) {
			console.log('error: ' + textStatus);
			console.log('error: ' + errorThrown);
		}
	});
	*/
}
<commit_msg>Added new response data manipulations<commit_after>$(function () {
	$(document).ready(function () {
		var server = $('input[name="hwaddr"]').val();
		var csrf = $('input[name="csrfmiddlewaretoken"]').val();
		var secret = $('input[name="secret"]').val();

		cpu_usage_set(csrf, server, secret);
		processes(csrf, server, secret);
//		loadavg_set (csrf, server, secret);
	});
});

function processes(csrf, server, secret) {
	var address = '/ajax/server/' + server + '/metrics/processes/';

	$('#running_processes_table').dataTable({
		lengthMenu: [[15, 50, 100], [15, 50, 100]],
		order: [[ 2, "desc" ]],
		draw: 1,
		processing: true,
		serverSide: true,
		ajax: {
			url: address,
			type: 'POST',
			dataType: 'json',
			dataSrc: function(json) {
				var data = [];
				for (var i = 0; i < json.data.length; i++) {

					var user = '';
					if (json.data[i]['cpu']  > 50) {
						user += '';
					} else {
						user += '';
					}
					user += json.data[i]['user'];
					user += '';

					data.push([
						json.data[i]['pid'],
						user,
						json.data[i]['cpu'],
						json.data[i]['mem'],
						json.data[i]['command'][0]
							.replace('[','')
							.replace(']',''),
						json.data[i]['command'].join(' ')
							.replace('[','')
							.replace(']','')
					]);
				}
				console.log(data);
				return data;
			},
			headers: {
				'X-CSRFToken': csrf
			},
			cache: false,
			data: {
				'server': server,
				'secret': secret
			}
		}
	}); //dataTable function end
}

function cpu_usage_set (csrf, server, secret) {
	var address = '/ajax/server/' + server + '/metrics/cpu_usage/';
	var lastValue = null;

	function requestCpuUsageData(series, lastValue, csrf, server, secret) {
		var address = '/ajax/server/' + server + '/metrics/cpu_usage/';
		$.ajax({
			url: address,
			type: 'POST',
			dataType: 'json',
			headers: {
				'X-CSRFToken': csrf
			},
			cache: false,
			data: {
				'server': server,
				'secret': secret,
				'lastvalue': lastValue
			},
			success: function(data) {
				if (typeof element === 'undefined') {
					var element = [null, null];
				}

				if (data[0] != element[0]) {
					series.addPoint(data[0], true, true);
					element[0] = data[0];
				}
			},
			error: function(data, textStatus, errorThrown) {
				console.log('error: ' + textStatus);
				console.log('error: ' + errorThrown);
			}
		});
	}

	function updateCpuUsageChart(series, lastValue, csrf, server, secret) {
		setInterval(function() {
			requestCpuUsageData(series, lastValue, csrf, server, secret);
		}, 1000);
	}

	Highcharts.setOptions({
		global: {
			useUTC: false
		}
	});

	$.ajax({
		url: address,
		type: 'POST',
		dataType: 'json',
		headers: {
			'X-CSRFToken': csrf
		},
		cache: false,
		data: {
			'server': server,
			'secret': secret,
			'lastvalue': lastValue
		},
		success: function(data) {
			console.log('naplneni daty');
			if (data != null) {
				var optionalData = [];
				var optionalLength = 30;
				console.log(data);
				var dataLength = data.length;
				data.reverse();
				for(var i = 0; i < (optionalLength - dataLength); i++) {
					optionalData.push([
							(data[0][0] - (i + 1) * 5),
							null
						]);
				}
				optionalData = optionalData.concat(data);
				var cpuUsageChart = new Highcharts.Chart({
					chart: {
						renderTo: 'cpu_usage',
						events: {
							load: function() {
								updateCpuUsageChart(
									this.series[0],
									data[0][0],
									csrf,
									server,
									secret
								);
							}
						}
					},
					title: {
						text: 'CPU Usage'
					},
					xAxis: {
						type: 'datetime',
						labels: {
							formatter: function() {
								return Highcharts.dateFormat('%H:%M:%S', this.value * 1000);
							}
						}
					},
					yAxis: {
						title: {
							text: 'Value'
						},
					plotLines: [{
						value: 0,
						width: 1,
						color: '#808080'
					}]
					},
					tooltip: {
						formatter: function () {
							return '' + Highcharts.numberFormat(this.y, 0) + this.series.name + '
' +
								Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x*1000);

						}
					},
					legend: {
						enabled: false
					},
					exporting: {
						enabled: false
					},
					series: [{
						name: '% CPU used',
						data: optionalData,
						zones: [{
								value: 10,
								color: '#7cb5ec'
							}, {
								value: 80,
								color: '#90ed7d'
							},{
								value: 95,
								color: 'orange'
							},{
								color: 'red'
							}
						]
					}]
				});
			}
		},
		error: function(data, textStatus, errorThrown) {
			console.log('error: ' + textStatus);
			console.log('error: ' + errorThrown);
		}
	});
}

function loadavg_set (csrf, server, secret)
{
	/*
	function requestLoadAvgData(series, csrf, server, secret) {
		var address = '/ajax/server/' + server + '/metrics/loadavg/';
		$.ajax({
			url: address,
			type: 'POST',
			dataType: 'json',
			headers: {
				'X-CSRFToken': csrf
			},
			cache: false,
			data: {
				'server': server,
			'secret': secret
			},
			success: function(data) {
				if (typeof element === 'undefined') {
					var element = [null,null];
				}

				if (element[0] != data[0]) {
					series.addPoint(data[0], true, true);
				}

				element [0] = data [0];
			},
			error: function(data, textStatus, errorThrown) {
				console.log('error: ' + textStatus);
				console.log('error: ' + errorThrown);
			}
		});
	}

	function updateLoadAvgChart(series, csrf, server, secret) {
		setInterval(function() {
			requestLoadAvgData(series, csrf, server, secret);
		}, 1000);
	}

	$.ajax({
		url: address,
		type: 'POST',
		dataType: 'json',
		headers: {
			'X-CSRFToken': csrf
		},
		cache: false,
		data: {
			'server': server,
			'secret': secret
		},
		success: function(data) {
			var cpuUsageChart = new Highcharts.Chart({
				chart: {
					renderTo: 'cpu_usage',
			events: {
				load: function() {
					updateChart(this.series[0], csrf, server, secret);
				}
			}
				},
			title: {
				text: 'CPU Usage'
			},
			xAxis: {
				type: 'datetime',
			tickPixelInterval: 1000
			},
			yAxis: {
				title: {
					text: 'Value'
				},
			plotLines: [{
				value: 0,
				width: 1,
				color: '#808080'
			}]
			},
			tooltip: {
				formatter: function () {
					return '' + this.series.name + '
' +
						Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '
' +
						Highcharts.numberFormat(this.y, 2);
				}
			},
			legend: {
				enabled: false
			},
			exporting: {
				enabled: false
			},
			series: [{
				name: '%CPU Usage',
				data: data.reverse()
			}]
			});
		},
		error: function(data, textStatus, errorThrown) {
			console.log('error: ' + textStatus);
			console.log('error: ' + errorThrown);
		}
	});
	*/
}
<|endoftext|>