<commit_before>KB
/*
Notes:
'data' is lazily imported from the html
'seedrandom' is also imported from html. it gives deterministic random #s based on a seed set in fire()
*/

var wordsSelected = [];
var teams = [];
var NUMBER_OF_WORDS = 6;
var spyMasterMode = false;
var sessionData = [];
var customData = [];

var COLOR_RED = "#ff0000";
var COLOR_YELLOW = "#ffff00";
var COLOR_BLUE = "#00eeee";
var COLOR_BLACK = "#808080";
var COLOR_GREEN = "#009000";

//init
$("#seed").keyup(function() {
	fire();
});

$("#gameMode").change(function() {
	fire();
});

$("#seed").val(Math.floor(Math.random() * 1000));
fire();

function fire() {
	//get seed and set the seed for randomizer
	var seed = document.getElementById("seed").value;
	Math.seedrandom(seed.toLowerCase());

	var option = $('#gameMode :selected').val();
	switch (option) {
		case '2knouns':
			sessionData = data.slice(0);
			break;
		case 'movies':
			sessionData = movieData.slice(0);
			break;
		case 'custom':
			if (customData.length === 0) {
				var customWordList = prompt("Please enter custom word list. The list will be saved until your refresh your browser. (The words MUST be delimanted by spaces). eg: cat dog mouse", "Enter words here");
				customData = customWordList.split(' ');
			}
			sessionData = customData.slice(0);
			break;
		default:
			sessionData = defaultData.slice(0);
	}

	wordsSelected = [];
	teams = [];
	spyMasterMode = false;
	document.getElementById("board").innerHTML = "";

	//fire new board
	updateScore();
	createNewGame();
}

// Trying to get the new word bank to work

function NewWords() {
//	document.getElementById("seed").focus();
//	document.getElementById("seed").value = "";
//	document.getElementById("seed").value = 222222;
//	document.getElementById("seed").focus();
	document.getElementById("seed").innerHTML = "";
	Math.seedrandom(seed.toLowerCase());

}

/////

//not used, but probably useful at some point
function removeItem(array, index) {
	if (index > -1) {
		// console.log("index: " + index + ", word: " + array[index] + " removed.");
		array.splice(index, 1);
	}
}

function createNewGame() {
	var trs = [];
	for (var i = 0; i < NUMBER_OF_WORDS; i++) {
		if (!trs[i % 3]) {
			trs[i % 3] = "";
		}
		var randomNumber = Math.floor(Math.random() * sessionData.length);
		var word = sessionData[randomNumber];
		removeItem(sessionData, randomNumber);
		wordsSelected.push(word);
		trs[i % 3] += "

" + word + "

";
	}
	//Washington stimulates economic growth Read me
	for (var i = 0; i < trs.length; i++) {
		document.getElementById("board").innerHTML += '
' + trs[i] + '
'
	}

	//create teams
	for (var i = 0; i < 8; i++) {
		teams.push(COLOR_RED);
		teams.push(COLOR_BLUE);
	}

	// one extra for one of the teams
	if (Math.floor(Math.random() * data.length) % 2 === 0) {
		teams.push(COLOR_RED);
		// document.getElementById("team").style.color = COLOR_RED;
		// document.getElementById("team").innerHTML = "RED";
		$('#board').addClass('redStarts').removeClass('blueStarts');

	} else {
		teams.push(COLOR_BLUE);
		// document.getElementById("team").style.color = COLOR_BLUE;
		// document.getElementById("team").innerHTML = "BLUE";
		$('#board').addClass('blueStarts').removeClass('redStarts');
	}

	// add neturals
	for (var i = 0; i < 7; i++) {
		teams.push(COLOR_YELLOW);
	}

	// push the assasin
	teams.push(COLOR_BLACK)

	//shuffle teams
	shuffle(teams);

	updateScore();
}

function clicked(value) {
	if (document.getElementById(value).style.backgroundColor == COLOR_RED) {
		document.getElementById(value).style.backgroundColor = COLOR_WHITE;
	} else {
		document.getElementById(value).style.backgroundColor = COLOR_RED;
		}
	updateScore();
}

function updateScore() {
	var blueScore = 9;
	var redScore = 9;
	if (spyMasterMode) {
		blueScore = 0;
		redScore = 0;
		$('div.word').each(function() {
			var color = $(this).css('background-color');
			if (color === 'rgb(0, 238, 238)') {
				blueScore++;
			}
			if (color === 'rgb(255, 0, 0)') {
				redScore++;
			}
		});
	} else {
		$('div.word').each(function() {
			var color = $(this).css('background-color');
			if (color === 'rgb(0, 238, 238)') {
				blueScore--;
			}
			if (color === 'rgb(255, 0, 0)') {
				redScore--;
			}
		});

		if ($('.redStarts').length === 1) {
			blueScore--;
		} else {
			redScore--;
		}
	}
	$('#redScore').text(redScore);
	$('#blueScore').text(blueScore);
	if(redScore === 0){
		$('#redScore').text('Winner!');
	}
	if(blueScore === 0){
		$('#blueScore').text('Winner!');
	}
}

function spyMaster() {
	//TODO: randomize or organize tiles for easier comparing
	spyMasterMode = true;
	for (var i = 0; i < NUMBER_OF_WORDS; i++) {
		document.getElementById(i).style.backgroundColor = teams[i];
		if (teams[i] == "black") {
			document.getElementById(i).style.color = "white";
		}
	}
}

function shuffle(array) {
	var currentIndex = array.length,
		temporaryValue, randomIndex;

	// While there remain elements to shuffle...
	while (0 !== currentIndex) {

		// Pick a remaining element...
		randomIndex = Math.floor(Math.random() * currentIndex);
		currentIndex -= 1;

		// And swap it with the current element.
		temporaryValue = array[currentIndex];
		array[currentIndex] = array[randomIndex];
		array[randomIndex] = temporaryValue;
	}

	return array;
}

//enable pressing 'Enter' on seed field
document.getElementById('seed').onkeypress = function(e) {
	if (!e) e = window.event;
	var keyCode = e.keyCode || e.which;
	if (keyCode == '13') {
		// Enter pressed
		fire();
		return false;
	}
}
<commit_msg>Update index.js<commit_after>
/*
Notes:
'data' is lazily imported from the html
'seedrandom' is also imported from html. it gives deterministic random #s based on a seed set in fire()
*/

var wordsSelected = [];
var teams = [];
var NUMBER_OF_WORDS = 6;
var spyMasterMode = false;
var sessionData = [];
var customData = [];

var COLOR_RED = "#ff0000";
var COLOR_YELLOW = "#ffff00";
var COLOR_BLUE = "#00eeee";
var COLOR_BLACK = "#808080";
var COLOR_GREEN = "#009000";

//init
$("#seed").keyup(function() {
	fire();
});

$("#gameMode").change(function() {
	fire();
});

$("#seed").val(Math.floor(Math.random() * 1000));
fire();

function fire() {
	//get seed and set the seed for randomizer
	var seed = document.getElementById("seed").value;
	Math.seedrandom(seed.toLowerCase());

	var option = $('#gameMode :selected').val();
	switch (option) {
		case '2knouns':
			sessionData = data.slice(0);
			break;
		case 'movies':
			sessionData = movieData.slice(0);
			break;
		case 'custom':
			if (customData.length === 0) {
				var customWordList = prompt("Please enter custom word list. The list will be saved until your refresh your browser. (The words MUST be delimanted by spaces). eg: cat dog mouse", "Enter words here");
				customData = customWordList.split(' ');
			}
			sessionData = customData.slice(0);
			break;
		default:
			sessionData = defaultData.slice(0);
	}

	wordsSelected = [];
	teams = [];
	spyMasterMode = false;
	document.getElementById("board").innerHTML = "";

	//fire new board
	updateScore();
	createNewGame();
}

// Trying to get the new word bank to work

function NewWords() {
//	document.getElementById("seed").focus();
//	document.getElementById("seed").value = "";
//	document.getElementById("seed").value = 222222;
//	document.getElementById("seed").focus();
	document.getElementById("seed").innerHTML = "";
	Math.seedrandom(seed.toLowerCase());

}

/////

//not used, but probably useful at some point
function removeItem(array, index) {
	if (index > -1) {
		// console.log("index: " + index + ", word: " + array[index] + " removed.");
		array.splice(index, 1);
	}
}

function createNewGame() {
	var trs = [];
	for (var i = 0; i < NUMBER_OF_WORDS; i++) {
		if (!trs[i % 3]) {
			trs[i % 3] = "";
		}
		var randomNumber = Math.floor(Math.random() * sessionData.length);
		var word = sessionData[randomNumber];
		removeItem(sessionData, randomNumber);
		wordsSelected.push(word);
		trs[i % 3] += "

" + word + "

";
	}
	//Washington stimulates economic growth Read me
	for (var i = 0; i < trs.length; i++) {
		document.getElementById("board").innerHTML += '
' + trs[i] + '
'
	}

	//create teams
	for (var i = 0; i < 8; i++) {
		teams.push(COLOR_RED);
		teams.push(COLOR_BLUE);
	}

	// one extra for one of the teams
	if (Math.floor(Math.random() * data.length) % 2 === 0) {
		teams.push(COLOR_RED);
		// document.getElementById("team").style.color = COLOR_RED;
		// document.getElementById("team").innerHTML = "RED";
		$('#board').addClass('redStarts').removeClass('blueStarts');

	} else {
		teams.push(COLOR_BLUE);
		// document.getElementById("team").style.color = COLOR_BLUE;
		// document.getElementById("team").innerHTML = "BLUE";
		$('#board').addClass('blueStarts').removeClass('redStarts');
	}

	// add neturals
	for (var i = 0; i < 7; i++) {
		teams.push(COLOR_YELLOW);
	}

	// push the assasin
	teams.push(COLOR_BLACK)

	//shuffle teams
	shuffle(teams);

	updateScore();
}

function clicked(value) {
	if (document.getElementById(value).style.backgroundColor == COLOR_RED) {
		document.getElementById(value).style.backgroundColor = COLOR_WHITE;
	} else {
		document.getElementById(value).style.backgroundColor = COLOR_RED;
		}
	updateScore();
}

function updateScore() {
	var blueScore = 9;
	var redScore = 9;
	if (spyMasterMode) {
		blueScore = 0;
		redScore = 0;
		$('div.word').each(function() {
			var color = $(this).css('background-color');
			if (color === 'rgb(0, 238, 238)') {
				blueScore++;
			}
			if (color === 'rgb(255, 0, 0)') {
				redScore++;
			}
		});
	} else {
		$('div.word').each(function() {
			var color = $(this).css('background-color');
			if (color === 'rgb(0, 238, 238)') {
				blueScore--;
			}
			if (color === 'rgb(255, 0, 0)') {
				redScore--;
			}
		});

		if ($('.redStarts').length === 1) {
			blueScore--;
		} else {
			redScore--;
		}
	}
	$('#redScore').text(redScore);
	$('#blueScore').text(blueScore);
	if(redScore === 0){
		$('#redScore').text('Winner!');
	}
	if(blueScore === 0){
		$('#blueScore').text('Winner!');
	}
}

