<commit_before>/**
 * ownCloud - Audio Player
 *
 * @author Marcel Scherello
 * @author Sebastian Doell
 * @copyright 2015 sebastian doell sebastian@libasys.de
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see http://www.gnu.org/licenses.
 *
 */

var audioPlayer = {
	mime : null,
	file : null,
	location : null,
	player : null,
	dir: null,
	onView : function(file, data) {
		file = encodeURIComponent(file);
		audioPlayer.file = file;
		audioPlayer.dir = data.dir;
		//sharingToken
		var token = ($('#sharingToken').val() !== undefined) ? $('#sharingToken').val() : '';
		//.thumbnail
		var dirLoad=data.dir.substr(1);
		if(dirLoad!=''){
			dirLoad=dirLoad+'/';
		}
		if(token !== ''){
			audioPlayer.location = OC.generateUrl('apps/audioplayer/getpublicaudiostream{file}?token={token}',{'file':dirLoad+file,'token':token},{escape:false});
		}else{
			audioPlayer.location = OC.generateUrl('apps/audioplayer/getaudiostream?file={file}',{'file':dirLoad+file},{escape:false});

		}
		audioPlayer.mime = data.$file.attr('data-mime');
		data.$file.find('.thumbnail').html('');

		if(audioPlayer.player == null){
			soundManager.setup({
			  url:OC.filePath('audioplayer', 'js', 'soundmanager2.swf'),
		  onready: function() {
			    audioPlayer.player = soundManager.createSound({
			      id:data.$file.attr('data-id'),
			      url: audioPlayer.location
			    });

			    	audioPlayer.player.play();

			  },
			  ontimeout: function() {
			    // Hrmm, SM2 could not start. Missing SWF? Flash blocked? Show an error, etc.?
			  }
			});
		}else{
			audioPlayer.player.stop();
			$('#filestable').find('.thumbnail i.ioc-pause').hide();
			$('#filestable').find('.thumbnail i.ioc-play').show();
			audioPlayer.player=null;
		}

	},
};
$(document).ready(function() {
	if (OCA.Files && OCA.Files.fileActions) {

		OCA.Files.fileActions.registerAction({
			name: 'audioplayer play',
			displayName: t('audioplayer', 'Play'),
			mime: 'audio/mpeg',
			permissions: OC.PERMISSION_READ,
			icon: function () {return OC.imagePath('core', 'actions/sound');},
			actionHandler: audioPlayer.onView
		});

		OCA.Files.fileActions.register('audio/mpeg', 'View', OC.PERMISSION_READ, '', audioPlayer.onView);
		OCA.Files.fileActions.setDefault('audio/mpeg', 'View');

		OCA.Files.fileActions.registerAction({
			name: 'audioplayer play',
			displayName: t('audioplayer', 'Play'),
			mime: 'audio/mp4',
			permissions: OC.PERMISSION_READ,
			icon: function () {return OC.imagePath('core', 'actions/sound');},
			actionHandler: audioPlayer.onView
		});

		OCA.Files.fileActions.register('audio/mp4', 'View', OC.PERMISSION_READ, '', audioPlayer.onView);
		OCA.Files.fileActions.setDefault('audio/mp4', 'View');

		OCA.Files.fileActions.registerAction({
			name: 'audioplayer play',
			displayName: t('audioplayer', 'Play'),
			mime: 'audio/m4b',
			permissions: OC.PERMISSION_READ,
			icon: function () {return OC.imagePath('core', 'actions/sound');},
			actionHandler: audioPlayer.onView
		});

		OCA.Files.fileActions.register('audio/m4b', 'View', OC.PERMISSION_READ, '', audioPlayer.onView);
		OCA.Files.fileActions.setDefault('audio/m4b', 'View');

		OCA.Files.fileActions.registerAction({
			name: 'audioplayer play',
			displayName: t('audioplayer', 'Play'),
			mime: 'audio/ogg',
			permissions: OC.PERMISSION_READ,
			icon: function () {return OC.imagePath('core', 'actions/sound');},
			actionHandler: audioPlayer.onView
		});

		OCA.Files.fileActions.register('audio/ogg', 'View', OC.PERMISSION_READ, '', audioPlayer.onView);
		OCA.Files.fileActions.setDefault('audio/ogg', 'View');

		if($('#header').hasClass('share-file')){

			var token = ($('#sharingToken').val() !== undefined) ? $('#sharingToken').val() : '';
			var mimeType=$('#mimetype').val();
			if(mimeType === 'audio/mpeg'){

			OC.addStyle('audioplayer','360player');
			OC.addStyle('audioplayer','360player-visualization');

			$('#imgframe').css({'width':'250px'});
			setTimeout(function(){ $('#imgframe').children().first().css({'width':'250px'}); }, 2000);

			if( $('#previewSupported').val() !== 'true'){
				$('#imgframe').hide();
			}
			//$('#imgframe').append($('
'));
			var fileName=$('#filename').val();
			fileName = encodeURIComponent(fileName);
			var audioUrl= OC.generateUrl('apps/audioplayer/getpublicaudiostream{file}?token={token}',{'file':fileName,'token':token},{escape:false});
			var audioContainer=$('
').attr('id','sm2-container');

			$('#preview').before(audioContainer);
			var audioOuterDiv=$('
').addClass('outer-audioplayer').css('clear','both');
			var audioInnerDiv=$('
').addClass('ui360 ui360-vis');
			var audioLink=$('').attr({
				'href':audioUrl
			}).text($('#filename').val());
			audioInnerDiv.append(audioLink);
			audioOuterDiv.append(audioInnerDiv);
			audioContainer.append(audioOuterDiv);
			OC.addScript('audioplayer','berniecode-animator',function(){
				OC.addScript('audioplayer','360player',function(){
					soundManager.setup({
					  url:'./apps/audioplayer/js/',
					 });

				});
			});
		}

		}
		//$(document).keydown(videoCoolViewer.onKeyDown);
	}
});
<commit_msg>more visible playing indicator in files app<commit_after>/**
 * ownCloud - Audio Player
 *
 * @author Marcel Scherello
 * @author Sebastian Doell
 * @copyright 2015 sebastian doell sebastian@libasys.de
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see http://www.gnu.org/licenses.
 *
 */

var audioPlayer = {
	mime : null,
	file : null,
	location : null,
	player : null,
	dir: null,
	onView : function(file, data) {
		file = encodeURIComponent(file);
		audioPlayer.file = file;
		audioPlayer.dir = data.dir;
		//sharingToken
		var token = ($('#sharingToken').val() !== undefined) ? $('#sharingToken').val() : '';
		//.thumbnail
		var dirLoad=data.dir.substr(1);
		if(dirLoad!=''){
			dirLoad=dirLoad+'/';
		}
		if(token !== ''){
			audioPlayer.location = OC.generateUrl('apps/audioplayer/getpublicaudiostream{file}?token={token}',{'file':dirLoad+file,'token':token},{escape:false});
		}else{
			audioPlayer.location = OC.generateUrl('apps/audioplayer/getaudiostream?file={file}',{'file':dirLoad+file},{escape:false});

		}
		audioPlayer.mime = data.$file.attr('data-mime');
		data.$file.find('.thumbnail').html('');

		if(audioPlayer.player == null){
			soundManager.setup({
			  url:OC.filePath('audioplayer', 'js', 'soundmanager2.swf'),
		  onready: function() {
			    audioPlayer.player = soundManager.createSound({
			      id:data.$file.attr('data-id'),
			      url: audioPlayer.location
			    });

			    	audioPlayer.player.play();

			  },
			  ontimeout: function() {
			    // Hrmm, SM2 could not start. Missing SWF? Flash blocked? Show an error, etc.?
			  }
			});
		}else{
			audioPlayer.player.stop();
			$('#filestable').find('.thumbnail i.ioc-volume-up').hide();
			//$('#filestable').find('.thumbnail i.ioc-play').show();
			audioPlayer.player=null;
		}

	},
};
$(document).ready(function() {
	if (OCA.Files && OCA.Files.fileActions) {

		OCA.Files.fileActions.registerAction({
			name: 'audioplayer play',
			displayName: t('audioplayer', 'Play'),
			mime: 'audio/mpeg',
			permissions: OC.PERMISSION_READ,
			icon: function () {return OC.imagePath('core', 'actions/sound');},
			actionHandler: audioPlayer.onView
		});

		OCA.Files.fileActions.register('audio/mpeg', 'View', OC.PERMISSION_READ, '', audioPlayer.onView);
		OCA.Files.fileActions.setDefault('audio/mpeg', 'View');

		OCA.Files.fileActions.registerAction({
			name: 'audioplayer play',
			displayName: t('audioplayer', 'Play'),
			mime: 'audio/mp4',
			permissions: OC.PERMISSION_READ,
			icon: function () {return OC.imagePath('core', 'actions/sound');},
			actionHandler: audioPlayer.onView
		});

		OCA.Files.fileActions.register('audio/mp4', 'View', OC.PERMISSION_READ, '', audioPlayer.onView);
		OCA.Files.fileActions.setDefault('audio/mp4', 'View');

		OCA.Files.fileActions.registerAction({
			name: 'audioplayer play',
			displayName: t('audioplayer', 'Play'),
			mime: 'audio/m4b',
			permissions: OC.PERMISSION_READ,
			icon: function () {return OC.imagePath('core', 'actions/sound');},
			actionHandler: audioPlayer.onView
		});

		OCA.Files.fileActions.register('audio/m4b', 'View', OC.PERMISSION_READ, '', audioPlayer.onView);
		OCA.Files.fileActions.setDefault('audio/m4b', 'View');

		OCA.Files.fileActions.registerAction({
			name: 'audioplayer play',
			displayName: t('audioplayer', 'Play'),
			mime: 'audio/ogg',
			permissions: OC.PERMISSION_READ,
			icon: function () {return OC.imagePath('core', 'actions/sound');},
			actionHandler: audioPlayer.onView
		});

		OCA.Files.fileActions.register('audio/ogg', 'View', OC.PERMISSION_READ, '', audioPlayer.onView);
		OCA.Files.fileActions.setDefault('audio/ogg', 'View');

		if($('#header').hasClass('share-file')){

			var token = ($('#sharingToken').val() !== undefined) ? $('#sharingToken').val() : '';
			var mimeType=$('#mimetype').val();
			if(mimeType === 'audio/mpeg'){

			OC.addStyle('audioplayer','360player');
			OC.addStyle('audioplayer','360player-visualization');

			$('#imgframe').css({'width':'250px'});
			setTimeout(function(){ $('#imgframe').children().first().css({'width':'250px'}); }, 2000);

			if( $('#previewSupported').val() !== 'true'){
				$('#imgframe').hide();
			}
			//$('#imgframe').append($('
'));
			var fileName=$('#filename').val();
			fileName = encodeURIComponent(fileName);
			var audioUrl= OC.generateUrl('apps/audioplayer/getpublicaudiostream{file}?token={token}',{'file':fileName,'token':token},{escape:false});
			var audioContainer=$('
').attr('id','sm2-container');

			$('#preview').before(audioContainer);
			var audioOuterDiv=$('
').addClass('outer-audioplayer').css('clear','both');
			var audioInnerDiv=$('
').addClass('ui360 ui360-vis');
			var audioLink=$('').attr({
				'href':audioUrl
			}).text($('#filename').val());
			audioInnerDiv.append(audioLink);
			audioOuterDiv.append(audioInnerDiv);
			audioContainer.append(audioOuterDiv);
			OC.addScript('audioplayer','berniecode-animator',function(){
				OC.addScript('audioplayer','360player',function(){
					soundManager.setup({
					  url:'./apps/audioplayer/js/',
					 });

				});
			});
		}

		}
		//$(document).keydown(videoCoolViewer.onKeyDown);
	}
});
<|endoftext|>


<commit_before>var zindex = 0;
var screenHeight = window.innerHeight;
var screenWidth = window.innerWidth;
var maxHeight = Math.floor(screenHeight / 3), minHeight = Math.floor(screenHeight / 5);
var maxWidth = Math.floor(screenWidth / 3), minWidth = Math.floor(screenWidth / 5);

// square-window mappings
var relations = {
    "home": {
        "windId": "home_window",
        "dims": {
            "initHeight": "",
            "initWidth": "",
            "prevHeight": "",
            "prevWidth": ""
        },
    },
    "internet": {
        "windId": "internet_window",
        "dims": {
            "initHeight": "",
            "initWidth": "",
            "prevHeight": "",
            "prevWidth": ""
        },
    },
    "pictures": {
        "windId": "pic_window",
        "dims": {
            "initHeight": 340,
            "initWidth": 420,
            "prevHeight": 340,
            "prevWidth": 420
        },
    },
    "videos": {
        "windId": "vid_window",
        "dims": {
            "initHeight": 485,
            "initWidth": 625,
            "prevHeight": 485,
            "prevWidth": 625
        },
    },
    "game": {
        "windId": "game_window",
        "dims": {
            "initHeight": 675,
            "initWidth": 750,
            "prevHeight": 675,
            "prevWidth": 750
        },
    },
    "folder": {
        "windId": "folder_window",
        "dims": {
            "initHeight": 470,
            "initWidth": 620,
            "prevHeight": 470,
            "prevWidth": 620
        },
    }
}

var tempId;
$(document).ready(function() {
    $(".window").addClass("new");

    $(".resize-drag").draggable({
        drag: function(event) { bringForward(this); },
        containment: "window"
    });

    for(var squareId in relations) {
        var windId = "#" + relations[squareId].windId;
        $(windId).resizable({
            resize: function(event) {
                relations[squareId].dims.prevHeight = $(this).height();
                relations[squareId].dims.prevWidth = $(this).width();
            },
            minHeight: relations[squareId].dims.initHeight,
            minWidth: relations[squareId].dims.initWidth
        })
    }

    $(".square").click(function() {
        $(this).css("background", "Red");
        var squareId = $(this).attr("id");
        openWindow(relations[squareId].windId);
    });

    $(".exit, .min").click(function() {
        var windId = "#" + $(this).parent().parent().attr("id");
        hideWindow(windId);
        if($(this).attr("class") === "exit") {
            if(windId === "#vid_window") { $("#vid").get(0).load(); }
            $(windId).removeClass("opened");
            var squareId = "#" + getSquare($(windId).attr("id"));
            $(squareId).css("background", "rgba(255, 255, 255, 0.6)");
        }
    });

    $(".window").click(function() {
        bringForward(this);
    });
});

function openWindow(windId) {
    zindex++;
    windId = "#" + windId;
    var css = { "display": "block", "position": "absolute", "z-index": zindex };

    if(!($(windId).hasClass("opened"))) {
        // open closed window
        $(windId).addClass("opened");
        $(windId).addClass("active");

        if(windId === "#pic_window") {
            $("#image_slider").css({"width": "5460px"});
        }

        // randomize position only when opened the first time
        if($(windId).hasClass("new")) {
            css.top = Math.floor(Math.random() * (maxHeight - minHeight + 1)) + minHeight + "px";
            css.left = Math.floor(Math.random() * (maxWidth - minWidth + 1)) + minWidth + "px";
            $(windId).removeClass("new");
        }
        $(windId).css(css);
    } else if(!$(windId).hasClass("active")) {
        // reactivate minimized window
        $(windId).addClass("active");
        $(windId).css(css);
    } else {
        // minimize active window
        hideWindow(windId);
    }
}

function getSquare(windId) {
    for(var squareId in relations) {
        if(relations[squareId].windId === windId) { return squareId; }
    }
}

function bringForward(wind) {
    zindex++;
    $(wind).css({"z-index": zindex});
}

function hideWindow(windId) {
    $(windId).css("display", "none");
    $(windId).removeClass("active");
}<commit_msg>fixed background replacement on button click/window action<commit_after>var zindex = 0;
var screenHeight = window.innerHeight;
var screenWidth = window.innerWidth;
var maxHeight = Math.floor(screenHeight / 3), minHeight = Math.floor(screenHeight / 5);
var maxWidth = Math.floor(screenWidth / 3), minWidth = Math.floor(screenWidth / 5);

// square-window mappings
var relations = {
    "home": {
        "windId": "home_window",
        "dims": {
            "initHeight": "",
            "initWidth": "",
            "prevHeight": "",
            "prevWidth": ""
        },
    },
    "internet": {
        "windId": "internet_window",
        "dims": {
            "initHeight": "",
            "initWidth": "",
            "prevHeight": "",
            "prevWidth": ""
        },
    },
    "pictures": {
        "windId": "pic_window",
        "dims": {
            "initHeight": 340,
            "initWidth": 420,
            "prevHeight": 340,
            "prevWidth": 420
        },
    },
    "videos": {
        "windId": "vid_window",
        "dims": {
            "initHeight": 485,
            "initWidth": 625,
            "prevHeight": 485,
            "prevWidth": 625
        },
    },
    "game": {
        "windId": "game_window",
        "dims": {
            "initHeight": 675,
            "initWidth": 750,
            "prevHeight": 675,
            "prevWidth": 750
        },
    },
    "folder": {
        "windId": "folder_window",
        "dims": {
            "initHeight": 470,
            "initWidth": 620,
            "prevHeight": 470,
            "prevWidth": 620
        },
    }
}

var tempId;
$(document).ready(function() {
    $(".window").addClass("new");

    $(".resize-drag").draggable({
        drag: function(event) { bringForward(this); },
        containment: "window"
    });

    for(var squareId in relations) {
        var windId = "#" + relations[squareId].windId;
        $(windId).resizable({
            resize: function(event) {
                relations[squareId].dims.prevHeight = $(this).height();
                relations[squareId].dims.prevWidth = $(this).width();
            },
            minHeight: relations[squareId].dims.initHeight,
            minWidth: relations[squareId].dims.initWidth
        })
    }

    $(".square").click(function() {
        $(this).css("background-color", "Red");
        var squareId = $(this).attr("id");
        openWindow(relations[squareId].windId);
    });

    $(".exit, .min").click(function() {
        var windId = "#" + $(this).parent().parent().attr("id");
        hideWindow(windId);
        if($(this).attr("class") === "exit") {
            if(windId === "#vid_window") { $("#vid").get(0).load(); }
            $(windId).removeClass("opened");
            var squareId = "#" + getSquare($(windId).attr("id"));
            $(squareId).css("background-color", "rgba(255, 255, 255, 0.6)");
        }
    });

    $(".window").click(function() {
        bringForward(this);
    });
});

function openWindow(windId) {
    zindex++;
    windId = "#" + windId;
    var css = { "display": "block", "position": "absolute", "z-index": zindex };

    if(!($(windId).hasClass("opened"))) {
        // open closed window
        $(windId).addClass("opened");
        $(windId).addClass("active");

        if(windId === "#pic_window") {
            $("#image_slider").css({"width": "5460px"});
        }

        // randomize position only when opened the first time
        if($(windId).hasClass("new")) {
            css.top = Math.floor(Math.random() * (maxHeight - minHeight + 1)) + minHeight + "px";
            css.left = Math.floor(Math.random() * (maxWidth - minWidth + 1)) + minWidth + "px";
            $(windId).removeClass("new");
        }
        $(windId).css(css);
    } else if(!$(windId).hasClass("active")) {
        // reactivate minimized window
        $(windId).addClass("active");
        $(windId).css(css);
    } else {
        // minimize active window
        hideWindow(windId);
    }
}

function getSquare(windId) {
    for(var squareId in relations) {
        if(relations[squareId].windId === windId) { return squareId; }
    }
}

function bringForward(wind) {
    zindex++;
    $(wind).css({"z-index": zindex});
}

function hideWindow(windId) {
    $(windId).css("display", "none");
    $(windId).removeClass("active");
}<|endoftext|>


<commit_before>/*Global abatement */
var jscompare = jscompare || {};
jscompare.contentPrefs = jscompare.contentPrefs || {};
jscompare.utils = jscompare.utils || {};

/*Create instance for Levenshtein scoring */
jscompare.contentPrefs.scoreObject = new diff_match_patch();

/* Score weighting for individual word matches */
jscompare.contentPrefs.compareWordsConf = {
	weighting : 10,
	rejectThreshold : 5
}

/* ************* */
/* MAIN FUNCTION */
/* ************* */

jscompare.contentPrefs.analyseContent = function analyseContent(primaryString, secondaryString) {

	/* Attributes */
	this.primaryWordList = primaryString.split(' ');
	this.secondaryWordList = secondaryString.split(' ');
	this.primaryPhrasePermutations = {}
	this.secondaryPhrasePermutations = {}
	jscompare.contentPrefs.matchScore = null;
	jscompare.contentPrefs.matchesList = {}

	/* Methods */

	/* Natural logarithm - function obtained from internet but unable to relocate source */
	this.ln = function ln(val) {
		return Math.log(val) / Math.LOG10E;
	}

	this.getScore = function getScore(primarySubstring, secondarySubstring) {
		/*Return Levenshtein score */
		return jscompare.contentPrefs.scoreObject.diff_levenshtein(jscompare.contentPrefs.scoreObject.diff_main(primarySubstring, secondarySubstring));
	}
	/* Return comparative scores on individual word or phrase combinations */
	this.compareSubtext = function compareSubtext(primaryArray, secondaryArray) {
		/* for each primary text related word */
		primaryArray.forEach(function(primaryItem) {
			/* compare that word with each secondary related word in turn and get a match scoring */
			secondaryArray.forEach(function(secondaryItem) {
				jscompare.contentPrefs.matchScore = that.getScore(primaryItem, secondaryItem);
				/* check if the levenshtein score is low enough to meet the threshold for a useful match */
				if (jscompare.contentPrefs.matchScore <= jscompare.contentPrefs.compareWordsConf.rejectThreshold) {
					/* determine if match is new or scores less than an existing match */
					if (jscompare.contentPrefs.matchesList[primaryItem] === undefined || (25 / that.ln(jscompare.contentPrefs.matchScore + 2)) * (that.ln(primaryItem.length)) > jscompare.contentPrefs.matchesList[primaryItem]) {
						jscompare.contentPrefs.matchesList[primaryItem] = (25 / that.ln(jscompare.contentPrefs.matchScore + 2)) * (that.ln(primaryItem.length));
					}
				}
			})
		})
	}

	var that = this;

	/* Call driver program to return comparative scores */
	this.compareSubtext(this.primaryWordList, this.secondaryWordList);

	return jscompare.contentPrefs.matchesList;
}

/* Calculate the total of all the match scores as a final match total */
jscompare.contentPrefs.CalculateCumulativeMatchScore = function CalculateCumulativeMatchScore(matchesListObject) {
	this.runningScore = 0;
	for (match in matchesListObject) {
		this.runningScore += matchesListObject[match];
	}
	return this.runningScore;
}

<commit_msg>version 1.01<commit_after>/*Global abatement */
var jscompare = jscompare || {};
jscompare = jscompare || {};

/*Create instance for Levenshtein scoring */
jscompare.scoreObject = new diff_match_patch();

/* Score weighting for individual word matches */
jscompare.compareWordsConf = {
	weighting : 10,
	rejectThreshold : 5
}

/* ************* */
/* MAIN FUNCTION */
/* ************* */

jscompare.analyseContent = function analyseContent(primaryString, secondaryString) {

	/* Attributes */
	this.primaryWordList = primaryString.split(' ');
	this.secondaryWordList = secondaryString.split(' ');
	this.primaryPhrasePermutations = {}
	this.secondaryPhrasePermutations = {}
	jscompare.matchScore = null;
	jscompare.matchesList = {}

	/* Methods */

	/* Natural logarithm - function obtained from internet but unable to relocate source */
	this.ln = function ln(val) {
		return Math.log(val) / Math.LOG10E;
	}

	this.getScore = function getScore(primarySubstring, secondarySubstring) {
		/*Return Levenshtein score */
		return jscompare.scoreObject.diff_levenshtein(jscompare.scoreObject.diff_main(primarySubstring, secondarySubstring));
	}
	/* Return comparative scores on individual word or phrase combinations */
	this.compareSubtext = function compareSubtext(primaryArray, secondaryArray) {
		var scoreValue;
		/* for each primary text related word */
		primaryArray.forEach(function(primaryItem) {
			/* compare that word with each secondary related word in turn and get a match scoring */
			secondaryArray.forEach(function(secondaryItem) {
				jscompare.matchScore = that.getScore(primaryItem, secondaryItem);
				/* check if the levenshtein score is low enough to meet the threshold for a useful match */
				if (jscompare.matchScore <= jscompare.compareWordsConf.rejectThreshold) {
					/* determine if match is new or scores less than an existing match */
					scoreValue = (25 / that.ln(jscompare.matchScore + 2)) * (that.ln(primaryItem.length));
					if (jscompare.matchesList[primaryItem] === undefined || scoreValue > jscompare.matchesList[primaryItem]) {
						jscompare.matchesList[primaryItem] = scoreValue;
					}
				}
			})
		})
	}
	var that = this;

	/* Call driver program to return comparative scores */
	this.compareSubtext(this.primaryWordList, this.secondaryWordList);

	return jscompare.matchesList;
}
/* Calculate the total of all the match scores as a final match total */
jscompare.CalculateCumulativeMatchScore = function CalculateCumulativeMatchScore(matchesListObject) {
	this.runningScore = 0;
	for (match in matchesListObject) {
		this.runningScore += matchesListObject[match];
	}
	return this.runningScore;
}

<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.8.0
// edited by alex date on 28/01/2021

$(function() {
  var word_score;
  $("#password").keyup(function() {
    var crack_time, display, passtext, result, word;
    passtext = $(this).val();
    result = zxcvbn(passtext);
    if (passtext.length < 6) {
      let error_message = `<strong style="color:red;">the password must have a length greater than six characters</strong>`
      $("#password_strength").html(error_message);
      return $("#password_alert").fadeIn();
    } else {
      word = word_score(result.score);
      crack_time = result.crack_times_display.online_throttling_100_per_hour;
      if (crack_time === "instant") {
        crack_time = "a second";
      }
      display = `This is ${word} password.`
      $("#password_strength").html(display);
      return $("#password_alert").fadeIn();
    }
  });
  return word_score = function(num_score) {
    num_score = parseInt(num_score);
    console.log("num_score is:", num_score);

    let passwordFeedback = {
      0:{
        color:"#cc1818",
        feedback:"a weak"
      },

      1:{
        color:"#cc1818",
        feedback:"a bad"
      },

      2:{
        color:"#f59105",
        feedback:"a mediocre"
      },

      3:{
        color:"#44ba34",
        feedback:"a strong"
      },
      4:{
        color:"green",
        feedback:"a stronger"
      }
    }

    mappingResult = `<strong style="color:${passwordFeedback[num_score].color};">${passwordFeedback[num_score].feedback}</strong>`
    return mappingResult;
  };
});
<commit_msg>modify password strength message<commit_after>// Generated by CoffeeScript 1.8.0

$(function() {
  var word_score;
  $("#password").keyup(function() {
    var crack_time, display, passtext, result, word;
    passtext = $(this).val();
    result = zxcvbn(passtext);
    if (passtext.length < 6) {
      let error_message = `<strong style="color:red;">the password must have a length greater than six characters</strong>`
      $("#password_strength").html(error_message);
      return $("#password_alert").fadeIn();
    } else {
      word = word_score(result.score);
      crack_time = result.crack_times_display.online_throttling_100_per_hour;
      if (crack_time === "instant") {
        crack_time = "a second";
      }
      display = `This is ${word} password.`
      $("#password_strength").html(display);
      return $("#password_alert").fadeIn();
    }
  });
  return word_score = function(num_score) {
    num_score = parseInt(num_score);
    console.log("num_score is:", num_score);

    let passwordFeedback = {
      0:{
        color:"#cc1818",
        feedback:"a weak"
      },

      1:{
        color:"#cc1818",
        feedback:"a bad"
      },

      2:{
        color:"#f59105",
        feedback:"a mediocre"
      },

      3:{
        color:"#44ba34",
        feedback:"a strong"
      },
      4:{
        color:"green",
        feedback:"a stronger"
      }
    }

    let mappingResult = `<strong style="color:${passwordFeedback[num_score].color};">${passwordFeedback[num_score].feedback}</strong>`
    return mappingResult;
  };
});
<|endoftext|>


<commit_before>/* eslint-env node */
/* global describe, it, browser */

var utils = require("./cardVisualTestUtils");

describe("sap.ui.integration.CardOthersVisualTests", function () {
	"use strict";
	browser.testrunner.currentSuite.meta.controlName = "sap.ui.integration.widgets.Card";

	function focusElement(oConfig) {
		var oElement = utils.getElement(oConfig);
		browser.executeScript("arguments[0].focus()", oElement.getWebElement());
	}

	it("No Header", function () {
		utils.navigateTo("No Header / No Content");

		var aCards = [
			{ id: "i1" },
			{ id: "f3" },
			{ id: "i4", focus: true }
		];

		aCards.forEach(function (oCard) {
			var oElement = {
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "NoHeaderNoContent",
					interaction: "root",
					id: oCard.id
				}
			};

			if (oCard.focus) {
				focusElement(oElement);
			}

			utils.takePictureOfElement(oElement, "1_NoHeader_" + oCard.id);
		});
	});

	it("No Content", function () {
		var aCards = [
			{ id: "i2", focus: true },
			{ id: "i5", focus: true },
			{ id: "i6-error", focus: true }
		];

		aCards.forEach(function (oCard) {
			var oElement = {
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "NoHeaderNoContent",
					interaction: "root",
					id: oCard.id
				}
			};

			if (oCard.focus) {
				focusElement(oElement);
			}

			utils.takePictureOfElement(oElement, "2_NoContent_" + oCard.id);
		});
	});

	it("Error Messages", function () {
		var aCards = [
			{ id: "i7-error", focus: true },
			{ id: "ListNodata-error", focus: true },
			{ id: "TableNodata-error", focus: true },
			{ id: "Custom-error", focus: true },
			{ id: "BadUrl-error", focus: true }
		];

		aCards.forEach(function (oCard) {
			var oElement = {
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "NoHeaderNoContent",
					interaction: "root",
					id: oCard.id
				}
			};

			if (oCard.focus) {
				focusElement(oElement);
			}

			utils.takePictureOfElement(oElement, "3_ErrorMessage_" + oCard.id);
		});

		utils.navigateBack();
	});

	it("Translation", function () {
		utils.navigateTo("Translations & Header Count");

		utils.takePictureOfElement({
			control: {
				viewNamespace: "sap.f.cardsdemo.view.",
				viewName: "Translation",
				interaction: "root",
				id: "card"
			}
		}, "4_Translations");

		utils.navigateBack();
	});

	it("Badges", function () {
		utils.navigateTo("Badges");

		utils.takePictureOfElement({
			control: {
				viewNamespace: "sap.f.cardsdemo.view.",
				viewName: "Badges",
				id: "badgesPage"
			}
		}, "5_Badges");

		utils.navigateBack();
	});

	it("Preview", function () {
		utils.navigateTo("Preview");

		utils.takePictureOfElement({
			control: {
				viewNamespace: "sap.f.cardsdemo.view.",
				viewName: "Preview",
				id: "previewPage"
			}
		}, "6_Preview");

		utils.navigateBack();
	});

	it("Filters", function () {
		utils.navigateTo("Filters");
		var aCardIds = ["card", "cardDateRange", "cardDateRangeParam", "cardDateRangeParam2"];

		aCardIds.forEach(function (sId) {
			utils.takePictureOfElement({
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "Filters",
					interaction: "root",
					id: sId
				}
			}, "7_Filters_" + sId);
		});

		utils.navigateBack();
	});

	it("Pagination", function () {
		utils.navigateTo("Pagination");
		var aCardIds = ["card1", "card2"];

		aCardIds.forEach(function (sId) {
			utils.takePictureOfElement({
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "Pagination",
					interaction: "root",
					id: sId
				}
			}, "8_Pagination_" + sId);
		});

		utils.navigateBack();
	});

	it("Transparent Card", function () {
		utils.navigateTo("Transparent");
		var aCardIds = ["containerCard", "list1", "object1", "todo3"];

		aCardIds.forEach(function (sId) {
			utils.takePictureOfElement({
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "Transparent",
					interaction: "root",
					id: sId
				}
			}, "9_Transparent_Card_" + sId);
		});
	});

	it("Parameters", function () {
		utils.navigateTo("Parameters");
		var aCardIds = ["weatherCard", "manifestOnly", "listCard", "defaultFromManifest", "defaultFromManifestOverwrite"];

		aCardIds.forEach(function (sId) {
			utils.takePictureOfElement({
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "Parameters",
					interaction: "root",
					id: sId
				}
			}, "10_Parameters_" + sId);
		});

		utils.navigateBack();
	});
});
<commit_msg>[INTERNAL][FIX] sap.ui.integration.CardOthersVisualTests: Test is fixed<commit_after>/* eslint-env node */
/* global describe, it, browser */

var utils = require("./cardVisualTestUtils");

describe("sap.ui.integration.CardOthersVisualTests", function () {
	"use strict";
	browser.testrunner.currentSuite.meta.controlName = "sap.ui.integration.widgets.Card";

	function focusElement(oConfig) {
		var oElement = utils.getElement(oConfig);
		browser.executeScript("arguments[0].focus()", oElement.getWebElement());
	}

	it("No Header", function () {
		utils.navigateTo("No Header / No Content");

		var aCards = [
			{ id: "i1" },
			{ id: "f3" },
			{ id: "i4", focus: true }
		];

		aCards.forEach(function (oCard) {
			var oElement = {
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "NoHeaderNoContent",
					interaction: "root",
					id: oCard.id
				}
			};

			if (oCard.focus) {
				focusElement(oElement);
			}

			utils.takePictureOfElement(oElement, "1_NoHeader_" + oCard.id);
		});
	});

	it("No Content", function () {
		var aCards = [
			{ id: "i2", focus: true },
			{ id: "i5", focus: true },
			{ id: "i6-error", focus: true }
		];

		aCards.forEach(function (oCard) {
			var oElement = {
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "NoHeaderNoContent",
					interaction: "root",
					id: oCard.id
				}
			};

			if (oCard.focus) {
				focusElement(oElement);
			}

			utils.takePictureOfElement(oElement, "2_NoContent_" + oCard.id);
		});
	});

	it("Error Messages", function () {
		var aCards = [
			{ id: "i7-error", focus: true },
			{ id: "ListNodata-error", focus: true },
			{ id: "TableNodata-error", focus: true },
			{ id: "Custom-error", focus: true },
			{ id: "BadUrl-error", focus: true }
		];

		aCards.forEach(function (oCard) {
			var oElement = {
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "NoHeaderNoContent",
					interaction: "root",
					id: oCard.id
				}
			};

			if (oCard.focus) {
				focusElement(oElement);
			}

			utils.takePictureOfElement(oElement, "3_ErrorMessage_" + oCard.id);
		});

		utils.navigateBack();
	});

	it("Translation", function () {
		utils.navigateTo("Translations & Header Count");

		utils.takePictureOfElement({
			control: {
				viewNamespace: "sap.f.cardsdemo.view.",
				viewName: "Translation",
				interaction: "root",
				id: "card"
			}
		}, "4_Translations");

		utils.navigateBack();
	});

	it("Badges", function () {
		utils.navigateTo("Badges");

		utils.takePictureOfElement({
			control: {
				viewNamespace: "sap.f.cardsdemo.view.",
				viewName: "Badges",
				id: "badgesPage"
			}
		}, "5_Badges");

		utils.navigateBack();
	});

	it("Preview", function () {
		utils.navigateTo("Preview");

		utils.takePictureOfElement({
			control: {
				viewNamespace: "sap.f.cardsdemo.view.",
				viewName: "Preview",
				id: "previewPage"
			}
		}, "6_Preview");

		utils.navigateBack();
	});

	it("Filters", function () {
		utils.navigateTo("Filters");
		var aCardIds = ["card", "cardDateRange", "cardDateRangeParam", "cardDateRangeParam2"];

		aCardIds.forEach(function (sId) {
			utils.takePictureOfElement({
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "Filters",
					interaction: "root",
					id: sId
				}
			}, "7_Filters_" + sId);
		});

		utils.navigateBack();
	});

	it("Pagination", function () {
		utils.navigateTo("Pagination");
		var aCardIds = ["card1", "card2"];

		aCardIds.forEach(function (sId) {
			utils.takePictureOfElement({
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "Pagination",
					interaction: "root",
					id: sId
				}
			}, "8_Pagination_" + sId);
		});

		utils.navigateBack();
	});

	it("Transparent Card", function () {
		utils.navigateTo("Transparent");
		var aCardIds = ["containerCard", "list1", "object1", "todo3"];

		aCardIds.forEach(function (sId) {
			utils.takePictureOfElement({
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "Transparent",
					interaction: "root",
					id: sId
				}
			}, "9_Transparent_Card_" + sId);
		});

		utils.navigateBack();
	});

	it("Parameters", function () {
		utils.navigateTo("Parameters");
		var aCardIds = ["weatherCard", "manifestOnly", "listCard", "defaultFromManifest", "defaultFromManifestOverwrite"];

		aCardIds.forEach(function (sId) {
			utils.takePictureOfElement({
				control: {
					viewNamespace: "sap.f.cardsdemo.view.",
					viewName: "Parameters",
					interaction: "root",
					id: sId
				}
			}, "10_Parameters_" + sId);
		});

		utils.navigateBack();
	});
});
<|endoftext|>