function spyMaster() {
	//TODO: randomize or organize tiles for easier comparing
	spyMasterMode = true;
	for (var i = 0; i < NUMBER_OF_WORDS; i++) {
		document.getElementById(i).style.backgroundColor = teams[i];
		if (teams[i] == "black") {
			document.getElementById(i).style.color = "white";
		}
	}
}

function shuffle(array) {
	var currentIndex = array.length,
		temporaryValue, randomIndex;

	// While there remain elements to shuffle...
	while (0 !== currentIndex) {

		// Pick a remaining element...
		randomIndex = Math.floor(Math.random() * currentIndex);
		currentIndex -= 1;

		// And swap it with the current element.
		temporaryValue = array[currentIndex];
		array[currentIndex] = array[randomIndex];
		array[randomIndex] = temporaryValue;
	}

	return array;
}

//enable pressing 'Enter' on seed field
document.getElementById('seed').onkeypress = function(e) {
	if (!e) e = window.event;
	var keyCode = e.keyCode || e.which;
	if (keyCode == '13') {
		// Enter pressed
		fire();
		return false;
	}
}
<|endoftext|>


<commit_before>var html5Player = function() {
    var video;

    function init(videoUrl, containerId) {
        video = document.createElement("video");
        video.setAttribute("src", videoUrl);
        video.setAttribute("width", 512);
        video.setAttribute('controls', true);
        document.getElementById(containerId).appendChild(video);
    }

    function play() {
        video.play();
    }

    function pause() {
        video.pause();
    }

    function destroy() {
        video.remove();
    }

    function paused() {
        return video.paused;
    }

    function duration() {
        return video.duration;
    }

    function currentTime() {
        return video.currentTime;
    }

    function setCurrentTime(time) {
        video.currentTime = time;
    }

    function ended() {
        return video.ended;
    }

    function volume() {
        return video.volume;
    }

    function setVolume(volume) {
        video.volume = volume;
    }

    function muted() {
        return video.muted;
    }

    function mute() {
        video.muted = true;
    }

    function unmute() {
        video.muted = false;
    }

    function onDurationAvailable(callback) {
        var onLoadedMetadata = function() {callback(duration());};
        video.addEventListener('loadedmetadata', onLoadedMetadata);
    }

    function onPlay(callback) {
        video.addEventListenºer('playing', callback);
    }

    function onPause(callback) {
        video.addEventListener('pause', callback);
    }

    function onPlayTimeChange(callback) {
        video.addEventListener('timeupdate', callback);
    }

    function onEnded(callback) {
        video.addEventListener('ended', callback);
    }

    return {
        init: init,
        play: play,
        pause: pause,
        destroy: destroy,
        paused: paused,
        duration: duration,
        currentTime: currentTime,
        setCurrentTime: setCurrentTime,
        ended: ended,
        volume: volume,
        setVolume: setVolume,
        muted: muted,
        mute: mute,
        unmute: unmute,
        onDurationAvailable: onDurationAvailable,
        onPlay: onPlay,
        onPause: onPause,
        onPlayTimeChange: onPlayTimeChange,
        onEnded: onEnded
    };
}

var vimeoPlayer = function() {
    var video,
        divWrapper;

    function init(videoUrl, containerId) {
        var vimeoApi = (function(){
            function Froogaloop(iframe) {
                return new Froogaloop.fn.init(iframe);
            }

            var eventCallbacks = {},
                hasWindowEvent = false,
                isReady = false,
                slice = Array.prototype.slice,
                playerOrigin = '*';

            Froogaloop.fn = Froogaloop.prototype = {
                element: null,

                init: function(iframe) {
                    if (typeof iframe === "string") {
                        iframe = document.getElementById(iframe);
                    }

                    this.element = iframe;

                    return this;
                },

                api: function(method, valueOrCallback) {
                    if (!this.element || !method) {
                        return false;
                    }

                    var self = this,
                        element = self.element,
                        target_id = element.id !== '' ? element.id : null,
                        params = !isFunction(valueOrCallback) ? valueOrCallback : null,
                        callback = isFunction(valueOrCallback) ? valueOrCallback : null;

                    if (callback) {
                        storeCallback(method, callback, target_id);
                    }

                    postMessage(method, params, element);
                    return self;
                },

                addEvent: function(eventName, callback) {
                    if (!this.element) {
                        return false;
                    }

                    var self = this,
                        element = self.element,
                        target_id = element.id !== '' ? element.id : null;

                    storeCallback(eventName, callback, target_id);

                    if (eventName != 'ready') {
                        postMessage('addEventListener', eventName, element);
                    }
                    else if (eventName == 'ready' && isReady) {
                        callback.call(null, target_id);
                    }

                    return self;
                },

                removeEvent: function(eventName) {
                    if (!this.element) {
                        return false;
                    }

                    var self = this,
                        element = self.element,
                        target_id = element.id !== '' ? element.id : null,
                        removed = removeCallback(eventName, target_id);

                    if (eventName != 'ready' && removed) {
                        postMessage('removeEventListener', eventName, element);
                    }
                }
            };

            function postMessage(method, params, target) {
                if (!target.contentWindow.postMessage) {
                    return false;
                }

                var data = JSON.stringify({
                    method: method,
                    value: params
                });

                target.contentWindow.postMessage(data, playerOrigin);
            }

            function onMessageReceived(event) {
                var data, method;

                try {
                    data = JSON.parse(event.data);
                    method = data.event || data.method;
                }
                catch(e) {
                }

                if (method == 'ready' && !isReady) {
                    isReady = true;
                }

                if (!(/^https?:\/\/player.vimeo.com/).test(event.origin)) {
                    return false;
                }

                if (playerOrigin === '*') {
                    playerOrigin = event.origin;
                }

                var value = data.value,
                    eventData = data.data,
                    target_id = target_id === '' ? null : data.player_id,

                    callback = getCallback(method, target_id),
                    params = [];

                if (!callback) {
                    return false;
                }

                if (value !== undefined) {
                    params.push(value);
                }

                if (eventData) {
                    params.push(eventData);
                }

                if (target_id) {
                    params.push(target_id);
                }

                return params.length > 0 ? callback.apply(null, params) : callback.call();
            }

            function storeCallback(eventName, callback, target_id) {
                if (target_id) {
                    if (!eventCallbacks[target_id]) {
                        eventCallbacks[target_id] = {};
                    }
                    eventCallbacks[target_id][eventName] = callback;
                }
                else {
                    eventCallbacks[eventName] = callback;
                }
            }

            function getCallback(eventName, target_id) {
                if (target_id) {
                    return eventCallbacks[target_id][eventName];
                }
                else {
                    return eventCallbacks[eventName];
                }
            }

            function removeCallback(eventName, target_id) {
                if (target_id && eventCallbacks[target_id]) {
                    if (!eventCallbacks[target_id][eventName]) {
                        return false;
                    }
                    eventCallbacks[target_id][eventName] = null;
                }
                else {
                    if (!eventCallbacks[eventName]) {
                        return false;
                    }
                    eventCallbacks[eventName] = null;
                }

                return true;
            }

            function isFunction(obj) {
                return !!(obj && obj.constructor && obj.call && obj.apply);
            }

            function isArray(obj) {
                return toString.call(obj) === '[object Array]';
            }

            Froogaloop.fn.init.prototype = Froogaloop.fn;

            if (window.addEventListener) {
                window.addEventListener('message', onMessageReceived, false);
            }
            else {
                window.attachEvent('onmessage', onMessageReceived);
            }

            return Froogaloop;

        })();

        this.baseUrl = 'https://player.vimeo.com/video/';
        this.videoId = videoUrl.split('//player.vimeo.com/video/')[1];

        this.iframe = document.createElement('iframe');
        this.iframe.setAttribute('title', 'Vimeo Video Player');
        this.iframe.setAttribute('class', 'vimeoplayer');
        this.iframe.setAttribute('src', this.baseUrl + this.videoId + '?api=1');
        this.iframe.setAttribute('frameborder', '0');
        this.iframe.setAttribute('scrolling', 'no');
        this.iframe.setAttribute('marginWidth', '0');
        this.iframe.setAttribute('marginHeight', '0');
        this.iframe.setAttribute('webkitAllowFullScreen', '0');
        this.iframe.setAttribute('mozallowfullscreen', '0');
        this.iframe.setAttribute('allowFullScreen', '0');

        video = vimeoApi(this.iframe);

        divWrapper = document.createElement('div');
        divWrapper.setAttribute('style', 'margin:0 auto;padding-bottom:56.25%;width:100%;height:0;position:relative;overflow:hidden;');
        divWrapper.setAttribute('class', 'vimeoFrame');
        divWrapper.appendChild(this.iframe);
        document.getElementById(containerId).appendChild(divWrapper);
        video.addEvent('ready', setPlayerInformationCallbacks);
    }

    var _volume = 1.0,
        _duration = 0,
        _currentTime = 0,
        _paused = true,
        _mutedPreviousVolume = 1.0;

    function setPlayerInformationCallbacks() {
        video.addEvent('pause', function() {_paused = true;});
        video.addEvent('play', function() {_paused = false;});
        video.addEvent('playProgress', function(value) {_currentTime = value.seconds;});
        video.addEvent('loadProgress', function(value) {_duration = value.duration});
        video.api('getVolume', function(value) {_volume = value;});
        video.api('getDuration', function(value) {_duration = value;});
    }

    function play() {
        video.api('play');
    }

    function pause() {
        video.api('pause');
    }

    function destroy() {
        divWrapper.remove();
    }
    function paused() {
        return _paused;
    }

    function duration() {
        return _duration;
    }

    function currentTime() {
        return _currentTime;
    }

    function setCurrentTime(time) {
        var wasPaused = _paused;
        video.api('seekTo', time);
        if (wasPaused) player.pause();
    }

    function ended() {
        return currentTime() === duration();
    }

    function volume() {
        return _volume;
    }

    function setVolume(vol) {
        video.api('setVolume', vol);
        _volume = vol;
    }

    function muted() {
        return volume() === 0;
    }

    function mute() {
        _mutedPreviousVolume = volume();
        setVolume(0);
    }

    function unmute() {
        video.api('setVolume', _mutedPreviousVolume);
        _volume = _mutedPreviousVolume;
    }

    function onDurationAvailable(callback) {
    }

    function onPlay(callback) {
    }

    function onPause(callback) {
    }

    function onPlayTimeChange(callback) {
    }

    function onEnded(callback) {
    }

    return {
        init: init,
        play: play,
        pause: pause,
        destroy: destroy,
        paused: paused,
        duration: duration,
        currentTime: currentTime,
        setCurrentTime: setCurrentTime,
        ended: ended,
        volume: volume,
        setVolume: setVolume,
        muted: muted,
        mute: mute,
        unmute: unmute,
        onDurationAvailable: onDurationAvailable,
        onPlay: onPlay,
        onPause: onPause,
        onPlayTimeChange: onPlayTimeChange,
        onEnded: onEnded
    };
}