<commit_before>    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var w = canvas.width;
    var h = canvas.height;
    var angle = 3 * Math.PI / 180;
    var cx = 200;
    var cy = 75;
    var radius = 40;

    ctx.fillStyle = "skyblue";
    ctx.strokeStyle = "lightgray";

    function draw(x, y) {
        ctx.clearRect(0, 0, w, h);
        ctx.save();
        ctx.beginPath();
        ctx.beginPath();
        ctx.rect(x, y, 50, 30)
        ctx.rect(x - 50 / 2, y - 30 / 2, 50, 30)
        ctx.fill();
        ctx.stroke();
        ctx.restore();
    };

    //keepDrawing();

    function keepDrawing() {

        draw(newX, newY);

        setTimeout(keepDrawing, 250)
    }

    window.requestAnimFrame = (function (callback) {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
            window.setTimeout(callback, 1000 / 60);
        };
    })();

    var fps = 60;

    function animate() {
        setTimeout(function () {
            requestAnimationFrame(animate);

            // increase the angle of rotation
            angle += 3 * Math.PI / 180;

            // calculate the new ball.x / ball.y
            var newX = cx + radius * Math.cos(angle) + 400;
            var newY = cy + radius * Math.sin(angle) + 400;
            // draw
            draw(newX, newY);
            console.log(newX);
	          console.log(newY);
	          Qwek.moveTo(500, 100);

            // draw the centerpoint
            ctx.beginPath();
            ctx.arc(cx, cy, radius, 0, Math.PI * 2, false);
            ctx.closePath();
            ctx.stroke();

        }, 1000 / fps);
    }
    animate();
<commit_msg>Update WinBoundJs.js<commit_after>    	function New_open_win()
        {
          Qwek=window.open("https://omaniamnotgoodwith.computer/side/WindowPullAlt","datshizzle","location=0,status=1,width=700,height=500");
          Qwek.focus()
        }
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var w = canvas.width;
    var h = canvas.height;
    var angle = 3 * Math.PI / 180;
    var cx = 200;
    var cy = 75;
    var radius = 40;

    ctx.fillStyle = "skyblue";
    ctx.strokeStyle = "lightgray";

    function draw(x, y) {
        ctx.clearRect(0, 0, w, h);
        ctx.save();
        ctx.beginPath();
        ctx.beginPath();
        ctx.rect(x, y, 50, 30)
        ctx.rect(x - 50 / 2, y - 30 / 2, 50, 30)
        ctx.fill();
        ctx.stroke();
        ctx.restore();
    };

    //keepDrawing();

    function keepDrawing() {

        draw(newX, newY);

        setTimeout(keepDrawing, 250)
    }

    window.requestAnimFrame = (function (callback) {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
            window.setTimeout(callback, 1000 / 60);
        };
    })();

    var fps = 60;

    function animate() {
        setTimeout(function () {
            requestAnimationFrame(animate);

            // increase the angle of rotation
            angle += 3 * Math.PI / 180;

            // calculate the new ball.x / ball.y
            var newX = cx + radius * Math.cos(angle) + 400;
            var newY = cy + radius * Math.sin(angle) + 400;
            // draw
            draw(newX, newY);
            console.log(newX);
	          console.log(newY);
	          Qwek.moveTo(500, 100);
		          Qwek.focus()

            // draw the centerpoint
            ctx.beginPath();
            ctx.arc(cx, cy, radius, 0, Math.PI * 2, false);
            ctx.closePath();
            ctx.stroke();

        }, 1000 / fps);
    }
    animate();
<|endoftext|>


<commit_before>Object.size = function(obj, t) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    for (key in obj) {
        if (obj[key].deleted == true && t) size--;
    }
    return size;
};

var updateInterval = 10000;
var jsonOld = [];
var model = OpenSprites.models.AssetList($("#collections .main-inner .content"));

function update() {
    $.getJSON(OpenSprites.domain + '/site-api/stuff.php?userid=' + OpenSprites.view.user.id + '&_=' + new Date, function(result) {
        if(JSON.stringify(result) !== JSON.stringify(jsonOld)) {
            jsonOld = result;
            processAjax(result);
        } else if(Object.size(result, true) === 0) {
            $('#collections .main-inner .heading').text("Uploads (None)");
        }

        setTimeout(update, updateInterval);
    });
}

function processAjax(json) {
    $('#collections .main-inner .heading').text('Uploads (' + json.length + ')');
    model.loadJson(json);
}

update();

// blurred background

/**
 * By Ken Fyrstenberg
 *
 * drawImageProp(context, image [, x, y, width, height [,offsetX, offsetY]])
 *
 * If image and context are only arguments rectangle will equal canvas
*/
function drawImageProp(ctx, img, x, y, w, h, offsetX, offsetY) {

    if (arguments.length === 2) {
        x = y = 0;
        w = ctx.canvas.width;
        h = ctx.canvas.height;
    }

    // default offset is center
    offsetX = typeof offsetX === "number" ? offsetX : 0.5;
    offsetY = typeof offsetY === "number" ? offsetY : 0.5;

    // keep bounds [0.0, 1.0]
    if (offsetX < 0) offsetX = 0;
    if (offsetY < 0) offsetY = 0;
    if (offsetX > 1) offsetX = 1;
    if (offsetY > 1) offsetY = 1;

    var iw = img.width,
        ih = img.height,
        r = Math.min(w / iw, h / ih),
        nw = iw * r,   // new prop. width
        nh = ih * r,   // new prop. height
        cx, cy, cw, ch, ar = 1;

    // decide which gap to fill
    if (nw < w) ar = w / nw;
    if (nh < h) ar = h / nh;
    nw *= ar;
    nh *= ar;

    // calc source rectangle
    cw = iw / (nw / w);
    ch = ih / (nh / h);

    cx = (iw - cw) * offsetX;
    cy = (ih - ch) * offsetY;

    // make sure source rectangle is valid
    if (cx < 0) cx = 0;
    if (cy < 0) cy = 0;
    if (cw > iw) cw = iw;
    if (ch > ih) ch = ih;

    // fill image in dest. rectangle
    ctx.drawImage(img, cx, cy, cw, ch,  x, y, w, h);
}