var pybossaPlayer = function(videoUrl, containerId) {
    var player;

    if (videoUrl.split('.').indexOf('vimeo') !== -1) {
        player = vimeoPlayer();
    }
    else {
        player = html5Player();
    }

    player.init(videoUrl, containerId);

    function play() {
        player.play();
    }

    function pause() {
        player.pause();
    }

    function destroy() {
        player.destroy();
    }

    function paused() {
        return player.paused();
    }

    function duration() {
        return player.duration();
    }

    function currentTime() {
        return player.currentTime();
    }

    function setCurrentTime(time) {
        player.setCurrentTime(time);
    }

    function ended() {
        return player.ended();
    }

    function volume() {
        return player.volume();
    }

    function setVolume(volume) {
        player.setVolume(volume);
    }

    function muted() {
        return player.muted();
    }

    function mute() {
        player.mute();
    }

    function unmute() {
        player.unmute();
    }

    function onDurationAvailable(callback) {
        player.onDurationAvailable(callback);
    }

    function onPlay(callback) {
        player.onPlay(callback);
    }

    function onPause(callback) {
        player.onPause(callback);
    }

    function onPlayTimeChange(callback) {
        player.onPlayTimeChange(callback);
    }

    function onEnded(callback) {
        player.onEnded(callback);
    }

    return {
        play: play,
        pause: pause,
        destroy: destroy,
        paused: paused,
        duration: duration,
        currentTime: currentTime,
        setCurrentTime: setCurrentTime,
        ended: ended,
        volume: volume,
        setVolume: setVolume,
        muted: muted,
        mute: mute,
        unmute: unmute,
        onDurationAvailable: onDurationAvailable,
        onPlay: onPlay,
        onPause: onPause,
        onPlayTimeChange: onPlayTimeChange,
        onEnded: onEnded
    };
}
<commit_msg>Modify Froogaloop code to support multiple callbacks per event<commit_after>var html5Player = function() {
    var video;

    function init(videoUrl, containerId) {
        video = document.createElement("video");
        video.setAttribute("src", videoUrl);
        video.setAttribute("width", 512);
        video.setAttribute('controls', true);
        document.getElementById(containerId).appendChild(video);
    }

    function play() {
        video.play();
    }

    function pause() {
        video.pause();
    }

    function destroy() {
        video.remove();
    }

    function paused() {
        return video.paused;
    }

    function duration() {
        return video.duration;
    }

    function currentTime() {
        return video.currentTime;
    }

    function setCurrentTime(time) {
        video.currentTime = time;
    }

    function ended() {
        return video.ended;
    }

    function volume() {
        return video.volume;
    }

    function setVolume(volume) {
        video.volume = volume;
    }

    function muted() {
        return video.muted;
    }

    function mute() {
        video.muted = true;
    }

    function unmute() {
        video.muted = false;
    }

    function onDurationAvailable(callback) {
        var onLoadedMetadata = function() {callback(duration());};
        video.addEventListener('loadedmetadata', onLoadedMetadata);
    }

    function onPlay(callback) {
        video.addEventListenºer('playing', callback);
    }

    function onPause(callback) {
        video.addEventListener('pause', callback);
    }

    function onPlayTimeChange(callback) {
        video.addEventListener('timeupdate', callback);
    }

    function onEnded(callback) {
        video.addEventListener('ended', callback);
    }

    return {
        init: init,
        play: play,
        pause: pause,
        destroy: destroy,
        paused: paused,
        duration: duration,
        currentTime: currentTime,
        setCurrentTime: setCurrentTime,
        ended: ended,
        volume: volume,
        setVolume: setVolume,
        muted: muted,
        mute: mute,
        unmute: unmute,
        onDurationAvailable: onDurationAvailable,
        onPlay: onPlay,
        onPause: onPause,
        onPlayTimeChange: onPlayTimeChange,
        onEnded: onEnded
    };
}

var vimeoPlayer = function() {
    var video,
        divWrapper;

    function init(videoUrl, containerId) {
        var vimeoApi = (function(){
            function Froogaloop(iframe) {
                return new Froogaloop.fn.init(iframe);
            }

            var eventCallbacks = {},
                hasWindowEvent = false,
                isReady = false,
                slice = Array.prototype.slice,
                playerOrigin = '*';

            Froogaloop.fn = Froogaloop.prototype = {
                element: null,

                init: function(iframe) {
                    if (typeof iframe === "string") {
                        iframe = document.getElementById(iframe);
                    }

                    this.element = iframe;

                    return this;
                },

                api: function(method, valueOrCallback) {
                    if (!this.element || !method) {
                        return false;
                    }

                    var self = this,
                        element = self.element,
                        target_id = element.id !== '' ? element.id : null,
                        params = !isFunction(valueOrCallback) ? valueOrCallback : null,
                        callback = isFunction(valueOrCallback) ? valueOrCallback : null;

                    if (callback) {
                        storeCallback(method, callback, target_id);
                    }

                    postMessage(method, params, element);
                    return self;
                },

                addEvent: function(eventName, callback) {
                    if (!this.element) {
                        return false;
                    }

                    var self = this,
                        element = self.element,
                        target_id = element.id !== '' ? element.id : null;

                    storeCallback(eventName, callback, target_id);

                    if (eventName != 'ready') {
                        postMessage('addEventListener', eventName, element);
                    }
                    else if (eventName == 'ready' && isReady) {
                        callback.call(null, target_id);
                    }

                    return self;
                },

                removeEvent: function(eventName) {
                    if (!this.element) {
                        return false;
                    }

                    var self = this,
                        element = self.element,
                        target_id = element.id !== '' ? element.id : null,
                        removed = removeCallbacks(eventName, target_id);

                    if (eventName != 'ready' && removed) {
                        postMessage('removeEventListener', eventName, element);
                    }
                }
            };

            function postMessage(method, params, target) {
                if (!target.contentWindow.postMessage) {
                    return false;
                }

                var data = JSON.stringify({
                    method: method,
                    value: params
                });

                target.contentWindow.postMessage(data, playerOrigin);
            }

            function onMessageReceived(event) {
                var data, method;

                try {
                    data = JSON.parse(event.data);
                    method = data.event || data.method;
                }
                catch(e) {
                }

                if (method == 'ready' && !isReady) {
                    isReady = true;
                }

                if (!(/^https?:\/\/player.vimeo.com/).test(event.origin)) {
                    return false;
                }

                if (playerOrigin === '*') {
                    playerOrigin = event.origin;
                }

                var value = data.value,
                    eventData = data.data,
                    target_id = target_id === '' ? null : data.player_id,

                    callbacks = getCallbacks(method, target_id),
                    params = [];

                if (!callbacks) {
                    return false;
                }

                if (value !== undefined) {
                    params.push(value);
                }

                if (eventData) {
                    params.push(eventData);
                }

                if (target_id) {
                    params.push(target_id);
                }

                callbacks.forEach(function(callback) {
                    params.length > 0 ? callback.apply(null, params) : callback.call();
                });
            }

            function storeCallback(eventName, callback, target_id) {
                if (target_id) {
                    if (!eventCallbacks[target_id]) {
                        eventCallbacks[target_id] = {};
                    }
                    if (!eventCallbacks[target_id][eventName]) {
                        eventCallbacks[target_id][eventName] = [];
                    }
                    eventCallbacks[target_id][eventName].push(callback);
                }
                else {
                    if (!eventCallbacks[eventName]) {
                        eventCallbacks[eventName] = [];
                    }
                    eventCallbacks[eventName].push(callback);
                }
            }

            function getCallbacks(eventName, target_id) {
                if (target_id) {
                    return eventCallbacks[target_id][eventName];
                }
                else {
                    return eventCallbacks[eventName];
                }
            }

            function removeCallbacks(eventName, target_id) {
                if (target_id && eventCallbacks[target_id]) {
                    if (!eventCallbacks[target_id][eventName]) {
                        return false;
                    }
                    eventCallbacks[target_id][eventName] = null;
                }
                else {
                    if (!eventCallbacks[eventName]) {
                        return false;
                    }
                    eventCallbacks[eventName] = null;
                }

                return true;
            }

            function isFunction(obj) {
                return !!(obj && obj.constructor && obj.call && obj.apply);
            }

            function isArray(obj) {
                return toString.call(obj) === '[object Array]';
            }

            Froogaloop.fn.init.prototype = Froogaloop.fn;

            if (window.addEventListener) {
                window.addEventListener('message', onMessageReceived, false);
            }
            else {
                window.attachEvent('onmessage', onMessageReceived);
            }

            return Froogaloop;

        })();

        this.baseUrl = 'https://player.vimeo.com/video/';
        this.videoId = videoUrl.split('//player.vimeo.com/video/')[1];

        this.iframe = document.createElement('iframe');
        this.iframe.setAttribute('title', 'Vimeo Video Player');
        this.iframe.setAttribute('class', 'vimeoplayer');
        this.iframe.setAttribute('src', this.baseUrl + this.videoId + '?api=1');
        this.iframe.setAttribute('frameborder', '0');
        this.iframe.setAttribute('scrolling', 'no');
        this.iframe.setAttribute('marginWidth', '0');
        this.iframe.setAttribute('marginHeight', '0');
        this.iframe.setAttribute('webkitAllowFullScreen', '0');
        this.iframe.setAttribute('mozallowfullscreen', '0');
        this.iframe.setAttribute('allowFullScreen', '0');

        video = vimeoApi(this.iframe);

        divWrapper = document.createElement('div');
        divWrapper.setAttribute('style', 'margin:0 auto;padding-bottom:56.25%;width:100%;height:0;position:relative;overflow:hidden;');
        divWrapper.setAttribute('class', 'vimeoFrame');
        divWrapper.appendChild(this.iframe);
        document.getElementById(containerId).appendChild(divWrapper);
        video.addEvent('ready', setPlayerInformationCallbacks);
    }

    var _volume = 1.0,
        _duration = 0,
        _currentTime = 0,
        _paused = true,
        _mutedPreviousVolume = 1.0;

    function setPlayerInformationCallbacks() {
        video.addEvent('pause', function() {_paused = true;});
        video.addEvent('play', function() {_paused = false;});
        video.addEvent('playProgress', function(value) {_currentTime = value.seconds;});
        video.addEvent('loadProgress', function(value) {_duration = value.duration});
        video.api('getVolume', function(value) {_volume = value;});
        video.api('getDuration', function(value) {_duration = value;});
    }

    function play() {
        video.api('play');
    }

    function pause() {
        video.api('pause');
    }

    function destroy() {
        divWrapper.remove();
    }
    function paused() {
        return _paused;
    }

    function duration() {
        return _duration;
    }

    function currentTime() {
        return _currentTime;
    }

    function setCurrentTime(time) {
        var wasPaused = _paused;
        video.api('seekTo', time);
        if (wasPaused) player.pause();
    }

    function ended() {
        return currentTime() === duration();
    }

    function volume() {
        return _volume;
    }

    function setVolume(vol) {
        video.api('setVolume', vol);
        _volume = vol;
    }

    function muted() {
        return volume() === 0;
    }

    function mute() {
        _mutedPreviousVolume = volume();
        setVolume(0);
    }

    function unmute() {
        video.api('setVolume', _mutedPreviousVolume);
        _volume = _mutedPreviousVolume;
    }

    function onDurationAvailable(callback) {
    }

    function onPlay(callback) {
    }

    function onPause(callback) {
    }

    function onPlayTimeChange(callback) {
    }

    function onEnded(callback) {
    }

    return {
        init: init,
        play: play,
        pause: pause,
        destroy: destroy,
        paused: paused,
        duration: duration,
        currentTime: currentTime,
        setCurrentTime: setCurrentTime,
        ended: ended,
        volume: volume,
        setVolume: setVolume,
        muted: muted,
        mute: mute,
        unmute: unmute,
        onDurationAvailable: onDurationAvailable,
        onPlay: onPlay,
        onPause: onPause,
        onPlayTimeChange: onPlayTimeChange,
        onEnded: onEnded
    };
}