function drawBg(){
	var canvasId = "background-img";
	var canvas = document.getElementById(canvasId);
	if(canvas !== null) {
		var context = canvas.getContext("2d");

		var img = new Image();
		img.onload = function() {
			drawImageProp(context, img);
			stackBlurCanvasRGB(canvas, 0, 0, canvas.width, canvas.height, 10);
		}
		img.src = "/uploads/avatar_blur.php?userid=" + OpenSprites.view.user.id;
	}
}

drawBg();
$(window).resize(drawBg);

/* fancy modal */
$("#settings").click(function() {
    $.get('/users/edit.php', function(data) {
        if(data == 'false') {
            json = {
                bgcolor: 'avatar'
            };
        } else {
            json = JSON.parse(data);
        }

        $('.modal input[name=bgcolor]').val(json.bgcolor == 'avatar' ? 'rgb(101, 149, 147)' : json.bgcolor);
        $('.modal input#bg').val(json.bgcolor == 'avatar');

        $('.modal input[name=bgcolor]').spectrum({
            showButtons: false
        });

        $('.modal input#bg').change(function() {
            var val = $(".modal input#bg:checked").map(function() {return this.value;}).get().join(",");
            console.log(val);
            if(val) {
                $('.modal #bg_true').hide();
            } else {
                $('.modal #bg_true').show();
            }
        });

        $(".modal-overlay, .modal").fadeIn();
    });
});

$('.modal .btn.red').click(function() {
	$(".modal-overlay, .modal").fadeOut();
});<commit_msg>user settings<commit_after>Object.size = function(obj, t) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    for (key in obj) {
        if (obj[key].deleted == true && t) size--;
    }
    return size;
};

var updateInterval = 10000;
var jsonOld = [];
var model = OpenSprites.models.AssetList($("#collections .main-inner .content"));

function update() {
    $.getJSON(OpenSprites.domain + '/site-api/stuff.php?userid=' + OpenSprites.view.user.id + '&_=' + new Date, function(result) {
        if(JSON.stringify(result) !== JSON.stringify(jsonOld)) {
            jsonOld = result;
            processAjax(result);
        } else if(Object.size(result, true) === 0) {
            $('#collections .main-inner .heading').text("Uploads (None)");
        }

        setTimeout(update, updateInterval);
    });
}

function processAjax(json) {
    $('#collections .main-inner .heading').text('Uploads (' + json.length + ')');
    model.loadJson(json);
}

update();

// blurred background

/**
 * By Ken Fyrstenberg
 *
 * drawImageProp(context, image [, x, y, width, height [,offsetX, offsetY]])
 *
 * If image and context are only arguments rectangle will equal canvas
*/
function drawImageProp(ctx, img, x, y, w, h, offsetX, offsetY) {

    if (arguments.length === 2) {
        x = y = 0;
        w = ctx.canvas.width;
        h = ctx.canvas.height;
    }

    // default offset is center
    offsetX = typeof offsetX === "number" ? offsetX : 0.5;
    offsetY = typeof offsetY === "number" ? offsetY : 0.5;

    // keep bounds [0.0, 1.0]
    if (offsetX < 0) offsetX = 0;
    if (offsetY < 0) offsetY = 0;
    if (offsetX > 1) offsetX = 1;
    if (offsetY > 1) offsetY = 1;

    var iw = img.width,
        ih = img.height,
        r = Math.min(w / iw, h / ih),
        nw = iw * r,   // new prop. width
        nh = ih * r,   // new prop. height
        cx, cy, cw, ch, ar = 1;

    // decide which gap to fill
    if (nw < w) ar = w / nw;
    if (nh < h) ar = h / nh;
    nw *= ar;
    nh *= ar;

    // calc source rectangle
    cw = iw / (nw / w);
    ch = ih / (nh / h);

    cx = (iw - cw) * offsetX;
    cy = (ih - ch) * offsetY;

    // make sure source rectangle is valid
    if (cx < 0) cx = 0;
    if (cy < 0) cy = 0;
    if (cw > iw) cw = iw;
    if (ch > ih) ch = ih;

    // fill image in dest. rectangle
    ctx.drawImage(img, cx, cy, cw, ch,  x, y, w, h);
}

function drawBg(){
	var canvasId = "background-img";
	var canvas = document.getElementById(canvasId);
	if(canvas !== null) {
		var context = canvas.getContext("2d");

		var img = new Image();
		img.onload = function() {
			drawImageProp(context, img);
			stackBlurCanvasRGB(canvas, 0, 0, canvas.width, canvas.height, 10);
		}
		img.src = "/uploads/avatar_blur.php?userid=" + OpenSprites.view.user.id;
	}
}

drawBg();
$(window).resize(drawBg);

/* fancy modal */
$("#settings").click(function() {
    $.get('/users/edit.php', function(data) {
        console.log(data);
        if(data == 'false') {
            json = {
                bgcolor: 'avatar'
            };
        } else {
            json = data;
        }

        $('.modal input[name=bgcolor]').val(json.bgcolor == 'avatar' ? 'rgb(101, 149, 147)' : json.bgcolor);
        $('.modal input#bg').val(json.bgcolor == 'avatar');

        $('.modal input[name=bgcolor]').spectrum({
            showButtons: false
        });

        $('.modal input#bg').change(function() {
            var val = $(".modal input#bg:checked").map(function() {return this.value;}).get().join(",");
            console.log(val);
            if(val) {
                $('.modal #bg_true').hide();
            } else {
                $('.modal #bg_true').show();
            }
        });

        $(".modal-overlay, .modal").fadeIn();
    });
});

$('.modal .btn.red').click(function() {
	$(".modal-overlay, .modal").fadeOut();
});<|endoftext|>


<commit_before>;

import angular from 'angular';
import squareImageModule from '../components/square-image';
import won from '../won-es6';
import { attach } from '../utils';
import { labels, relativeTime, updateRelativeTimestamps   } from '../won-label-utils';
import { createSelector } from 'reselect';

const serviceDependencies = ['$scope', '$interval'];
function genComponentConf() {
    let template = `

                <won-square-image src="self.item.titleImgSrc" title="self.item.title"></won-square-image>

{{self.item.title}}

{{self.creationDate}}

                         {{self.item.group}}
                          –

                         {{self.labels.type[self.item.basicNeedType]}}

                        {{ self.unreadConversationsCount() }}

                        {{ self.unreadRequestsCount() }}

                        {{ self.unreadMatchesCount() }}

    `;

    class Controller {
        constructor() {
            attach(this, serviceDependencies, arguments);
            window.pil4dbg = this; //TODO deletme
            this.labels = labels;
            //this.EVENT = won.EVENT;

            updateRelativeTimestamps(
                this.$scope,
                this.$interval,
                this.item.creationDate,
                t => this.creationDate = t);

        }

        unreadXCount(type) {
            return !this.unreadCounts?
                undefined : //ensure existence of count object
                this.unreadCounts.get(type)
        }
        unreadMatchesCount() {
            return this.unreadXCount(won.EVENT.HINT_RECEIVED)
        }
        unreadRequestsCount() {
            return this.unreadXCount(won.EVENT.CONNECT_RECEIVED)
        }
        unreadConversationsCount() {
            return this.unreadXCount(won.EVENT.WON_MESSAGE_RECEIVED)
        }

    }
    Controller.$inject = serviceDependencies;

    return {
        restrict: 'E',
        controller: Controller,
        controllerAs: 'self',
        bindToController: true, //scope-bindings -> ctrl
        scope: {
            item: "=",
            unreadCounts: "="
        },
        template: template
    }
}

export default angular.module('won.owner.components.postItemLine', [
    squareImageModule
])
    .directive('wonPostItemLine', genComponentConf)
    .name;

<commit_msg>disabled tabs on close posts and made greyscale icon (to indicate a close post better)<commit_after>;

import angular from 'angular';
import squareImageModule from '../components/square-image';
import won from '../won-es6';
import { attach } from '../utils';
import { labels, relativeTime, updateRelativeTimestamps   } from '../won-label-utils';
import { createSelector } from 'reselect';

const serviceDependencies = ['$scope', '$interval'];
function genComponentConf() {
    let template = `

                <won-square-image  ng-class="{'inactive' : !self.isActive()}" src="self.item.titleImgSrc" title="self.item.title"></won-square-image>

{{self.item.title}}

{{self.creationDate}}

                         {{self.item.group}}
                          –

                         {{self.labels.type[self.item.basicNeedType]}}

                        {{ self.unreadConversationsCount() }}

                        {{ self.unreadRequestsCount() }}

                        {{ self.unreadMatchesCount() }}

    `;

    class Controller {
        constructor() {
            attach(this, serviceDependencies, arguments);
            window.pil4dbg = this; //TODO deletme
            this.labels = labels;
            //this.EVENT = won.EVENT;

            updateRelativeTimestamps(
                this.$scope,
                this.$interval,
                this.item.creationDate,
                t => this.creationDate = t);

        }

        isActive() {
            return this.item.state === won.WON.Active;
        }

        unreadXCount(type) {
            return !this.unreadCounts?
                undefined : //ensure existence of count object
                this.unreadCounts.get(type)
        }
        unreadMatchesCount() {
            return this.unreadXCount(won.EVENT.HINT_RECEIVED)
        }
        unreadRequestsCount() {
            return this.unreadXCount(won.EVENT.CONNECT_RECEIVED)
        }
        unreadConversationsCount() {
            return this.unreadXCount(won.EVENT.WON_MESSAGE_RECEIVED)
        }

    }
    Controller.$inject = serviceDependencies;

    return {
        restrict: 'E',
        controller: Controller,
        controllerAs: 'self',
        bindToController: true, //scope-bindings -> ctrl
        scope: {
            item: "=",
            unreadCounts: "="
        },
        template: template
    }
}

export default angular.module('won.owner.components.postItemLine', [
    squareImageModule
])
    .directive('wonPostItemLine', genComponentConf)
    .name;

<|endoftext|>