var pybossaPlayer = function(videoUrl, containerId) {
    var player;

    if (videoUrl.split('.').indexOf('vimeo') !== -1) {
        player = vimeoPlayer();
    }
    else {
        player = html5Player();
    }

    player.init(videoUrl, containerId);

    function play() {
        player.play();
    }

    function pause() {
        player.pause();
    }

    function destroy() {
        player.destroy();
    }

    function paused() {
        return player.paused();
    }

    function duration() {
        return player.duration();
    }

    function currentTime() {
        return player.currentTime();
    }

    function setCurrentTime(time) {
        player.setCurrentTime(time);
    }

    function ended() {
        return player.ended();
    }

    function volume() {
        return player.volume();
    }

    function setVolume(volume) {
        player.setVolume(volume);
    }

    function muted() {
        return player.muted();
    }

    function mute() {
        player.mute();
    }

    function unmute() {
        player.unmute();
    }

    function onDurationAvailable(callback) {
        player.onDurationAvailable(callback);
    }

    function onPlay(callback) {
        player.onPlay(callback);
    }

    function onPause(callback) {
        player.onPause(callback);
    }

    function onPlayTimeChange(callback) {
        player.onPlayTimeChange(callback);
    }

    function onEnded(callback) {
        player.onEnded(callback);
    }

    return {
        play: play,
        pause: pause,
        destroy: destroy,
        paused: paused,
        duration: duration,
        currentTime: currentTime,
        setCurrentTime: setCurrentTime,
        ended: ended,
        volume: volume,
        setVolume: setVolume,
        muted: muted,
        mute: mute,
        unmute: unmute,
        onDurationAvailable: onDurationAvailable,
        onPlay: onPlay,
        onPause: onPause,
        onPlayTimeChange: onPlayTimeChange,
        onEnded: onEnded
    };
}
<|endoftext|>


<commit_before>var PMath = Particulate.Math;
App.PointRepulsorForce = PointRepulsorForce;

function PointRepulsorForce(position, opts) {
  opts = opts || {};
  Particulate.Force.apply(this, arguments);

  this.position = this.vector;
  this.intensity = opts.intensity != null ? opts.intensity : 0.05;
  this.setRadius(opts.radius || 0);
}

PointRepulsorForce.create = Particulate.ctor(PointRepulsorForce);
PointRepulsorForce.prototype = Object.create(Particulate.Force.prototype);
PointRepulsorForce.prototype.constructor = PointRepulsorForce;

PointRepulsorForce.prototype.setRadius = function (r) {
  this._radius2 = r * r;
};

PointRepulsorForce.prototype.applyForce = function (ix, f0, p0, p1) {
  var v0 = this.vector;
  var iy = ix + 1;
  var iz = ix + 2;

  var dx = p0[ix] - v0[0];
  var dy = p0[iy] - v0[1];
  var dz = p0[iz] - v0[2];

  var dist = dx * dx + dy * dy + dz * dz;
  var diff = PMath.clamp(0.001, 100,
    dist - this._radius2 * this.intensity);
  var diffInv = 1 / diff;
	var scale = PMath.clamp(0, 10,
		diffInv * diffInv * diffInv);

  f0[ix] += dx * scale;
  f0[iy] += dy * scale;
  f0[iz] += dz * scale;
};
<commit_msg>Whitespace <commit_after>var PMath = Particulate.Math;
App.PointRepulsorForce = PointRepulsorForce;

function PointRepulsorForce(position, opts) {
  opts = opts || {};
  Particulate.Force.apply(this, arguments);

  this.position = this.vector;
  this.intensity = opts.intensity != null ? opts.intensity : 0.05;
  this.setRadius(opts.radius || 0);
}

PointRepulsorForce.create = Particulate.ctor(PointRepulsorForce);
PointRepulsorForce.prototype = Object.create(Particulate.Force.prototype);
PointRepulsorForce.prototype.constructor = PointRepulsorForce;

PointRepulsorForce.prototype.setRadius = function (r) {
  this._radius2 = r * r;
};

PointRepulsorForce.prototype.applyForce = function (ix, f0, p0, p1) {
  var v0 = this.vector;
  var iy = ix + 1;
  var iz = ix + 2;

  var dx = p0[ix] - v0[0];
  var dy = p0[iy] - v0[1];
  var dz = p0[iz] - v0[2];

  var dist = dx * dx + dy * dy + dz * dz;
  var diff = PMath.clamp(0.001, 100,
    dist - this._radius2 * this.intensity);
  var diffInv = 1 / diff;
  var scale = PMath.clamp(0, 10,
    diffInv * diffInv * diffInv);

  f0[ix] += dx * scale;
  f0[iy] += dy * scale;
  f0[iz] += dz * scale;
};
<|endoftext|>


<commit_before>/*
 * ***** BEGIN LICENSE BLOCK *****
 * OpenPGP Zimbra Secure is the open source digital signature and encrypt for Zimbra Collaboration Open Source Edition software
 * Copyright (C) 2016-present OpenPGP Zimbra Secure

 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.

 * This program 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 program. If not, see <http://www.gnu.org/licenses/>
 * ***** END LICENSE BLOCK *****
 *
 * OpenPGP MIME Secure Email Zimlet
 *
 * Written by nguyennv1981@gmail.com
 */

OpenPGPDialog = function(handler, title, onOk, onCancel, standardButtons) {
    ZmDialog.call(this, {
        title: title,
        parent: handler.getShell(),
        className: "OpenPGP dialog",
        standardButtons: standardButtons
    });
    this._handler = handler;
    this._onOk = onOk;
    this._onCancel = onCancel;

    var submitListener = new AjxListener(this, this._dialogSubmit);
    var onCancel = new AjxListener(this, this._dialogCancel);

    if (this._button[DwtDialog.OK_BUTTON]) {
        this.setButtonListener(DwtDialog.OK_BUTTON, submitListener);
    }
    if (this._button[DwtDialog.CANCEL_BUTTON]) {
        this.registerCallback(DwtDialog.CANCEL_BUTTON, onCancel);
    }
    this.setEnterListener(submitListener);
    this._createContent();
    this._initialize();
};

OpenPGPDialog.prototype = new ZmDialog;
OpenPGPDialog.prototype.constructor = OpenPGPDialog;

OpenPGPDialog.prototype.toString = function() {
    return "OpenPGPDialog";
};

OpenPGPDialog.prototype._dialogSubmit = function() {
    var retVal;
    if (this._onOk instanceof AjxCallback) {
        retVal = this._onOk.run();
    } else if (AjxUtil.isFunction(this._onOk)) {
        retVal = this._onOk();
    }
    if (retVal !== false) {
        this.popdown();
    }
};

OpenPGPDialog.prototype._dialogCancel = function() {
    this.popdown();
    if (this._onCancel instanceof AjxCallback) {
        this._onCancel.run();
    } else if (AjxUtil.isFunction(this._onCancel)) {
        this._onCancel();
    }
};

OpenPGPDialog.prototype.popup = function(onOk, onCancel) {
    if (onOk) {
        this._onOk = onOk;
    }
    if (onCancel) {
        this._onCancel = onCancel;
    }
    DwtDialog.prototype.popup.call(this);
    if (this._focusElement) {
        appCtxt.getKeyboardMgr().grabFocus(this._focusElement);
    }
};

OpenPGPDialog.prototype.clearContentElement = function() {
    while (this._contentEl.hasChildNodes()) {
        this._contentEl.removeChild(this._contentEl.firstChild);
    }
};

OpenPGPDialog.prototype.setContentElement = function(el) {
    this.clearContentElement();
    this._contentEl.appendChild(el);
};

OpenPGPDialog.prototype.getContentContainer = function(el) {
    return this._contentEl;
};

OpenPGPDialog.prototype._createContent = function() {
    if (this.CONTENT_TEMPLATE) {
        this.setContent(AjxTemplate.expand(this.CONTENT_TEMPLATE, this._getTemplateData()));
    }
};

OpenPGPDialog.prototype._getTemplateData = function() {
    return {};
};

OpenPGPDialog.prototype._initialize = function() {
};
<commit_msg>Update pgp dialog class<commit_after>/*
 * ***** BEGIN LICENSE BLOCK *****
 * OpenPGP Zimbra Secure is the open source digital signature and encrypt for Zimbra Collaboration Open Source Edition software
 * Copyright (C) 2016-present OpenPGP Zimbra Secure

 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.

 * This program 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 program. If not, see <http://www.gnu.org/licenses/>
 * ***** END LICENSE BLOCK *****
 *
 * OpenPGP MIME Secure Email Zimlet
 *
 * Written by nguyennv1981@gmail.com
 */

OpenPGPDialog = function(handler, title, onOk, onCancel, standardButtons) {
    ZmDialog.call(this, {
        title: title,
        parent: handler.getShell(),
        className: "OpenPGP dialog",
        standardButtons: standardButtons
    });
    this._handler = handler;
    this._onOk = onOk;
    this._onCancel = onCancel;

    var submitListener = new AjxListener(this, this._dialogSubmit);
    var cancelListener = new AjxListener(this, this._dialogCancel);

    if (this._button[DwtDialog.OK_BUTTON]) {
        this.setButtonListener(DwtDialog.OK_BUTTON, submitListener);
    }
    if (this._button[DwtDialog.CANCEL_BUTTON]) {
        this.registerCallback(DwtDialog.CANCEL_BUTTON, cancelListener);
    }
    this.setEnterListener(submitListener);
    this._createContent();
    this._initialize();
};

OpenPGPDialog.prototype = new ZmDialog;
OpenPGPDialog.prototype.constructor = OpenPGPDialog;

OpenPGPDialog.prototype.toString = function() {
    return "OpenPGPDialog";
};

OpenPGPDialog.prototype._dialogSubmit = function() {
    var result;
    if (this._onOk instanceof AjxCallback) {
        result = this._onOk.run();
    } else if (AjxUtil.isFunction(this._onOk)) {
        result = this._onOk();
    }
    if (result !== false) {
        this.popdown();
    }
};

OpenPGPDialog.prototype._dialogCancel = function() {
    this.popdown();
    if (this._onCancel instanceof AjxCallback) {
        this._onCancel.run();
    } else if (AjxUtil.isFunction(this._onCancel)) {
        this._onCancel();
    }
};

OpenPGPDialog.prototype.popup = function(onOk, onCancel) {
    if (onOk) {
        this._onOk = onOk;
    }
    if (onCancel) {
        this._onCancel = onCancel;
    }
    DwtDialog.prototype.popup.call(this);
    if (this._focusElement) {
        appCtxt.getKeyboardMgr().grabFocus(this._focusElement);
    }
};

OpenPGPDialog.prototype.clearContentElement = function() {
    while (this._contentEl.hasChildNodes()) {
        this._contentEl.removeChild(this._contentEl.firstChild);
    }
};

OpenPGPDialog.prototype.setContentElement = function(el) {
    this.clearContentElement();
    this._contentEl.appendChild(el);
};

OpenPGPDialog.prototype.getContentContainer = function(el) {
    return this._contentEl;
};

OpenPGPDialog.prototype._createContent = function() {
    if (this.CONTENT_TEMPLATE) {
        this.setContent(AjxTemplate.expand(this.CONTENT_TEMPLATE, this._getTemplateData()));
    }
};

OpenPGPDialog.prototype._getTemplateData = function() {
    return {};
};

OpenPGPDialog.prototype._initialize = function() {
};
<|endoftext|>


<commit_before>angular.module( 'gj.Game' ).factory( 'Game', function( $state, Model, Environment, User, MediaItem, Registry )
{
	Registry.setConfig( 'Game', {
		maxItems: 50,
	} );

	function Game( data )
	{
		if ( data ) {
			angular.extend( this, data );

			if ( data.developer && angular.isObject( data.developer ) ) {
				this.developer = new User( data.developer );
			}

			if ( data.thumbnail_media_item && angular.isObject( data.thumbnail_media_item ) ) {
				this.thumbnail_media_item = new MediaItem( data.thumbnail_media_item );
			}

			if ( data.header_media_item && angular.isObject( data.header_media_item ) ) {
				this.header_media_item = new MediaItem( data.header_media_item );
			}
		}

		this.is_published = false;
		if ( this.status == Game.STATUS_VISIBLE ) {
			this.is_published = true;
		}

		this._has_packages = false;
		if ( this.compatibility ) {
			var keys = Object.keys( this.compatibility );
			for ( var i in keys ) {
				if ( keys[ i ] != 'id' && keys[ i ] != 'game_id' ) {
					this._has_packages = true;
					break;
				}
			}
		}

		// We don't want to show ads if this game has sellable items.
		this._should_show_ads = true;
		if ( !this.ads_enabled ) {
			this._should_show_ads = false;
		}
		else if ( this.sellable && this.sellable.type != 'free' ) {
			this._should_show_ads = false;
		}

		Registry.store( 'Game', this );
	}

	Game.STATUS_HIDDEN = 0;
	Game.STATUS_VISIBLE = 1;
	Game.STATUS_REMOVED = 2;

	Game.DEVELOPMENT_STATUS_FINISHED = 1;
	Game.DEVELOPMENT_STATUS_WIP = 2;
	Game.DEVELOPMENT_STATUS_CANCELED = 3;

	Game.prototype.getSref = function( page, includeParams )
	{
		var sref = '';

		if ( page == 'dashboard' ) {
			sref = 'dashboard.developer.games.manage.game.overview';
		}
		else if ( page == 'edit' ) {
			sref = 'dashboard.developer.games.manage.game.edit';
		}
		else {
			sref = 'discover.games.view.overview';
		}

		if ( includeParams ) {
			sref += '( ' + angular.toJson( this.getSrefParams( page ) ) + ' )'
		}

		return sref;
	};

	Game.prototype.getSrefParams = function( page )
	{
		if ( [ 'dashboard', 'edit' ].indexOf( page ) !== -1 ) {
			return { id: this.id };
		}

		return {
			id: this.id,
			category: this.category_slug,
			slug: this.slug
		};
	};

	Game.prototype.getUrl = function( page )
	{
		if ( page == 'soundtrack' ) {
			return '/games/' + this.slug + '/' + this.id + '/download/soundtrack';
		}

		return $state.href( this.getSref( page ), this.getSrefParams( page ) );
	};

	Game.prototype.hasDesktopSupport = function()
	{
		var compat = this.compatibility;
		return compat.os_windows
			|| compat.os_windows_64
			|| compat.os_mac
			|| compat.os_mac_64
			|| compat.os_linux
			|| compat.os_linux_64
			;
	};

	Game.prototype.hasBrowserSupport = function()
	{
		var compat = this.compatibility;
		return compat.type_html
			|| compat.type_flash
			|| compat.type_unity
			|| compat.type_applet
			|| compat.type_silverlight
			;
	};

	/**
	 * Helper function to check if the resource passed in has support for the
	 * os/arch passed in.
	 */
	Game.checkDeviceSupport = function( obj, os, arch )
	{
		if ( obj[ 'os_' + os ] ) {
			return true;
		}

		// If they are on 64bit, then we can check for 64bit only support as well.
		// If there is no arch (web site context) then we allow 64bit builds as well.
		if ( (!arch || arch == '64') && obj[ 'os_' + os + '_64' ] ) {
			return true;
		}

		return false;
	};

	Game.prototype.canInstall = function( os, arch )
	{
		// Obviously can't install if no desktop build.
		if ( !this.hasDesktopSupport() ) {
			return false;
		}

		return Game.checkDeviceSupport( this.compatibility, os, arch );
	};

	Game.pluckInstallableBuilds = function( packages, os, arch )
	{
		var pluckedBuilds = [];

		packages.forEach( function( _package )
		{
			_package._builds.forEach( function( build )
			{
				if ( Game.checkDeviceSupport( build, os, arch ) ) {
					pluckedBuilds.push( build );
				}
			} );
		} );

		return pluckedBuilds;
	};

	Game.pluckBrowserBuilds = function( packages )
	{
		var pluckedBuilds = [];

		packages.forEach( function( _package )
		{
			_package._builds.forEach( function( build )
			{
				if ( build.isBrowserBased() ) {
					pluckedBuilds.push( build );
				}
			} );
		} );

		return pluckedBuilds;
	};

	Game.pluckRomBuilds = function( packages )
	{
		var pluckedBuilds = [];

		packages.forEach( function( _package )
		{
			_package._builds.forEach( function( build )
			{
				if ( build.isRom() ) {
					pluckedBuilds.push( build );
				}
			} );
		} );

		return pluckedBuilds;
	};

	Game.chooseBestBuild = function( builds, os, arch )
	{
		var build, search;

		if ( arch == '64' ) {
			search = {};
			search[ 'os_' + os + '_64' ] = true;
			if ( build = _.find( builds, search ) ) {
				return build;
			}
		}

		search = {};
		search[ 'os_' + os ] = true;
		if ( build = _.find( builds, search ) ) {
			return build;
		}

		return builds[0];
	};

	Game.prototype.$save = function()
	{
		if ( this.id ) {
			return this.$_save( '/web/dash/developer/games/save/' + this.id, 'game' );
		}
		else {
			return this.$_save( '/web/dash/developer/games/save', 'game' );
		}
	};

	Game.prototype.$saveMaturity = function()
	{
		return this.$_save( '/web/dash/developer/games/maturity/save/' + this.id, 'game' );
	};

	Game.prototype.$saveThumbnail = function()
	{
		return this.$_save( '/web/dash/developer/games/thumbnail/save/' + this.id, 'game', { file: this.file, allowComplexData: [ 'crop' ] } );
	};

	Game.prototype.$saveHeader = function()
	{
		return this.$_save( '/web/dash/developer/games/header/save/' + this.id, 'game', { file: this.file } );
	};

	Game.prototype.$clearHeader = function()
	{
		return this.$_save( '/web/dash/developer/games/header/clear/' + this.id, 'game' );
	};

	Game.prototype.$setStatus = function( status )
	{
		return this.$_save( '/web/dash/developer/games/set-status/' + this.id + '/' + status, 'game' );
	};

	Game.prototype.$saveSettings = function()
	{
		return this.$_save( '/web/dash/developer/games/settings/save/' + this.id, 'game' );
	};

	Game.prototype.$remove = function( status )
	{
		return this.$_remove( '/web/dash/developer/games/remove/' + this.id );
	};

	return Model.create( Game );
} );
<commit_msg>Make game model not dependent on Registry being available.<commit_after>angular.module( 'gj.Game' ).factory( 'Game', function( $state, $injector, Model, Environment, User, MediaItem )
{
	if ( $injector.has( 'Registry' ) ) {
		$injector.get( 'Registry' ).setConfig( 'Game', {
			maxItems: 50,
		} );
	}

	function Game( data )
	{
		if ( data ) {
			angular.extend( this, data );

			if ( data.developer && angular.isObject( data.developer ) ) {
				this.developer = new User( data.developer );
			}

			if ( data.thumbnail_media_item && angular.isObject( data.thumbnail_media_item ) ) {
				this.thumbnail_media_item = new MediaItem( data.thumbnail_media_item );
			}

			if ( data.header_media_item && angular.isObject( data.header_media_item ) ) {
				this.header_media_item = new MediaItem( data.header_media_item );
			}
		}

		this.is_published = false;
		if ( this.status == Game.STATUS_VISIBLE ) {
			this.is_published = true;
		}

		this._has_packages = false;
		if ( this.compatibility ) {
			var keys = Object.keys( this.compatibility );
			for ( var i in keys ) {
				if ( keys[ i ] != 'id' && keys[ i ] != 'game_id' ) {
					this._has_packages = true;
					break;
				}
			}
		}

		// We don't want to show ads if this game has sellable items.
		this._should_show_ads = true;
		if ( !this.ads_enabled ) {
			this._should_show_ads = false;
		}
		else if ( this.sellable && this.sellable.type != 'free' ) {
			this._should_show_ads = false;
		}

		if ( $injector.has( 'Registry' ) ) {
			$injector.get( 'Registry' ).store( 'Game', this );
		}
	}

	Game.STATUS_HIDDEN = 0;
	Game.STATUS_VISIBLE = 1;
	Game.STATUS_REMOVED = 2;

	Game.DEVELOPMENT_STATUS_FINISHED = 1;
	Game.DEVELOPMENT_STATUS_WIP = 2;
	Game.DEVELOPMENT_STATUS_CANCELED = 3;

	Game.prototype.getSref = function( page, includeParams )
	{
		var sref = '';

		if ( page == 'dashboard' ) {
			sref = 'dashboard.developer.games.manage.game.overview';
		}
		else if ( page == 'edit' ) {
			sref = 'dashboard.developer.games.manage.game.edit';
		}
		else {
			sref = 'discover.games.view.overview';
		}

		if ( includeParams ) {
			sref += '( ' + angular.toJson( this.getSrefParams( page ) ) + ' )'
		}

		return sref;
	};

	Game.prototype.getSrefParams = function( page )
	{
		if ( [ 'dashboard', 'edit' ].indexOf( page ) !== -1 ) {
			return { id: this.id };
		}

		return {
			id: this.id,
			category: this.category_slug,
			slug: this.slug
		};
	};

	Game.prototype.getUrl = function( page )
	{
		if ( page == 'soundtrack' ) {
			return '/games/' + this.slug + '/' + this.id + '/download/soundtrack';
		}

		return $state.href( this.getSref( page ), this.getSrefParams( page ) );
	};

	Game.prototype.hasDesktopSupport = function()
	{
		var compat = this.compatibility;
		return compat.os_windows
			|| compat.os_windows_64
			|| compat.os_mac
			|| compat.os_mac_64
			|| compat.os_linux
			|| compat.os_linux_64
			;
	};

	Game.prototype.hasBrowserSupport = function()
	{
		var compat = this.compatibility;
		return compat.type_html
			|| compat.type_flash
			|| compat.type_unity
			|| compat.type_applet
			|| compat.type_silverlight
			;
	};

	/**
	 * Helper function to check if the resource passed in has support for the
	 * os/arch passed in.
	 */
	Game.checkDeviceSupport = function( obj, os, arch )
	{
		if ( obj[ 'os_' + os ] ) {
			return true;
		}

		// If they are on 64bit, then we can check for 64bit only support as well.
		// If there is no arch (web site context) then we allow 64bit builds as well.
		if ( (!arch || arch == '64') && obj[ 'os_' + os + '_64' ] ) {
			return true;
		}

		return false;
	};

	Game.prototype.canInstall = function( os, arch )
	{
		// Obviously can't install if no desktop build.
		if ( !this.hasDesktopSupport() ) {
			return false;
		}

		return Game.checkDeviceSupport( this.compatibility, os, arch );
	};

	Game.pluckInstallableBuilds = function( packages, os, arch )
	{
		var pluckedBuilds = [];

		packages.forEach( function( _package )
		{
			_package._builds.forEach( function( build )
			{
				if ( Game.checkDeviceSupport( build, os, arch ) ) {
					pluckedBuilds.push( build );
				}
			} );
		} );

		return pluckedBuilds;
	};

	Game.pluckBrowserBuilds = function( packages )
	{
		var pluckedBuilds = [];

		packages.forEach( function( _package )
		{
			_package._builds.forEach( function( build )
			{
				if ( build.isBrowserBased() ) {
					pluckedBuilds.push( build );
				}
			} );
		} );

		return pluckedBuilds;
	};

	Game.pluckRomBuilds = function( packages )
	{
		var pluckedBuilds = [];

		packages.forEach( function( _package )
		{
			_package._builds.forEach( function( build )
			{
				if ( build.isRom() ) {
					pluckedBuilds.push( build );
				}
			} );
		} );

		return pluckedBuilds;
	};

	Game.chooseBestBuild = function( builds, os, arch )
	{
		var build, search;

		if ( arch == '64' ) {
			search = {};
			search[ 'os_' + os + '_64' ] = true;
			if ( build = _.find( builds, search ) ) {
				return build;
			}
		}

		search = {};
		search[ 'os_' + os ] = true;
		if ( build = _.find( builds, search ) ) {
			return build;
		}

		return builds[0];
	};

	Game.prototype.$save = function()
	{
		if ( this.id ) {
			return this.$_save( '/web/dash/developer/games/save/' + this.id, 'game' );
		}
		else {
			return this.$_save( '/web/dash/developer/games/save', 'game' );
		}
	};

	Game.prototype.$saveMaturity = function()
	{
		return this.$_save( '/web/dash/developer/games/maturity/save/' + this.id, 'game' );
	};

	Game.prototype.$saveThumbnail = function()
	{
		return this.$_save( '/web/dash/developer/games/thumbnail/save/' + this.id, 'game', { file: this.file, allowComplexData: [ 'crop' ] } );
	};

	Game.prototype.$saveHeader = function()
	{
		return this.$_save( '/web/dash/developer/games/header/save/' + this.id, 'game', { file: this.file } );
	};

	Game.prototype.$clearHeader = function()
	{
		return this.$_save( '/web/dash/developer/games/header/clear/' + this.id, 'game' );
	};

	Game.prototype.$setStatus = function( status )
	{
		return this.$_save( '/web/dash/developer/games/set-status/' + this.id + '/' + status, 'game' );
	};

	Game.prototype.$saveSettings = function()
	{
		return this.$_save( '/web/dash/developer/games/settings/save/' + this.id, 'game' );
	};

	Game.prototype.$remove = function( status )
	{
		return this.$_remove( '/web/dash/developer/games/remove/' + this.id );
	};

	return Model.create( Game );
} );
<|endoftext|>