<commit_before>var values;
var phrases;
window.onload = function(){
	chrome.storage.sync.get("userdata", build);
	chrome.storage.sync.get("phraseWhitelist", phraseDisplay);
	chrome.storage.sync.get("whitepage", pageDisplay);

	document.getElementById("xshow").onclick = function(){
		if (document.getElementById("CusList").style.display == "none"){
			document.getElementById("CusList").innerHTML = values.toString().replace(/,/g,"
");
			document.getElementById("CusList").style.display = "inline-block";
			document.getElementById("ListDesc").style.display = "inline-block";

		}else{
			document.getElementById("CusList").style.display = "inline-block";
			document.getElementById("ListDesc").style.display = "inline-block";
		}
		document.getElementById("xshow").style.display = "none";
		document.getElementById("xhide").style.display = "inline";

	}

	document.getElementById("xhide").onclick = function(){
		document.getElementById("CusList").style.display = "none"
		document.getElementById("ListDesc").style.display = "none";
		document.getElementById("xshow").style.display = "inline";
		document.getElementById("xhide").style.display = "none";
	}

		document.getElementById("page_show").onclick= function(){
		if (document.getElementById("WLpages").style.display == "none"){
			if (Array.isArray(pages)){
				document.getElementById("WLpages").innerHTML = pages.toString().replace(/,/g,"
");
			}else{
				document.getElementById("WLpages").innerHTML = pages;
			}
			document.getElementById("WLpages").style.display = "block";
		}else{
			document.getElementById("WLpages").style.display = "block";
		}
		document.getElementById("page_show").style.display = "none";
		document.getElementById("page_hide").style.display = "inline";
		}

		document.getElementById("page_hide").onclick = function(){
		document.getElementById("WLpages").style.display = "none"
		document.getElementById("page_show").style.display = "inline";
		document.getElementById("page_hide").style.display = "none";
		}

	document.getElementById("pshow").onclick= function(){
		if (document.getElementById("phraseList").style.display == "none"){
			if (Array.isArray(phrases)){
				document.getElementById("phraseList").innerHTML = phrases.toString().replace(/,/g,"
");
			}else{
				document.getElementById("phraseList").innerHTML = phrases;
			}
			document.getElementById("phraseList").style.display = "block";
		}else{
			document.getElementById("phraseList").style.display = "block";
		}
		document.getElementById("pshow").style.display = "none";
		document.getElementById("phide").style.display = "inline";
	}

	document.getElementById("phide").onclick = function(){
		document.getElementById("phraseList").style.display = "none"
		document.getElementById("pshow").style.display = "inline";
		document.getElementById("phide").style.display = "none";
	}

	document.getElementById("clearWhite").onclick = function(){
		var result = confirm("This will delete your custom whitelist, are you sure this is what you want?");
		if (result){
			chrome.storage.sync.remove("phraseWhitelist");
			chrome.runtime.sendMessage({clear: "clear"});
			location.reload();
		}
	}
	document.getElementById("clearPages").onclick = function(){
		var result = confirm("This will delete your custom whitelist, are you sure this is what you want?");
		if (result){
			chrome.storage.sync.remove("whitepage")
			chrome.runtime.sendMessage({clear: "clear"});
			location.reload();
		}

}
function build(data){
	values = data.userdata.splice(0,4);
	values.push(data.userdata[data.userdata.length-1]);
}

function phraseDisplay(whitelist){
	if (whitelist.phraseWhitelist){
		if (Array.isArray(whitelist.phraseWhitelist)){
			phrases = whitelist.phraseWhitelist.splice(0,whitelist.phraseWhitelist.length);
		}else{
			phrases = whitelist.phraseWhitelist;
		}
	}else{
		phrases = "No custom whitelist!";
	}

}
function pageDisplay(WLPages){
	if (WLPages.whitepage){
		if (Array.isArray(WLPages.whitepage)){
			pages = WLPages.whitepage.splice(0,WLPages.whitepage.length);
		}else{
			pages = WLPages.whitepage;
		}
	}else{
		pages = "No custom whitelist!";
	}

	}
}
<commit_msg>Clean up index.js<commit_after>var values;
var phrases;
window.onload = function(){
	chrome.storage.sync.get("userdata", build);
	chrome.storage.sync.get("phraseWhitelist", phraseDisplay);
	chrome.storage.sync.get("whitepage", pageDisplay);

	// Onclick behavior for wordlist show button.
	document.getElementById("xshow").onclick = function(){
		if (document.getElementById("CusList").style.display == "none"){
			document.getElementById("CusList").innerHTML = values.toString().replace(/,/g,"
");
			document.getElementById("CusList").style.display = "inline-block";
			document.getElementById("ListDesc").style.display = "inline-block";

		}else{
			document.getElementById("CusList").style.display = "inline-block";
			document.getElementById("ListDesc").style.display = "inline-block";
		}
		document.getElementById("xshow").style.display = "none";
		document.getElementById("xhide").style.display = "inline";

	}

	// Onclick behavior for wordlist hide button.
	document.getElementById("xhide").onclick = function(){
		document.getElementById("CusList").style.display = "none"
		document.getElementById("ListDesc").style.display = "none";
		document.getElementById("xshow").style.display = "inline";
		document.getElementById("xhide").style.display = "none";
	}

	// Onclick behavior for whitelisted pages show button.
	document.getElementById("page_show").onclick= function(){
		if (document.getElementById("WLpages").style.display == "none"){
			if (Array.isArray(pages)){
				document.getElementById("WLpages").innerHTML = pages.toString().replace(/,/g,"
");
			}
			else{
				document.getElementById("WLpages").innerHTML = pages;
			}
			document.getElementById("WLpages").style.display = "block";
		}
		else{
			document.getElementById("WLpages").style.display = "block";
		}
		document.getElementById("page_show").style.display = "none";
		document.getElementById("page_hide").style.display = "inline";
	}

	// Onclick behavior for whitelisted page hide button.
	document.getElementById("page_hide").onclick = function(){
		document.getElementById("WLpages").style.display = "none"
		document.getElementById("page_show").style.display = "inline";
		document.getElementById("page_hide").style.display = "none";
	}

	// Onclick behavior for whitelisted phrase show button.
	document.getElementById("pshow").onclick= function(){
		if (document.getElementById("phraseList").style.display == "none"){
			if (Array.isArray(phrases)){
				document.getElementById("phraseList").innerHTML = phrases.toString().replace(/,/g,"
");
			}else{
				document.getElementById("phraseList").innerHTML = phrases;
			}
			document.getElementById("phraseList").style.display = "block";
		}else{
			document.getElementById("phraseList").style.display = "block";
		}
		document.getElementById("pshow").style.display = "none";
		document.getElementById("phide").style.display = "inline";
	}

	// Onclick behavior for whitelisted phrase hide button
	document.getElementById("phide").onclick = function(){
		document.getElementById("phraseList").style.display = "none"
		document.getElementById("pshow").style.display = "inline";
		document.getElementById("phide").style.display = "none";
	}

	// Onclick behavior for clear phrase whitelist button.
	document.getElementById("clearWhite").onclick = function(){
		var result = confirm("This will delete your custom whitelist, are you sure this is what you want?");
		if (result){
			chrome.storage.sync.remove("phraseWhitelist");
			chrome.runtime.sendMessage({clear: "clear"});
			location.reload();
		}
	}

	// Onclick behavior for clear page whitelist button.
	document.getElementById("clearPages").onclick = function(){
		var result = confirm("This will delete your custom whitelist, are you sure this is what you want?");
		if (result){
			chrome.storage.sync.remove("whitepage")
			chrome.runtime.sendMessage({clear: "clear"});
			location.reload();
		}
	}

	// Function to populate the custom wordlist list with userdata from storage.
	function build(data){
		values = data.userdata.splice(0,4);
		values.push(data.userdata[data.userdata.length-1]);
	}

	// Function to populate phrase whitelist list with stored whitelist.
	function phraseDisplay(whitelist){
		if (whitelist.phraseWhitelist){
			if (Array.isArray(whitelist.phraseWhitelist)){
				phrases = whitelist.phraseWhitelist.splice(0,whitelist.phraseWhitelist.length);
			}
			else{
				phrases = whitelist.phraseWhitelist;
			}
		}
		else{
			phrases = "No custom whitelist!";
		}
	}

	// Function to populate whitelisted page list with storage whitelist.
	function pageDisplay(WLPages){
		if (WLPages.whitepage){
			if (Array.isArray(WLPages.whitepage)){
				pages = WLPages.whitepage.splice(0,WLPages.whitepage.length);
			}
			else{
				pages = WLPages.whitepage;
			}
		}
		else{
			pages = "No custom whitelist!";
		}
	}
}
<|endoftext|>


<commit_before>"use strict";

const path = require("path");

function mockPromise(value) {
	const isValueAPromise = (value || {}).then;
	const mockedPromise = {
		then: function(callback) {
			return mockPromise(callback(value));
		}
	};

	return isValueAPromise ? value : mockedPromise;
}
function spawnChild(pkg) {
	return pkg;
}

function getLoc(option) {
	let packageModule = [];
	option.filter(pkg => {
		mockPromise(spawnChild(pkg)).then(_ => {
			try {
				let loc = path.join("..", "..", "node_modules", pkg);
				packageModule.push(loc);
			} catch (err) {
				throw new Error(
					"Package wasn't validated correctly.." + "Submit an issue for",
					pkg,
					"if this persists"
				);
			}
		});
		return packageModule;
	});
	return packageModule;
}

describe("resolve-packages", () => {
	let moduleLoc;

	afterEach(() => {
		moduleLoc = null;
	});

	it("should resolve a location of a published module", () => {
		moduleLoc = getLoc(["webpack-addons-ylvis"]);
		expect(moduleLoc).toEqual(["../../node_modules/webpack-addons-ylvis"]);
	});

	it("should be empty if argument is blank", () => {
		// normally caught before getting resolved
		moduleLoc = getLoc([" "]);
		expect(moduleLoc).toEqual(["../../node_modules/ "]);
	});

	it("should resolve multiple locations of published modules", () => {
		/* we're testing multiple paths here. At Github this up for discussion, because if
		 * we validate each package on each run, we can catch and build the questions in init gradually
		 * while we get one filepath at the time. If not, this is a workaround.
		 */
		moduleLoc = getLoc(["webpack-addons-ylvis", "webpack-addons-noop"]);
		expect(moduleLoc).toEqual([
			"../../node_modules/webpack-addons-ylvis",
			"../../node_modules/webpack-addons-noop"
		]);
	});
});
<commit_msg>normalize test paths for appveyor to be happy<commit_after>"use strict";

const path = require("path");

function mockPromise(value) {
	const isValueAPromise = (value || {}).then;
	const mockedPromise = {
		then: function(callback) {
			return mockPromise(callback(value));
		}
	};

	return isValueAPromise ? value : mockedPromise;
}
function spawnChild(pkg) {
	return pkg;
}

function getLoc(option) {
	let packageModule = [];
	option.filter(pkg => {
		mockPromise(spawnChild(pkg)).then(_ => {
			try {
				let loc = path.join("..", "..", "node_modules", pkg);
				packageModule.push(loc);
			} catch (err) {
				throw new Error(
					"Package wasn't validated correctly.." + "Submit an issue for",
					pkg,
					"if this persists"
				);
			}
		});
		return packageModule;
	});
	return packageModule;
}

describe("resolve-packages", () => {
	let moduleLoc;

	afterEach(() => {
		moduleLoc = null;
	});

	it("should resolve a location of a published module", () => {
		moduleLoc = getLoc(["webpack-addons-ylvis"]);
		expect(moduleLoc).toEqual([path.normalize("../../node_modules/webpack-addons-ylvis")]);
	});

	it("should be empty if argument is blank", () => {
		// normally caught before getting resolved
		moduleLoc = getLoc([" "]);
		expect(moduleLoc).toEqual([path.normalize("../../node_modules/ ")]);
	});

	it("should resolve multiple locations of published modules", () => {
		/* we're testing multiple paths here. At Github this up for discussion, because if
		 * we validate each package on each run, we can catch and build the questions in init gradually
		 * while we get one filepath at the time. If not, this is a workaround.
		 */
		moduleLoc = getLoc(["webpack-addons-ylvis", "webpack-addons-noop"]);
		expect(moduleLoc).toEqual([
			path.normalize("../../node_modules/webpack-addons-ylvis"),
			path.normalize("../../node_modules/webpack-addons-noop")
		]);
	});
});
<|endoftext|>


<commit_before>/*
---
name: Behavior
description: Auto-instantiates widgets/classes based on parsed, declarative HTML.
requires: [Core/Class.Extras, Core/Element, Core/Selectors, /Element.Data, More/Table]
provides: [DashSelectors, Behavior]
...
*/

(function(){

	var spaceOrCommaRegex = /\s*,\s*|\s+/g;

	this.Behavior = new Class({

		Implements: [Options, Events],

		options: {
			//by default, errors thrown by filters are caught; the onError event is fired.
			//set this to *true* to NOT catch these errors to allow them to be handled by the browser.
			// breakOnErrors: false,

			//default error behavior when a filter cannot be applied
			onError: function(){
				if (window.console && console.warn){
					if(console.warn.apply) console.warn.apply(console, arguments);
					else console.warn($A(arguments).join(' '));
				}
			}
			//Components that have a Behavior instance (like an ART.Window)
			//call these events to tell filters that need to know that the state
			//has changed:
			// onResize: $empty, //the element's dimensions have changed
			// onShow: $empty, //the element is displayed
			// onHide: $empty //the element is hidden
		},

		initialize: function(options){
			this.setOptions(options);
			this.passMethods({
				addEvent: this.addEvent.bind(this),
				removeEvent: this.removeEvent.bind(this),
				addEvents: this.addEvents.bind(this),
				removeEvents: this.removeEvents.bind(this),
				fireEvent: this.fireEvent.bind(this),
				applyFilters: this.apply.bind(this),
				applyFilter: this.applyFilter.bind(this),
				getContentElement: $lambda(this.options.container || document.body),
				//this doesn't really stand up; the container is variable - one behavior instance
				//can handle numerous containers... TODO: revisit
				getContainerSize: function() { return this.currentSize; }.bind(this),
				error: function(){ this.fireEvent('error', arguments); }.bind(this)
			});
		},

		//pass a method pointer through to a filter
		//by default the methods for add/remove events are passed to the filter
		//pointed to this instance of behavior. you could use this to pass along
		//other methods to your filters. For example, a method to close a popup
		//for filters presented inside popups.
		_passedMethods: {},
		passMethod: function(method, fn){
			var self = this;
			this._passedMethods[method] = function(){
				return fn.apply(this, arguments);
			};
			return this;
		},

		passMethods: function(methods){
			for (var method in methods) {
				this.passMethod(method, methods[method]);
			}
			return this;
		},

		//These methods don't change the element's state but rather are used
		//to tell filters that need to adapt to the new element state that
		//it has changed.
		show: function(){
			return this.fireEvent('show');
		},

		//the element is hidden
		hide: function(){
			return this.fireEvent('hide');
		},

		//the element's dimensions are now the specified width and height
		resize: function(x, y){
			this.currentSize = {x: x, y: y};
			return this.fireEvent('resize', [x, y]);
		},

		//Applies all the behavior filters for an element.
		//container - (element) an element to apply the filters registered with this Behavior instance to.
		//force - (boolean; optional) passed through to applyFilter (see it for docs)
		apply: function(container, force){
			document.id(container).getElements('[data-filters]').each(function(element){
				var plugins = [];
				element.getDataFilters().each(function(name){
					var behavior = this.getFilter(name.trim());
					if (!behavior) {
						this.fireEvent('error', ['There is no behavior registered with this name: ', name, element]);
					} else {
						plugins.extend(this.applyFilter(element, behavior, force, true));
					}
				}, this);
				plugins.each(function(plugin){ plugin(); });
			}, this);
			return this;
		},

		//Applies a specific behavior to a specific element.
		//element - the element to which to apply the behavior
		//filter - (object) a specific behavior filter, typically one registered with this instance or registered globally.
		//force - (boolean; optional) apply the behavior to each element it matches, even if it was previously applied. Defaults to *false*.
		//returnPlugins - (boolean; optional) if true, plugins are not rendered but instead returned as an array of functions
		applyFilter: function(element, filter, force, returnPlugins){
			var pluginsToReturn = [];
			var run = function(){
				element = document.id(element);
				//get the filters already applied to this element
				var applied = getApplied(element);
				//if this filter is not yet applied to the element, or we are forcing the filter
				if (!applied[filter.name] || force) {
					//if it was previously applied, garbage collect it
					if (applied[filter.name]) applied[filter.name].cleanup(element);
					//apply the filter
					filter.attach(element, this._passedMethods);
					//and mark it as having been previously applied
					applied[filter.name] = filter;
					//apply all the plugins for this filter
					var plugins = this.getPlugins(filter.name);
					if (plugins) {
						for (var name in plugins) {
							if (returnPlugins) {
								pluginsToReturn.push(this.applyFilter.pass([element, plugins[name], force], this));
							} else {
								this.applyFilter(element, plugins[name], force);
							}
						}
					}
				}
			}.bind(this);
			if (this.options.breakOnErrors) {
				run();
			} else {
				try {
					run();
				} catch (e) {
					this.fireEvent('error', ['Could not apply the behavior ' + filter.name, e]);
				}
			}
			return returnPlugins ? pluginsToReturn : this;
		},

		//given a name, returns a registered behavior
		getFilter: function(name){
			return this._registered[name] || Behavior._registered[name];
		},

		getPlugins: function(name){
			return this._plugins[name] || Behavior._plugins[name];
		},

		//Garbage collects all applied filters for an element and its children.
		//element - (*element*) container to cleanup
		//ignoreChildren - (*boolean*; optional) if *true* only the element will be cleaned, otherwise the element and all the
		//	  children with filters applied will be cleaned. Defaults to *false*.
		cleanup: function(element, ignoreChildren){
			element = document.id(element);
			var applied = getApplied(element);
			for (var behavior in applied) {
				applied[behavior].cleanup(element);
				delete applied[behavior];
			}
			if (!ignoreChildren) element.getElements(':hasBehaviors').each(this.cleanup, this);
			return this;
		}

	});

	//Returns the applied behaviors for an element.
	var getApplied = function(el){
		return el.retrieve('_appliedBehaviors', {});
	};

	//Registers a behavior filter.
	//name - the name of the filter
	//fn - a function that applies the filter to the given element
	//overwrite - (boolean) if true, will overwrite existing filter if one exists; defaults to false.
	var addFilter = function(name, fn, overwrite){
		if (!this._registered[name] || overwrite) this._registered[name] = new Behavior.Filter(name, fn);
	};

	var addFilters = function(obj, overwrite) {
		for (var name in obj) {
			addFilter.apply(this, [name, obj[name], overwrite]);
		}
	};

	//Registers a behavior plugin
	//filterName - (*string*) the filter (or plugin) this is a plugin for
	//name - (*string*) the name of this plugin
	//attacher - a function that applies the filter to the given element
	var addPlugin = function(filterName, name, attacher, overwrite) {
		if (!this._plugins[filterName]) this._plugins[filterName] = {};
		if (!this._plugins[filterName][name] || overwrite) this._plugins[filterName][name] = new Behavior.Filter(name, attacher);
	};

	var addPlugins = function(obj, overwrite) {
		for (var name in obj) {
			addPlugin.apply(this, [obj[name].fitlerName, obj[name].name, obj[name].attacher], overwrite);
		}
	};

	//Add methods to the Behavior namespace for global registration.
	$extend(Behavior, {
		_registered: {},
		_plugins: {},
		addGlobalFilter: addFilter,
		addGlobalFilters: addFilters,
		addGlobalPlugin: addPlugin,
		addGlobalPlugins: addPlugins
	});
	//Add methods to the Behavior class for instance registration.
	Behavior.implement({
		_registered: {},
		_plugins: {},
		addFilter: addFilter,
		addFilters: addFilters,
		addPlugin: addPlugin,
		addPlugins: addPlugins
	});

	//This class is an actual filter that, given an element, alters it with specific behaviors.
	Behavior.Filter = new Class({

		//Pass in an object with the following properties:
		//name - the name of this filter
		//attacher - a function that applies the filter to the given element
		initialize: function(name, attacher){
			this.name = name;
			this.attach = attacher;
			this._marks = new Table();
		},

		//Stores a garbage collection pointer for a specific element.
		//Example: if your filter enhances all the inputs in the container
		//you might have a function that removes that enhancement for garbage collection.
		//You would mark each input matched with its own cleanup function.
		//NOTE: this MUST be the element passed to the filter - the element with this filters
		//      name in its data-filter property. I.E.:
		//<form data-filter="FormValidator">
		//  <input type="text" name="email"/>
		//</form>
		//If this filter is FormValidator, you can mark the form for cleanup, but not, for example
		//the input. Only elements that match this filter can be marked.
		markForCleanup: function(element, fn){
			var marks = this._marks.get(element);
			if (!marks) marks = [];
			marks.include(fn);
			this._marks.set(element, marks);
			return this;
		},

		//Garbage collect a specific element.
		//NOTE: this should be an element that has a data-filter property that matches this filter.
		cleanup: function(element){
			var marks = this._marks.get(element);
			if (marks) {
				marks.each(function(fn){ fn(); });
				this._marks.erase(element);
			}
			return this;
		}

	});

	//a selector to find all elements that have behaviors applied to them.
	Selectors.Pseudo.hasBehaviors = function(){
		return !!Element.retrieve(this, '_appliedBehaviors');
	};

	Element.implement({

		addDataFilter: function(name){
			return this.set('data', 'filters', this.getDataFilters().include(name).join(' '));
		},

		removeDataFilter: function(name){
			return this.set('data', 'filters', this.getDataFilters().erase(name).join(' '));
		},

		getDataFilters: function(){
			var filters = this.getData('filters');
			if (!filters) return [];
			return filters.trim().split(spaceOrCommaRegex);
		},

		hasDataFilter: function(name){
			return this.getDataFilters().contains(name);
		}

	});

})();

//allows for selectors like $$('[data-foo-bar]'); TODO: Note that it'll be in Moo 1.3; remove then.
if (window.Selectors && Selectors.RegExps) {
	Selectors.RegExps.combined = (/\.([\w-]+)|\[([\w-]+)(?:([!*^$~|]?=)(["']?)([^\4]*?)\4)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g);
}
<commit_msg>Behavior now stores the result of applied filters on the element and provides a method to get that result.<commit_after>/*
---
name: Behavior
description: Auto-instantiates widgets/classes based on parsed, declarative HTML.
requires: [Core/Class.Extras, Core/Element, Core/Selectors, /Element.Data, More/Table]
provides: [DashSelectors, Behavior]
...
*/

(function(){

	var spaceOrCommaRegex = /\s*,\s*|\s+/g;

	this.Behavior = new Class({

		Implements: [Options, Events],

		options: {
			//by default, errors thrown by filters are caught; the onError event is fired.
			//set this to *true* to NOT catch these errors to allow them to be handled by the browser.
			// breakOnErrors: false,

			//default error behavior when a filter cannot be applied
			onError: function(){
				if (window.console && console.warn){
					if(console.warn.apply) console.warn.apply(console, arguments);
					else console.warn($A(arguments).join(' '));
				}
			}
			//Components that have a Behavior instance (like an ART.Window)
			//call these events to tell filters that need to know that the state
			//has changed:
			// onResize: $empty, //the element's dimensions have changed
			// onShow: $empty, //the element is displayed
			// onHide: $empty //the element is hidden
		},

		initialize: function(options){
			this.setOptions(options);
			this.passMethods({
				addEvent: this.addEvent.bind(this),
				removeEvent: this.removeEvent.bind(this),
				addEvents: this.addEvents.bind(this),
				removeEvents: this.removeEvents.bind(this),
				fireEvent: this.fireEvent.bind(this),
				applyFilters: this.apply.bind(this),
				applyFilter: this.applyFilter.bind(this),
				getContentElement: $lambda(this.options.container || document.body),
				//this doesn't really stand up; the container is variable - one behavior instance
				//can handle numerous containers... TODO: revisit
				getContainerSize: function() { return this.currentSize; }.bind(this),
				error: function(){ this.fireEvent('error', arguments); }.bind(this)
			});
		},

		//pass a method pointer through to a filter
		//by default the methods for add/remove events are passed to the filter
		//pointed to this instance of behavior. you could use this to pass along
		//other methods to your filters. For example, a method to close a popup
		//for filters presented inside popups.
		_passedMethods: {},
		passMethod: function(method, fn){
			var self = this;
			this._passedMethods[method] = function(){
				return fn.apply(this, arguments);
			};
			return this;
		},

		passMethods: function(methods){
			for (var method in methods) {
				this.passMethod(method, methods[method]);
			}
			return this;
		},

		//These methods don't change the element's state but rather are used
		//to tell filters that need to adapt to the new element state that
		//it has changed.
		show: function(){
			return this.fireEvent('show');
		},

		//the element is hidden
		hide: function(){
			return this.fireEvent('hide');
		},

		//the element's dimensions are now the specified width and height
		resize: function(x, y){
			this.currentSize = {x: x, y: y};
			return this.fireEvent('resize', [x, y]);
		},

		//Applies all the behavior filters for an element.
		//container - (element) an element to apply the filters registered with this Behavior instance to.
		//force - (boolean; optional) passed through to applyFilter (see it for docs)
		apply: function(container, force){
			document.id(container).getElements('[data-filters]').each(function(element){
				var plugins = [];
				element.getDataFilters().each(function(name){
					var behavior = this.getFilter(name.trim());
					if (!behavior) {
						this.fireEvent('error', ['There is no behavior registered with this name: ', name, element]);
					} else {
						plugins.extend(this.applyFilter(element, behavior, force, true));
					}
				}, this);
				plugins.each(function(plugin){ plugin(); });
			}, this);
			return this;
		},

		//Applies a specific behavior to a specific element.
		//element - the element to which to apply the behavior
		//filter - (object) a specific behavior filter, typically one registered with this instance or registered globally.
		//force - (boolean; optional) apply the behavior to each element it matches, even if it was previously applied. Defaults to *false*.
		//_returnPlugins - (boolean; optional; internal) if true, plugins are not rendered but instead returned as an array of functions
		//_pluginTargetResult - (obj; optional internal) if this filter is a plugin for another, this is whatever that target filter returned
		//                      (an instance of a class for example)
		applyFilter: function(element, filter, force, _returnPlugins, _pluginTargetResult){
			var pluginsToReturn = [];
			var run = function(){
				element = document.id(element);
				//get the filters already applied to this element
				var applied = getApplied(element);
				//if this filter is not yet applied to the element, or we are forcing the filter
				if (!applied[filter.name] || force) {
					//if it was previously applied, garbage collect it
					if (applied[filter.name]) applied[filter.name].cleanup(element);
					//apply the filter
					var result = filter.attach(element, this._passedMethods, _pluginTargetResult);
					element.store('Behavior:' + filter.name, result);
					//and mark it as having been previously applied
					applied[filter.name] = filter;
					//apply all the plugins for this filter
					var plugins = this.getPlugins(filter.name);
					if (plugins) {
						for (var name in plugins) {
							if (_returnPlugins) {
								pluginsToReturn.push(this.applyFilter.pass([element, plugins[name], force, null, result], this));
							} else {
								this.applyFilter(element, plugins[name], force, null, result);
							}
						}
					}
				}
			}.bind(this);
			if (this.options.breakOnErrors) {
				run();
			} else {
				try {
					run();
				} catch (e) {
					this.fireEvent('error', ['Could not apply the behavior ' + filter.name, e]);
				}
			}
			return _returnPlugins ? pluginsToReturn : this;
		},

		//given a name, returns a registered behavior
		getFilter: function(name){
			return this._registered[name] || Behavior._registered[name];
		},

		getPlugins: function(name){
			return this._plugins[name] || Behavior._plugins[name];
		},

		//Garbage collects all applied filters for an element and its children.
		//element - (*element*) container to cleanup
		//ignoreChildren - (*boolean*; optional) if *true* only the element will be cleaned, otherwise the element and all the
		//	  children with filters applied will be cleaned. Defaults to *false*.
		cleanup: function(element, ignoreChildren){
			element = document.id(element);
			var applied = getApplied(element);
			for (var filter in applied) {
				applied[filter].cleanup(element);
				element.eliminate('Behavior:' + filter);
				delete applied[filter];
			}
			if (!ignoreChildren) element.getElements(':hasBehaviors').each(this.cleanup, this);
			return this;
		}

	});

	//Returns the applied behaviors for an element.
	var getApplied = function(el){
		return el.retrieve('_appliedBehaviors', {});
	};

	//Registers a behavior filter.
	//name - the name of the filter
	//fn - a function that applies the filter to the given element
	//overwrite - (boolean) if true, will overwrite existing filter if one exists; defaults to false.
	var addFilter = function(name, fn, overwrite){
		if (!this._registered[name] || overwrite) this._registered[name] = new Behavior.Filter(name, fn);
	};

	var addFilters = function(obj, overwrite) {
		for (var name in obj) {
			addFilter.apply(this, [name, obj[name], overwrite]);
		}
	};

	//Registers a behavior plugin
	//filterName - (*string*) the filter (or plugin) this is a plugin for
	//name - (*string*) the name of this plugin
	//attacher - a function that applies the filter to the given element
	var addPlugin = function(filterName, name, attacher, overwrite) {
		if (!this._plugins[filterName]) this._plugins[filterName] = {};
		if (!this._plugins[filterName][name] || overwrite) this._plugins[filterName][name] = new Behavior.Filter(name, attacher);
	};

	var addPlugins = function(obj, overwrite) {
		for (var name in obj) {
			addPlugin.apply(this, [obj[name].fitlerName, obj[name].name, obj[name].attacher], overwrite);
		}
	};

	//Add methods to the Behavior namespace for global registration.
	$extend(Behavior, {
		_registered: {},
		_plugins: {},
		addGlobalFilter: addFilter,
		addGlobalFilters: addFilters,
		addGlobalPlugin: addPlugin,
		addGlobalPlugins: addPlugins
	});
	//Add methods to the Behavior class for instance registration.
	Behavior.implement({
		_registered: {},
		_plugins: {},
		addFilter: addFilter,
		addFilters: addFilters,
		addPlugin: addPlugin,
		addPlugins: addPlugins
	});

	//This class is an actual filter that, given an element, alters it with specific behaviors.
	Behavior.Filter = new Class({

		//Pass in an object with the following properties:
		//name - the name of this filter
		//attacher - a function that applies the filter to the given element
		initialize: function(name, attacher){
			this.name = name;
			this.attach = attacher;
			this._marks = new Table();
		},

		//Stores a garbage collection pointer for a specific element.
		//Example: if your filter enhances all the inputs in the container
		//you might have a function that removes that enhancement for garbage collection.
		//You would mark each input matched with its own cleanup function.
		//NOTE: this MUST be the element passed to the filter - the element with this filters
		//      name in its data-filter property. I.E.:
		//<form data-filter="FormValidator">
		//  <input type="text" name="email"/>
		//</form>
		//If this filter is FormValidator, you can mark the form for cleanup, but not, for example
		//the input. Only elements that match this filter can be marked.
		markForCleanup: function(element, fn){
			var marks = this._marks.get(element);
			if (!marks) marks = [];
			marks.include(fn);
			this._marks.set(element, marks);
			return this;
		},

		//Garbage collect a specific element.
		//NOTE: this should be an element that has a data-filter property that matches this filter.
		cleanup: function(element){
			var marks = this._marks.get(element);
			if (marks) {
				marks.each(function(fn){ fn(); });
				this._marks.erase(element);
			}
			return this;
		}

	});

	//a selector to find all elements that have behaviors applied to them.
	Selectors.Pseudo.hasBehaviors = function(){
		return !!Element.retrieve(this, '_appliedBehaviors');
	};

	Element.implement({

		addDataFilter: function(name){
			return this.setData('filters', this.getDataFilters().include(name).join(' '));
		},

		removeDataFilter: function(name){
			return this.setData('filters', this.getDataFilters().erase(name).join(' '));
		},

		getDataFilters: function(){
			var filters = this.getData('filters');
			if (!filters) return [];
			return filters.trim().split(spaceOrCommaRegex);
		},

		hasDataFilter: function(name){
			return this.getDataFilters().contains(name);
		},

		getFilterResult: function(name){
			return this.retrieve('Behavior:' + name);
		}

	});

})();

//allows for selectors like $$('[data-foo-bar]'); TODO: Note that it'll be in Moo 1.3; remove then.
if (window.Selectors && Selectors.RegExps) {
	Selectors.RegExps.combined = (/\.([\w-]+)|\[([\w-]+)(?:([!*^$~|]?=)(["']?)([^\4]*?)\4)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g);
}
<|endoftext|>