<commit_before>import SaihuBot from './packages/core/src/saihubot.js';
import basicAdapter from './packages/html-adapter/saihubot-html-adapter.js';
import localforageBrain from './packages/html-adapter/saihubot-html-brain-localforage.js';
import {addons as dialogAddons} from './packages/html-adapter/saihubot-html-addon-dialog.js';
import {addons as searchAddons} from './packages/html-adapter/saihubot-html-addon-search.js';
import {skills as helpSkills} from '../packages/html-adapter/saihubot-html-skill-help.js';
import {skills as diagnosSkills} from '../packages/skill-diagnostics/index.js';
import {skills as searchSkills} from '../packages/skill-search/index.js';

//

//

//

//
Can be verified on any platform using docker

//

//
//

//

// user
//

//

//

//
Your error message says permission denied, npm global installs must be given root privileges.

//

//
//

//

const renderMessage = (message, charactor, role = 'bot') => {
  const messageWraper = document.createElement('span');
  messageWraper.className = role === 'bot'
    ? 'px-4 py-2 rounded-lg inline-block rounded-bl-none bg-gray-300 text-gray-600'
    : 'px-4 py-2 rounded-lg inline-block rounded-br-none bg-blue-600 text-white';
  if (typeof message === 'string') {
    messageWraper.textContent = message;
  } else if (message instanceof HTMLElement) {
    messageWraper.appendChild(message);
  }
  const messageDivL3 = document.createElement('div');
  const messageDivL2 = document.createElement('div');
  messageDivL2.className = role === 'bot' ?
    'flex flex-col space-y-2 text-xs max-w-xs mx-2 order-2 items-start' :
    'flex flex-col space-y-2 text-xs max-w-xs mx-2 order-1 items-end';

  const span = document.createElement('span');
  span.textContent = charactor;
  span.className = role === 'bot' ? 'w-6 h-6 rounded-full order-1' : 'w-6 h-6 rounded-full order-2';

  const messageDivL1 = document.createElement('div');
  messageDivL1.className = role === 'bot' ?
    'flex items-end' :
    'flex items-end justify-end';
  const botContainer = document.createElement('div');
  botContainer.className = 'chat-message';
  messageDivL3.appendChild(messageWraper);
  messageDivL2.appendChild(messageDivL3);
  messageDivL1.appendChild(messageDivL2);
  messageDivL1.appendChild(span);
  botContainer.appendChild(messageDivL1);
  return botContainer;
};

document.addEventListener('DOMContentLoaded', function() {
  const skillHome = {
    name: 'home',
    help: 'home - search github for saihubot',
    requirements: {},
    rule: /HOME/i,
    action: function(robot, msg) {
      robot.ask('github saihubot');
    },
  };
  const skillSample = {
    name: 'sample',
    help: 'sample - show saihu samples',
    requirements: {},
    rule: /SAMPLE/i,
    action: function(robot, msg) {
      robot.addons.confirm('Here are samples', [
        {
          title: 'hello',
          id: 'hello',
          rule: /hello/i,
          action: function() {
            robot.send('Open hello bot sample');
            robot.render();
            window.open('samples/index.html', '_blank');
          },
        },
        {
          title: 'skill',
          id: 'skill',
          rule: /SKILL/i,
          action: function() {
            robot.send('Open skill sample');
            robot.render();
            window.open('samples/skill.html', '_blank');
          },
        },
      ]);
    },
  };

  new SaihuBot({
    adapter: basicAdapter,
    brain: localforageBrain,
    welcomeMessage: 'Hello! type `help` to check skills I can serve',
    notFoundMessages: [
      'type `ping`, `time`, or `echo [message]` to see what\'s happened',
      'type `google [keyword]`, `wiki [keyword]` to search',
      'type `help` for full sample commands list',
      'Want more samples? type `samples`',
      'Try refresh the page, messages are cached locally',
      'type `github saihubot` to visit me and give a star!',
      'you can ask anything ex: `siri who is current Us president?`',
    ],
    botAlias: '🤖',
    userAlias: '😎',
    renderMessage,
    renderComponent: renderMessage,
    addons: [...dialogAddons, ...searchAddons],
    skills: [
      ...helpSkills,
      ...diagnosSkills,
      ...searchSkills,
      skillHome,
      skillSample,
    ],
    debug: true,
  });
});
<commit_msg>fix path<commit_after>import SaihuBot from './packages/core/src/saihubot.js';
import basicAdapter from './packages/html-adapter/saihubot-html-adapter.js';
import localforageBrain from './packages/html-adapter/saihubot-html-brain-localforage.js';
import {addons as dialogAddons} from './packages/html-adapter/saihubot-html-addon-dialog.js';
import {addons as searchAddons} from './packages/html-adapter/saihubot-html-addon-search.js';
import {skills as helpSkills} from './packages/html-adapter/saihubot-html-skill-help.js';
import {skills as diagnosSkills} from './packages/skill-diagnostics/index.js';
import {skills as searchSkills} from './packages/skill-search/index.js';

//

//

//

//
Can be verified on any platform using docker

//

//
//

//

// user
//

//

//

//
Your error message says permission denied, npm global installs must be given root privileges.

//

//
//

//

const renderMessage = (message, charactor, role = 'bot') => {
  const messageWraper = document.createElement('span');
  messageWraper.className = role === 'bot'
    ? 'px-4 py-2 rounded-lg inline-block rounded-bl-none bg-gray-300 text-gray-600'
    : 'px-4 py-2 rounded-lg inline-block rounded-br-none bg-blue-600 text-white';
  if (typeof message === 'string') {
    messageWraper.textContent = message;
  } else if (message instanceof HTMLElement) {
    messageWraper.appendChild(message);
  }
  const messageDivL3 = document.createElement('div');
  const messageDivL2 = document.createElement('div');
  messageDivL2.className = role === 'bot' ?
    'flex flex-col space-y-2 text-xs max-w-xs mx-2 order-2 items-start' :
    'flex flex-col space-y-2 text-xs max-w-xs mx-2 order-1 items-end';

  const span = document.createElement('span');
  span.textContent = charactor;
  span.className = role === 'bot' ? 'w-6 h-6 rounded-full order-1' : 'w-6 h-6 rounded-full order-2';

  const messageDivL1 = document.createElement('div');
  messageDivL1.className = role === 'bot' ?
    'flex items-end' :
    'flex items-end justify-end';
  const botContainer = document.createElement('div');
  botContainer.className = 'chat-message';
  messageDivL3.appendChild(messageWraper);
  messageDivL2.appendChild(messageDivL3);
  messageDivL1.appendChild(messageDivL2);
  messageDivL1.appendChild(span);
  botContainer.appendChild(messageDivL1);
  return botContainer;
};

document.addEventListener('DOMContentLoaded', function() {
  const skillHome = {
    name: 'home',
    help: 'home - search github for saihubot',
    requirements: {},
    rule: /HOME/i,
    action: function(robot, msg) {
      robot.ask('github saihubot');
    },
  };
  const skillSample = {
    name: 'sample',
    help: 'sample - show saihu samples',
    requirements: {},
    rule: /SAMPLE/i,
    action: function(robot, msg) {
      robot.addons.confirm('Here are samples', [
        {
          title: 'hello',
          id: 'hello',
          rule: /hello/i,
          action: function() {
            robot.send('Open hello bot sample');
            robot.render();
            window.open('samples/index.html', '_blank');
          },
        },
        {
          title: 'skill',
          id: 'skill',
          rule: /SKILL/i,
          action: function() {
            robot.send('Open skill sample');
            robot.render();
            window.open('samples/skill.html', '_blank');
          },
        },
      ]);
    },
  };

  new SaihuBot({
    adapter: basicAdapter,
    brain: localforageBrain,
    welcomeMessage: 'Hello! type `help` to check skills I can serve',
    notFoundMessages: [
      'type `ping`, `time`, or `echo [message]` to see what\'s happened',
      'type `google [keyword]`, `wiki [keyword]` to search',
      'type `help` for full sample commands list',
      'Want more samples? type `samples`',
      'Try refresh the page, messages are cached locally',
      'type `github saihubot` to visit me and give a star!',
      'you can ask anything ex: `siri who is current Us president?`',
    ],
    botAlias: '🤖',
    userAlias: '😎',
    renderMessage,
    renderComponent: renderMessage,
    addons: [...dialogAddons, ...searchAddons],
    skills: [
      ...helpSkills,
      ...diagnosSkills,
      ...searchSkills,
      skillHome,
      skillSample,
    ],
    debug: true,
  });
});
<|endoftext|>


<commit_before>module.exports = {

    VERSION: "0.0.9",

    bet_request: function (game_state, bet) {
        var myBet        = 0,
            myIndex      = game_state.in_action,
            currentBuyIn = game_state.current_buy_in,
            myCurrentBet = game_state.players[myIndex].bet,
            myCards      = game_state.players[myIndex].hole_cards,
            myStack      = game_state.players[myIndex].stack,
            tableCards   = game_state.community_cards,
            allCards     = myCards.concat(tableCards),
            minimumRaise = game_state.minimum_raise,
            decision,
            callBet      = this.getRaiseAmount(currentBuyIn, myCurrentBet, minimumRaise),
            raiseBet     = this.getCallAmount(currentBuyIn, myCurrentBet);

        if (tableCards.length) {
            if (this.checkIsStreetFlash(allCards)) {
                decision = this.ACTIONS.ALL_IN;
            } else if (this.checkIsCare(allCards)) {
                decision = this.ACTIONS.ALL_IN;
            } else if (this.checkIsFullHouse(allCards)) {
                decision = this.ACTIONS.ALL_IN;
            } else if (this.checkIsFlash(allCards)) {
                decision = this.ACTIONS.RAISE;
            } else if (this.checkIsStreet(allCards)) {
                decision = this.ACTIONS.RAISE;
            } else if (this.checkIsSet(allCards)) {
                if (callBet < 200) {
                    decision = this.ACTIONS.CALL;
                } else {
                    decision = this.ACTIONS.FOLD;
                }
            } else if (this.checkIsTwoPair(allCards)) {
                if (callBet < 100) {
                    decision = this.ACTIONS.CALL;
                } else {
                    decision = this.ACTIONS.FOLD;
                }
            } else if (this.checkIsPair(allCards)) {
                if (callBet < 50) {
                    decision = this.ACTIONS.CALL;
                } else {
                    decision = this.ACTIONS.FOLD;
                }
            } else {
                decision = this.ACTIONS.FOLD;
            }
        } else {
            //starting (no flop)
            var card1    = myCards[0],
                card2    = myCards[1];

            decision = this.ACTIONS.FOLD;

            if (card1.rank === card2.rank) {
                decision = this.ACTIONS.RAISE;
            } else if (this.HIGH_RANKS.indexOf(card1.rank) > -1 && this.HIGH_RANKS.indexOf(card2.rank) > -1) {
                decision = this.ACTIONS.RAISE;
            } else if (card1.suit == card2.suit) {
                decision = this.ACTIONS.CALL;
            }

            if (decision == this.ACTIONS.FOLD && callBet < 50) {
                decision = this.ACTIONS.CALL;
            }

            if (callBet > 400) {
                decision = this.ACTIONS.FOLD;
            }

            if (card1.rank === card2.rank && this.HIGH_RANKS.indexOf(card1.rank)) {
                decision = this.ACTIONS.CALL;
            }
        }

        if (decision == this.ACTIONS.RAISE) {
            myBet = callBet;
        } else if (decision == this.ACTIONS.CALL) {
            myBet = raiseBet;
        } else if (decision == this.ACTIONS.ALL_IN) {
            myBet = myStack;
        }

        console.log('======================================================================');
        console.log('my cards: ' + JSON.stringify(myCards));
        console.log('table cards: ' + JSON.stringify(tableCards));
        console.log('my stack: ' + myStack);
        console.log('decision: ' + decision);
        console.log('my bet: ' + myBet);
        console.log('======================================================================');

        bet(myBet);
    },

    // decisionMaker: function (game_state, myIndex, currentBuyIn, myCurrentBet, minimumRaise) {
    //     var myBet = 0,
    //         decision = this.checkCombination(game_state, myIndex);
    //
    //     if (decision == this.ACTIONS.RAISE) {
    //         myBet = this.getRaiseAmount(currentBuyIn, myCurrentBet);
    //     } else if (decision == this.ACTIONS.CALL) {
    //         myBet = this.getCallAmount(currentBuyIn, myCurrentBet, minimumRaise);
    //     }
    //
    //     return myBet;
    // },

    checkCombination: function (myCards) {
        var card1    = myCards[0],
            card2    = myCards[1],
            decision = this.ACTIONS.FOLD;

        if (card1.rank === card2.rank) {
            decision = this.ACTIONS.RAISE;
        } else if (this.HIGH_RANKS.indexOf(card1.rank) > -1 && this.HIGH_RANKS.indexOf(card2.rank) > -1) {
            decision = this.ACTIONS.RAISE;
        } else if (card1.suit == card2.suit) {
            decision = this.ACTIONS.CALL;
        }

        return decision;
    },

    getCallAmount: function (currentBuyIn, myCurrentBet) {
        var myBet = 0;

        myBet = currentBuyIn - myCurrentBet;

        return myBet;
    },

    getRaiseAmount: function (currentBuyIn, myCurrentBet, minimumRaise) {
        var myBet = 0;

        myBet = currentBuyIn - myCurrentBet + minimumRaise;

        return myBet;
    },

    checkIsFlash: function (incomingCards) {
        var spades = 0;
        var diamonds = 0;
        var hearts = 0;
        var clubs = 0;

        if (incomingCards.length <= 4) {
            return false;
        }

        for (var i = 0; i < incomingCards.length; i++) {
            var incomingCardItem = incomingCards[i];

            if (incomingCardItem.suit == this.SUITS.SPADES) {
                spades++;
            }
            if (incomingCardItem.suit == this.SUITS.DIAMONDS) {
                diamonds++;
            }
            if (incomingCardItem.suit == this.SUITS.HEARTS) {
                hearts++;
            }
            if (incomingCardItem.suit == this.SUITS.CLUBS) {
                clubs++;
            }
            if (spades == 5 || diamonds == 5 || hearts == 5 || clubs == 5) {
                return true;

            }
        }
        return false;
    },

    checkIsPair: function (incomingCards) {

        var pair = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!pair[incomingCard.rank]) pair[incomingCard.rank] = 0;

            pair[incomingCard.rank] = pair[incomingCard.rank] + 1;

        }

        for (var j in pair) {
            if (pair[j] >= 2) {
                return true;
            }
        }

        return false;

    },

    checkIsTwoPair: function (incomingCards) {

        var pair = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!pair[incomingCard.rank]) pair[incomingCard.rank] = 0;

            pair[incomingCard.rank] = pair[incomingCard.rank] + 1;

        }
        var countPair = 0;

        for (var j in pair) {
            if (pair[j] >= 2) {
                countPair++;

            }
            if (countPair == 2) {

                return true;
            }
        }

        return false;

    },

    checkIsSet: function (incomingCards) {

        var pair = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!pair[incomingCard.rank]) pair[incomingCard.rank] = 0;

            pair[incomingCard.rank] = pair[incomingCard.rank] + 1;

        }

        for (var j in pair) {
            if (pair[j] >= 3) {
                return true;
            }
        }

        return false;

    },

    checkIsStreet: function (incomingCards) {
        var arrRanks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];

        var street = [];

        var tempStreet = [];

        if (incomingCards.length < 5) {
            return false;
        }
        for (var z = 0; z < arrRanks.length; z++) {
            street[arrRanks[z]] = 0;
        }

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!street[incomingCard.rank]) street[incomingCard.rank] = 0;

            street[incomingCard.rank] = street[incomingCard.rank] + 1;

        }
        var countStreet = 0;
        for (var key in street) {

            if (street[key] != 0) {
                countStreet++
            }
            if (countStreet == 5) {
                return true;
            }
            if (street[key] == 0) {
                countStreet = 0;
            }
        }

        return false;

    },

    checkIsFullHouse: function (incomingCards) {
        var fullHouse = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!fullHouse[incomingCard.rank]) fullHouse[incomingCard.rank] = 0;

            fullHouse[incomingCard.rank] = fullHouse[incomingCard.rank] + 1;

        }
        var pair = false;
        var set = false;

        for (var j in fullHouse) {
            if (fullHouse[j] == 3) {
                set = true;
            }
            if (fullHouse[j] == 2) {
                pair = true;
            }
            if (pair && set) {
                return true;
            }
        }

        return false;
    },

    checkIsCare: function (incomingCards) {
        var checkCare = 0;
        var arrCombination = [];

        if (incomingCards.length < 4) {
            return false;
        }

        for (var i = 0; i < incomingCards.length; i++) {
            var incomingCardItem = incomingCards[i];

            if (!arrCombination[incomingCardItem.rank]) {
                arrCombination[incomingCardItem.rank] = 0;
            }

            arrCombination[incomingCardItem.rank] = arrCombination[incomingCardItem.rank] + 1;
        }

        for (var k in arrCombination) {
            if (arrCombination.hasOwnProperty(k)) {
                if (arrCombination[k] == 4) {
                    return true;
                }
            }
        }

        return false;
    },

    checkIsStreetFlash: function (incomingCards) {
        var spades = 0;
        var diamonds = 0;
        var hearts = 0;
        var clubs = 0;

        if (incomingCards.length <= 4) {
            return false
        }

        for (var i = 0; i < incomingCards.length; i++) {
            console.log(incomingCards[i]);
            var incomingCardItem = incomingCards[i];
            if (incomingCardItem.suit == 'spades') {
                spades++;
            }
            if (incomingCardItem.suit == 'diamonds') {
                diamonds++;
            }
            if (incomingCardItem.suit == 'hearts') {
                hearts++;
            }
            if (incomingCardItem.suit == 'clubs') {
                clubs++;
            }
            if (spades == 5 || diamonds == 5 || hearts == 5 || clubs == 5) {
                var arrRanks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];

                var street = [];

                var tempStreet = [];

                if (incomingCards.length < 5) {
                    return false;
                }
                for (var z = 0; z < arrRanks.length; z++) {
                    street[arrRanks[z]] = 0;
                }

                for (var y = 0; y < incomingCards.length; y++) {

                    var incomingCard = incomingCards[y];

                    if (!street[incomingCard.rank]) street[incomingCard.rank] = 0;

                    street[incomingCard.rank] = street[incomingCard.rank] + 1;

                }
                var countStreet = 0;
                for (var key in street) {

                    if (street[key] != 0) {
                        countStreet++
                    }
                    if (countStreet == 5) {
                        return true;
                    }
                    if (street[key] == 0) {
                        countStreet = 0;
                    }
                }

            } else {
                return false;
            }
        }
        return false;
    },

    showdown: function (game_state) {

    },

    ACTIONS: {
        FOLD: 'fold',
        RAISE: 'raise',
        CALL: 'call',
        ALL_IN: 'allIn'
    },

    ALL_RANKS: ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"],

    HIGH_RANKS: ["A", "10", "J", "Q", "K"],

    // SUITS: ['spades', 'diamonds', 'hearts', 'clubs']

    SUITS: {
        SPADES: 'spades',
        DIAMONDS: 'diamonds',
        HEARTS: 'hearts',
        CLUBS: 'clubs'
    }
};
<commit_msg>fantastic 2<commit_after>module.exports = {

    VERSION: "0.0.10",

    bet_request: function (game_state, bet) {
        var myBet        = 0,
            myIndex      = game_state.in_action,
            currentBuyIn = game_state.current_buy_in,
            myCurrentBet = game_state.players[myIndex].bet,
            myCards      = game_state.players[myIndex].hole_cards,
            myStack      = game_state.players[myIndex].stack,
            tableCards   = game_state.community_cards,
            allCards     = myCards.concat(tableCards),
            minimumRaise = game_state.minimum_raise,
            decision,
            callBet      = this.getRaiseAmount(currentBuyIn, myCurrentBet, minimumRaise),
            raiseBet     = this.getCallAmount(currentBuyIn, myCurrentBet);

        if (tableCards.length) {
            if (this.checkIsStreetFlash(allCards)) {
                decision = this.ACTIONS.ALL_IN;
            } else if (this.checkIsCare(allCards)) {
                decision = this.ACTIONS.ALL_IN;
            } else if (this.checkIsFullHouse(allCards)) {
                decision = this.ACTIONS.ALL_IN;
            } else if (this.checkIsFlash(allCards)) {
                decision = this.ACTIONS.RAISE;
            } else if (this.checkIsStreet(allCards)) {
                decision = this.ACTIONS.RAISE;
            } else if (this.checkIsSet(allCards)) {
                if (callBet < 200) {
                    decision = this.ACTIONS.CALL;
                } else {
                    decision = this.ACTIONS.FOLD;
                }
            } else if (this.checkIsTwoPair(allCards)) {
                if (callBet < 100) {
                    decision = this.ACTIONS.CALL;
                } else {
                    decision = this.ACTIONS.FOLD;
                }
            } else if (this.checkIsPair(allCards)) {
                if (callBet < 50) {
                    decision = this.ACTIONS.CALL;
                } else {
                    decision = this.ACTIONS.FOLD;
                }
            } else {
                decision = this.ACTIONS.FOLD;
            }
        } else {
            //starting (no flop)
            var card1    = myCards[0],
                card2    = myCards[1];

            decision = this.ACTIONS.FOLD;

            if (card1.rank === card2.rank) {
                decision = this.ACTIONS.RAISE;
            } else if (this.HIGH_RANKS.indexOf(card1.rank) > -1 && this.HIGH_RANKS.indexOf(card2.rank) > -1) {
                decision = this.ACTIONS.RAISE;
            } else if (card1.suit == card2.suit) {
                decision = this.ACTIONS.CALL;
            }

            if (decision == this.ACTIONS.FOLD && callBet < 50) {
                decision = this.ACTIONS.CALL;
            }

            if (callBet > 400) {
                decision = this.ACTIONS.FOLD;
            }

            if (card1.rank === card2.rank && this.HIGH_RANKS.indexOf(card1.rank)) {
                decision = this.ACTIONS.CALL;
            }
        }

        if (decision == this.ACTIONS.RAISE) {
            myBet = callBet;
        } else if (decision == this.ACTIONS.CALL) {
            myBet = raiseBet;
        } else if (decision == this.ACTIONS.ALL_IN) {
            myBet = myStack;
        }

        console.log('======================================================================');
        console.log('my cards: ' + JSON.stringify(myCards));
        console.log('table cards: ' + JSON.stringify(tableCards));
        console.log('my stack: ' + myStack);
        console.log('decision: ' + decision);
        console.log('my bet: ' + myBet);
        console.log('======================================================================');

        bet(myBet);
    },

    // decisionMaker: function (game_state, myIndex, currentBuyIn, myCurrentBet, minimumRaise) {
    //     var myBet = 0,
    //         decision = this.checkCombination(game_state, myIndex);
    //
    //     if (decision == this.ACTIONS.RAISE) {
    //         myBet = this.getRaiseAmount(currentBuyIn, myCurrentBet);
    //     } else if (decision == this.ACTIONS.CALL) {
    //         myBet = this.getCallAmount(currentBuyIn, myCurrentBet, minimumRaise);
    //     }
    //
    //     return myBet;
    // },

    checkCombination: function (myCards) {
        var card1    = myCards[0],
            card2    = myCards[1],
            decision = this.ACTIONS.FOLD;

        if (card1.rank === card2.rank) {
            decision = this.ACTIONS.RAISE;
        } else if (this.HIGH_RANKS.indexOf(card1.rank) > -1 && this.HIGH_RANKS.indexOf(card2.rank) > -1) {
            decision = this.ACTIONS.RAISE;
        } else if (card1.suit == card2.suit) {
            decision = this.ACTIONS.CALL;
        }

        return decision;
    },

    getCallAmount: function (currentBuyIn, myCurrentBet) {
        var myBet = 0;

        myBet = currentBuyIn - myCurrentBet;

        return myBet;
    },

    getRaiseAmount: function (currentBuyIn, myCurrentBet, minimumRaise) {
        var myBet = 0;

        myBet = currentBuyIn - myCurrentBet + minimumRaise;

        return myBet;
    },

    checkIsFlash: function (incomingCards) {
        var spades = 0;
        var diamonds = 0;
        var hearts = 0;
        var clubs = 0;

        if (incomingCards.length <= 4) {
            return false;
        }

        for (var i = 0; i < incomingCards.length; i++) {
            var incomingCardItem = incomingCards[i];

            if (incomingCardItem.suit == this.SUITS.SPADES) {
                spades++;
            }
            if (incomingCardItem.suit == this.SUITS.DIAMONDS) {
                diamonds++;
            }
            if (incomingCardItem.suit == this.SUITS.HEARTS) {
                hearts++;
            }
            if (incomingCardItem.suit == this.SUITS.CLUBS) {
                clubs++;
            }
            if (spades == 5 || diamonds == 5 || hearts == 5 || clubs == 5) {
                return true;

            }
        }
        return false;
    },

    checkIsPair: function (incomingCards) {

        var pair = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!pair[incomingCard.rank]) pair[incomingCard.rank] = 0;

            pair[incomingCard.rank] = pair[incomingCard.rank] + 1;

        }

        for (var j in pair) {
            if (pair[j] >= 2) {
                return true;
            }
        }

        return false;

    },

    checkIsTwoPair: function (incomingCards) {

        var pair = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!pair[incomingCard.rank]) pair[incomingCard.rank] = 0;

            pair[incomingCard.rank] = pair[incomingCard.rank] + 1;

        }
        var countPair = 0;

        for (var j in pair) {
            if (pair[j] >= 2) {
                countPair++;

            }
            if (countPair == 2) {

                return true;
            }
        }

        return false;

    },

    checkIsSet: function (incomingCards) {

        var pair = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!pair[incomingCard.rank]) pair[incomingCard.rank] = 0;

            pair[incomingCard.rank] = pair[incomingCard.rank] + 1;

        }

        for (var j in pair) {
            if (pair[j] >= 3) {
                return true;
            }
        }

        return false;

    },

    checkIsStreet: function (incomingCards) {
        var arrRanks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];

        var street = [];

        var tempStreet = [];

        if (incomingCards.length < 5) {
            return false;
        }
        for (var z = 0; z < arrRanks.length; z++) {
            street[arrRanks[z]] = 0;
        }

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!street[incomingCard.rank]) street[incomingCard.rank] = 0;

            street[incomingCard.rank] = street[incomingCard.rank] + 1;

        }
        var countStreet = 0;
        for (var key in street) {

            if (street[key] != 0) {
                countStreet++
            }
            if (countStreet == 5) {
                return true;
            }
            if (street[key] == 0) {
                countStreet = 0;
            }
        }

        return false;

    },

    checkIsFullHouse: function (incomingCards) {
        var fullHouse = [];

        for (var i = 0; i < incomingCards.length; i++) {

            var incomingCard = incomingCards[i];

            if (!fullHouse[incomingCard.rank]) fullHouse[incomingCard.rank] = 0;

            fullHouse[incomingCard.rank] = fullHouse[incomingCard.rank] + 1;

        }
        var pair = false;
        var set = false;

        for (var j in fullHouse) {
            if (fullHouse[j] == 3) {
                set = true;
            }
            if (fullHouse[j] == 2) {
                pair = true;
            }
            if (pair && set) {
                return true;
            }
        }

        return false;
    },

    checkIsCare: function (incomingCards) {
        var checkCare = 0;
        var arrCombination = [];

        if (incomingCards.length < 4) {
            return false;
        }

        for (var i = 0; i < incomingCards.length; i++) {
            var incomingCardItem = incomingCards[i];

            if (!arrCombination[incomingCardItem.rank]) {
                arrCombination[incomingCardItem.rank] = 0;
            }

            arrCombination[incomingCardItem.rank] = arrCombination[incomingCardItem.rank] + 1;
        }

        for (var k in arrCombination) {
            if (arrCombination.hasOwnProperty(k)) {
                if (arrCombination[k] == 4) {
                    return true;
                }
            }
        }

        return false;
    },

    checkIsStreetFlash: function (incomingCards) {
        var spades = 0;
        var diamonds = 0;
        var hearts = 0;
        var clubs = 0;

        if (incomingCards.length <= 4) {
            return false
        }

        for (var i = 0; i < incomingCards.length; i++) {
            console.log(incomingCards[i]);
            var incomingCardItem = incomingCards[i];
            if (incomingCardItem.suit == 'spades') {
                spades++;
            }
            if (incomingCardItem.suit == 'diamonds') {
                diamonds++;
            }
            if (incomingCardItem.suit == 'hearts') {
                hearts++;
            }
            if (incomingCardItem.suit == 'clubs') {
                clubs++;
            }
            if (spades == 5 || diamonds == 5 || hearts == 5 || clubs == 5) {
                var arrRanks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];

                var street = [];

                var tempStreet = [];

                if (incomingCards.length < 5) {
                    return false;
                }
                for (var z = 0; z < arrRanks.length; z++) {
                    street[arrRanks[z]] = 0;
                }

                for (var y = 0; y < incomingCards.length; y++) {

                    var incomingCard = incomingCards[y];

                    if (!street[incomingCard.rank]) street[incomingCard.rank] = 0;

                    street[incomingCard.rank] = street[incomingCard.rank] + 1;

                }
                var countStreet = 0;
                for (var key in street) {

                    if (street[key] != 0) {
                        countStreet++
                    }
                    if (countStreet == 5) {
                        return true;
                    }
                    if (street[key] == 0) {
                        countStreet = 0;
                    }
                }

            } else {
                return false;
            }
        }
        return false;
    },

    showdown: function (game_state) {

    },

    ACTIONS: {
        FOLD: 'fold',
        RAISE: 'raise',
        CALL: 'call',
        ALL_IN: 'allIn'
    },

    ALL_RANKS: ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"],

    HIGH_RANKS: ["A", "10", "J", "Q", "K"],

    // SUITS: ['spades', 'diamonds', 'hearts', 'clubs']

    SUITS: {
        SPADES: 'spades',
        DIAMONDS: 'diamonds',
        HEARTS: 'hearts',
        CLUBS: 'clubs'
    }
};
<|endoftext|>