<commit_before>function getCookie(name) {
	var value = "; " + document.cookie;
	var parts = value.split("; " + name + "=");
	if (parts.length == 2) {
		return parts.pop().split(";").shift();
	}
	return false;
}

if (!getCookie(score)) {
	document.cookie = 'score=0;';
}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return parseInt(result[1], 16).toString() +
		',' + parseInt(result[2], 16).toString() +
		',' + parseInt(result[3], 16).toString();
}

$(document).ready(
	function() {
		startGame = function(size) {
			var GameHandler = new Game(size);
		}

		$('.menuButton').click(function() {
			$('#MainMenu').fadeOut();
		})

		$('#menu').find('td').hover(function() {
			$(this).css({backgroundColor: '#4585F2', color: '#1B1B1B'});
		}, function() {
			$(this).css({backgroundColor: '#1B1B1B', color: '#EEEEEE'});
		});

		$('.button').hover(function() {
			$(this).css({backgroundColor: '#4585F2', color: '#1B1B1B'});
		}, function() {
			$(this).css({backgroundColor: '#1B1B1B', color: '#EEEEEE'});
		});

		$('.heading').hover(function() {
			$(this).css({color: '#45CF4D'});
		}, function() {
			$(this).css({color: '#EEEEEE'});
		});

		$('.score').hover(function() {
			$(this).css({color: '#45CF4D'});
		}, function() {
			$(this).css({color: '#EEEEEE'});
		});

		$('.score').text(document.cookie.score);

		$('#gameHowToPlay').find('rule').hover(function() {
			$(this).css({color: '#45CF4D'});
		}, function() {
			$(this).css({color: '#EEEEEE'});
		});
	}
);<commit_msg>fixed scores<commit_after>function getCookie(name) {
	var value = "; " + document.cookie;
	var parts = value.split("; " + name + "=");
	if (parts.length == 2) {
		return parts.pop().split(";").shift();
	}
	return false;
}

if (!getCookie('score')) {
	document.cookie = 'score=0;';
}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return parseInt(result[1], 16).toString() +
		',' + parseInt(result[2], 16).toString() +
		',' + parseInt(result[3], 16).toString();
}

$(document).ready(
	function() {
		startGame = function(size) {
			var GameHandler = new Game(size);
		}

		$('.menuButton').click(function() {
			$('#MainMenu').fadeOut();
		})

		$('#menu').find('td').hover(function() {
			$(this).css({backgroundColor: '#4585F2', color: '#1B1B1B'});
		}, function() {
			$(this).css({backgroundColor: '#1B1B1B', color: '#EEEEEE'});
		});

		$('.button').hover(function() {
			$(this).css({backgroundColor: '#4585F2', color: '#1B1B1B'});
		}, function() {
			$(this).css({backgroundColor: '#1B1B1B', color: '#EEEEEE'});
		});

		$('.heading').hover(function() {
			$(this).css({color: '#45CF4D'});
		}, function() {
			$(this).css({color: '#EEEEEE'});
		});

		$('.score').hover(function() {
			$(this).css({color: '#45CF4D'});
		}, function() {
			$(this).css({color: '#EEEEEE'});
		});

		$('.score').text(document.cookie.score);

		$('#gameHowToPlay').find('rule').hover(function() {
			$(this).css({color: '#45CF4D'});
		}, function() {
			$(this).css({color: '#EEEEEE'});
		});
	}
);<|endoftext|>


<commit_before>/*global Observable, window:true, document*/
window.Sieve = (function (Observable) {
    'use strict';
    var Sieve = {};

    var SieveNumber = Sieve.Number = function (n) {
        Observable.call(this);
        this.n = n;
        this.ds = [];
    };
    SieveNumber.prototype = new Observable();
    SieveNumber.prototype.value = function () {
        return this.n;
    };
    SieveNumber.prototype.divisors = function () {
        return this.ds.slice(0);
    };
    SieveNumber.prototype.addDivisor = function (d) {
        this.ds.push(d);
        this.notify();
    };

    var numbers = function (n) {
        var result = [];
        for (var index = 1; index <= n; index++) {
            result.push(new SieveNumber(index));
            if (index === 1) {
                result[0].addDivisor(0);
            }
        }
        return result;
    };

    var Model = Sieve.Model = function (n) {
        Observable.call(this);
        this.currentIndex = 1;
        this.n = n;
        this.ns = numbers(n);
    };
    Model.prototype = new Observable();
    Model.prototype.numbers = function () {
        return this.ns.slice(0);
    };
    Model.prototype.finished = function () {
        return 2 * this.ns[this.currentIndex].value() > this.n;
    };
    Model.prototype.sieveStep = function () {
        var d = this.ns[this.currentIndex].value();
        var index = 2;
        while ((d * index - 1) < this.ns.length) {
            this.ns[d * index - 1].addDivisor(d);
            index++;
        }
        while (this.ns[++this.currentIndex].divisors().length > 0) {/* do nothing */}
        this.notify();
    };
    Model.prototype.sieve = function () {
        while (!this.finished()) {
            this.sieveStep();
        }
    };

    var NumberView = Sieve.NumberView = function (parent, model) {
        this.parent = parent;
        this.model = model;
        this.model.addObserver(this.update.bind(this));
        this.update();
    };
    NumberView.prototype.update = function () {
        var container = this.container();
        container.textContent = this.model.value();
        if (this.model.divisors().length > 0) {
            container.style['text-decoration'] = 'line-through';
        } else {
            container.style['text-decoration'] = 'none';
        }
    };
    NumberView.prototype.container = function () {
        return this.parent;
    };

    var View = Sieve.View = function (parent, model) {
        this.parent = parent;
        this.model = model;
        this.model.addObserver(this.update.bind(this));
        this.clear();
        this.update();
    };
    View.prototype.clear = function () {
        while (this.parent.firstChild) {
            this.parent.removeChild(this.parent.firstChild);
        }
    };
    View.prototype.update = function () {
        var children = this.children();
        children.forEach(function (child, index) {
            child.setAttribute('class', (index === this.model.currentIndex) ? 'current': '');
        }.bind(this));
    };
    View.prototype.children = function () {
        if (! this._children) {
            var numbers = this.model.numbers();
            var children = this._children = [];
            for (var index = 0; index < numbers.length; index++) {
                var container = document.createElement('span');
                new NumberView(container, numbers[index]);
                this.parent.appendChild(container);
                children.push(container);
            }
        }
        return this._children;
    };

    var Control = Sieve.ControlView = function (parent, model) {
        this.parent = parent;
        this.model = model;
        this.clear();
        this.update();
    };
    Control.prototype.clear = function () {
        while (this.parent.firstChild) {
            this.parent.removeChild(this.parent.firstChild);
        }
    };
    Control.prototype.update = function () {
        var stepSpan = document.createElement('span');
        stepSpan.textContent = '>';
        stepSpan.addEventListener('click', this.model.sieveStep.bind(this.model));
        var allSpan = document.createElement('span');
        allSpan.textContent = '>>';
        allSpan.addEventListener('click', this.model.sieve.bind(this.model));
        var sieveSpan = document.createElement('span');
        new Sieve.View(sieveSpan, this.model);
        [stepSpan, allSpan, sieveSpan].forEach(function (span) {
            this.parent.appendChild(span);
        }.bind(this));
    };
    return Sieve;
})(Observable);
<commit_msg>do not step if finished<commit_after>/*global Observable, window:true, document*/
window.Sieve = (function (Observable) {
    'use strict';
    var Sieve = {};

    var SieveNumber = Sieve.Number = function (n) {
        Observable.call(this);
        this.n = n;
        this.ds = [];
    };
    SieveNumber.prototype = new Observable();
    SieveNumber.prototype.value = function () {
        return this.n;
    };
    SieveNumber.prototype.divisors = function () {
        return this.ds.slice(0);
    };
    SieveNumber.prototype.addDivisor = function (d) {
        this.ds.push(d);
        this.notify();
    };

    var numbers = function (n) {
        var result = [];
        for (var index = 1; index <= n; index++) {
            result.push(new SieveNumber(index));
            if (index === 1) {
                result[0].addDivisor(0);
            }
        }
        return result;
    };

    var Model = Sieve.Model = function (n) {
        Observable.call(this);
        this.currentIndex = 1;
        this.n = n;
        this.ns = numbers(n);
    };
    Model.prototype = new Observable();
    Model.prototype.numbers = function () {
        return this.ns.slice(0);
    };
    Model.prototype.finished = function () {
        return 2 * this.ns[this.currentIndex].value() > this.n;
    };
    Model.prototype.sieveStep = function () {
	if (this.finished()) { return; }
        var d = this.ns[this.currentIndex].value();
        var index = 2;
        while ((d * index - 1) < this.ns.length) {
            this.ns[d * index - 1].addDivisor(d);
            index++;
        }
        while (this.ns[++this.currentIndex].divisors().length > 0) {/* do nothing */}
        this.notify();
    };
    Model.prototype.sieve = function () {
        while (!this.finished()) {
            this.sieveStep();
        }
    };

    var NumberView = Sieve.NumberView = function (parent, model) {
        this.parent = parent;
        this.model = model;
        this.model.addObserver(this.update.bind(this));
        this.update();
    };
    NumberView.prototype.update = function () {
        var container = this.container();
        container.textContent = this.model.value();
        if (this.model.divisors().length > 0) {
            container.style['text-decoration'] = 'line-through';
        } else {
            container.style['text-decoration'] = 'none';
        }
    };
    NumberView.prototype.container = function () {
        return this.parent;
    };

    var View = Sieve.View = function (parent, model) {
        this.parent = parent;
        this.model = model;
        this.model.addObserver(this.update.bind(this));
        this.clear();
        this.update();
    };
    View.prototype.clear = function () {
        while (this.parent.firstChild) {
            this.parent.removeChild(this.parent.firstChild);
        }
    };
    View.prototype.update = function () {
        var children = this.children();
        children.forEach(function (child, index) {
            child.setAttribute('class', (index === this.model.currentIndex) ? 'current': '');
        }.bind(this));
    };
    View.prototype.children = function () {
        if (! this._children) {
            var numbers = this.model.numbers();
            var children = this._children = [];
            for (var index = 0; index < numbers.length; index++) {
                var container = document.createElement('span');
                new NumberView(container, numbers[index]);
                this.parent.appendChild(container);
                children.push(container);
            }
        }
        return this._children;
    };

    var Control = Sieve.ControlView = function (parent, model) {
        this.parent = parent;
        this.model = model;
        this.clear();
        this.update();
    };
    Control.prototype.clear = function () {
        while (this.parent.firstChild) {
            this.parent.removeChild(this.parent.firstChild);
        }
    };
    Control.prototype.update = function () {
        var stepSpan = document.createElement('span');
        stepSpan.textContent = '>';
        stepSpan.addEventListener('click', this.model.sieveStep.bind(this.model));
        var allSpan = document.createElement('span');
        allSpan.textContent = '>>';
        allSpan.addEventListener('click', this.model.sieve.bind(this.model));
        var sieveSpan = document.createElement('span');
        new Sieve.View(sieveSpan, this.model);
        [stepSpan, allSpan, sieveSpan].forEach(function (span) {
            this.parent.appendChild(span);
        }.bind(this));
    };
    return Sieve;
})(Observable);
<|endoftext|>


<commit_before>// +--------------------------------------------------------------------------+
// | BXE                                                                      |
// +--------------------------------------------------------------------------+
// | Copyright (c) 2003,2004 Bitflux GmbH                                     |
// +--------------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the "License");          |
// | you may not use this file except in compliance with the License.         |
// | You may obtain a copy of the License at                                  |
// |     http://www.apache.org/licenses/LICENSE-2.0                           |
// | Unless required by applicable law or agreed to in writing, software      |
// | distributed under the License is distributed on an "AS IS" BASIS,        |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
// | See the License for the specific language governing permissions and      |
// | limitations under the License.                                           |
// +--------------------------------------------------------------------------+
// | Author: Christian Stocker <chregu@bitflux.ch>                            |
// +--------------------------------------------------------------------------+
//
// $Id$

HTMLTableCellElement.prototype.TableRemoveRow = function() {
	this.parentNode.parentNode.removeChild(this.parentNode);
}

HTMLTableCellElement.prototype.TableRemoveCol = function() {
	var pos = this.findPosition();
	var table = this.parentNode.parentNode;
	var colpos = 1;
	var row = table.firstChild;
	var colToBeRemoved = null;
	while (row) {
		if (row.nodeType == 1) {

			if ( row.localName.toLowerCase() == "tr") {
				var cell = row.findCellPosition(pos);
				if (cell) {
					row.removeChild(cell);
				}
			} else if ( row.localName.toLowerCase() == "col") {
				if (colpos == pos) {
					colToBeRemoved = row;

				}
				colpos++;
			}
		}
		row = row.nextSibling;
	}
	if (colToBeRemoved) {
		table.removeChild(colToBeRemoved);
	}
}

HTMLTableCellElement.prototype.TableAppendRow = function () {
	var newRow = this.parentNode.cloneNode(true);
	this.parentNode.parentNode.insertAfter(newRow,this.parentNode);

	var _children = newRow.childNodes;
	for (var i in _children) {
		if (_children[i].nodeType == 1){
			_children[i].removeAllChildren();
			_children[i].appendChild(document.createTextNode(STRING_NBSP));
		}
	}
}

HTMLTableCellElement.prototype.TableAppendCol = function () {
	var pos = this.findPosition();
	var table = this.parentNode.parentNode;
	var row = table.firstChild;
	var colpos = 1;
	while (row) {
		if (row.nodeType == 1) {
			if ( row.localName.toLowerCase() == "tr") {
				var cell = row.findCellPosition(pos);
				if (cell) {
					var newtd = document.createElementNS(XHTMLNS,"td");
					newtd.appendChild(document.createTextNode(STRING_NBSP));
					row.insertBefore(newtd,cell.nextSibling);
				}
			} else if ( row.localName.toLowerCase() == "col") {
				dump (colpos + " ==  " + pos + "\n");
				if (colpos == pos) {

					table.insertBefore(document.createElementNS(XHTMLNS, "col"),row.nextSibling);
				}
				colpos++;
			}
		}

		row = row.nextSibling;
	}

}

HTMLTableCellElement.prototype.findPosition = function () {
	// find position
	var prevSibling = this.previousSibling;
	var pos = 1;
	while(prevSibling) {
		if (prevSibling.nodeType == 1 && prevSibling.localName.toLowerCase() == "td") {
			if (prevSibling.hasAttribute("colspan")) {
				pos += parseInt( prevSibling.getAttribute("colspan"));
			} else {
				pos++;
			}
		}
		prevSibling = prevSibling.previousSibling;
	}
	return pos;
}

HTMLTableCellElement.prototype.TableCellMergeRight = function () {
	var nextSibling = this.nextSibling;
	while (nextSibling && nextSibling.nodeType != 1) {
		nextSibling = nextSibling.nextSibling;
	}
	var child = nextSibling.firstChild;
	while (child) {
		this.appendChild(child);
		child = child.nextSibling;
	}
	this.normalize();
	nextSibling.parentNode.removeChild(nextSibling);
	var colspan = this.getAttribute("colspan");
	if (!colspan) {
		colspan = 1;
	}
	this.setAttribute("colspan", colspan+1);
}

HTMLTableCellElement.prototype.TableCellMergeDown = function () {

	var pos = this.findPosition();
	var thisRowspan = 1;
	if (this.hasAttribute("rowspan")) {
		thisRowspan = this.getAttribute("rowspan");
	}
	this.setAttribute("rowspan",thisRowspan+1);

	// find the same cell in the row below..
	var tr = null;
	// find next Row

	var nextSibling = this.parentNode.nextSibling
	while(nextSibling) {
		if (nextSibling.nodeType == 1 && nextSibling.localName.toLowerCase() == "tr") {
			tr = nextSibling;
			break;
		}
		nextSibling = nextSibling.nextSibling;
	}

	if (!tr) {
		alert("no next table row found");
		return;
	}

	nextSibling = tr.firstChild;
	var nextpos = 1;
	while(nextSibling) {
		if (nextSibling.nodeType == 1 && nextSibling.localName.toLowerCase() == "td") {
			if (nextSibling.hasAttribute("colspan")) {
				nextpos += parseInt( nextSibling.getAttribute("colspan"));
			} else {
				nextpos++;
			}
			if (nextpos > pos) {
				break;
			}
		}
		nextSibling = nextSibling.nextSibling;
	}

	var child = nextSibling.firstChild;
	while (child) {
		this.appendChild(child);
		child = child.nextSibling;
	}
	this.normalize();
	tr.removeChild(nextSibling);
}

HTMLTableCellElement.prototype.TableCellSplitRight = function () {

	var cssr = window.getSelection().getEditableRange();
	var ip = documentCreateInsertionPoint(cssr.top, cssr.startContainer, cssr.startOffset);
	ip.splitContainedLine();

	var colspan = this.getAttribute("colspan");
	if (colspan > 2) {
		this.setAttribute("colspan", colspan-1);
	} else {
		this.removeAttribute("colspan");
	}
	var nextSibling = this.nextSibling;
	while (nextSibling && nextSibling.nodeType != 1) {
		nextSibling = nextSibling.nextSibling;
	}
	if (nextSibling) {
		nextSibling.removeAttribute("colspan");
	}

}

HTMLTableCellElement.prototype.TableCellSplitDown = function() {
	var pos = this.findPosition();
	var tr = this.parentNode;
	var cssr = window.getSelection().getEditableRange();
	var ip = documentCreateInsertionPoint(cssr.top, cssr.startContainer, cssr.startOffset);
	ip.splitContainedLine();

	var rowspan = this.getAttribute("rowspan");
	if (rowspan > 2) {
		this.setAttribute("rowspan", rowspan-1);
	} else {
		this.removeAttribute("rowspan");
	}
	var nextSibling = this.nextSibling;
	while (nextSibling && nextSibling.nodeType != 1) {
		nextSibling = nextSibling.nextSibling;
	}
	if (nextSibling) {
		nextSibling.removeAttribute("rowspan");
	}

	var nexttr = tr.nextSibling;
	while (nexttr) {
		if (nexttr.nodeType == 1 && nexttr.localName.toLowerCase() == "tr") {
			var cell = nexttr.findCellPosition(pos-1);
			if (cell) {
				nexttr.insertBefore(nextSibling,cell.nextSibling);
			}
			break;
		}
		nexttr = nexttr.nextSibling;
	}

}
HTMLTableRowElement.prototype.findCellPosition = function(pos) {
	var cell = this.firstChild;
	var nextpos = 1;

	while (cell) {
		if (cell.nodeType == 1 && cell.localName.toLowerCase() == "td") {
			if (nextpos >= pos) {
				return cell;
			}
			if (cell.hasAttribute("colspan")) {
				nextpos += parseInt( cell.getAttribute("colspan"));
			} else {
				nextpos++;
			}
		}
		cell = cell.nextSibling;
	}

}

<commit_msg>remove A0 character<commit_after>// +--------------------------------------------------------------------------+
// | BXE                                                                      |
// +--------------------------------------------------------------------------+
// | Copyright (c) 2003,2004 Bitflux GmbH                                     |
// +--------------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the "License");          |
// | you may not use this file except in compliance with the License.         |
// | You may obtain a copy of the License at                                  |
// |     http://www.apache.org/licenses/LICENSE-2.0                           |
// | Unless required by applicable law or agreed to in writing, software      |
// | distributed under the License is distributed on an "AS IS" BASIS,        |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
// | See the License for the specific language governing permissions and      |
// | limitations under the License.                                           |
// +--------------------------------------------------------------------------+
// | Author: Christian Stocker <chregu@bitflux.ch>                            |
// +--------------------------------------------------------------------------+
//
// $Id$

HTMLTableCellElement.prototype.TableRemoveRow = function() {
	this.parentNode.parentNode.removeChild(this.parentNode);
}

HTMLTableCellElement.prototype.TableRemoveCol = function() {
	var pos = this.findPosition();
	var table = this.parentNode.parentNode;
	var colpos = 1;
	var row = table.firstChild;
	var colToBeRemoved = null;
	while (row) {
		if (row.nodeType == 1) {

			if ( row.localName.toLowerCase() == "tr") {
				var cell = row.findCellPosition(pos);
				if (cell) {
					row.removeChild(cell);
				}
			} else if ( row.localName.toLowerCase() == "col") {
				if (colpos == pos) {
					colToBeRemoved = row;

				}
				colpos++;
			}
		}
		row = row.nextSibling;
	}
	if (colToBeRemoved) {
		table.removeChild(colToBeRemoved);
	}
}

HTMLTableCellElement.prototype.TableAppendRow = function () {
	var newRow = this.parentNode.cloneNode(true);
	this.parentNode.parentNode.insertAfter(newRow,this.parentNode);

	var _children = newRow.childNodes;
	for (var i in _children) {
		if (_children[i].nodeType == 1) {
			_children[i].removeAllChildren();
			_children[i].appendChild(document.createTextNode(STRING_NBSP));
		}
	}
}

HTMLTableCellElement.prototype.TableAppendCol = function () {
	var pos = this.findPosition();
	var table = this.parentNode.parentNode;
	var row = table.firstChild;
	var colpos = 1;
	while (row) {
		if (row.nodeType == 1) {
			if ( row.localName.toLowerCase() == "tr") {
				var cell = row.findCellPosition(pos);
				if (cell) {
					var newtd = document.createElementNS(XHTMLNS,"td");
					newtd.appendChild(document.createTextNode(STRING_NBSP));
					row.insertBefore(newtd,cell.nextSibling);
				}
			} else if ( row.localName.toLowerCase() == "col") {
				dump (colpos + " ==  " + pos + "\n");
				if (colpos == pos) {

					table.insertBefore(document.createElementNS(XHTMLNS, "col"),row.nextSibling);
				}
				colpos++;
			}
		}

		row = row.nextSibling;
	}

}

HTMLTableCellElement.prototype.findPosition = function () {
	// find position
	var prevSibling = this.previousSibling;
	var pos = 1;
	while(prevSibling) {
		if (prevSibling.nodeType == 1 && prevSibling.localName.toLowerCase() == "td") {
			if (prevSibling.hasAttribute("colspan")) {
				pos += parseInt( prevSibling.getAttribute("colspan"));
			} else {
				pos++;
			}
		}
		prevSibling = prevSibling.previousSibling;
	}
	return pos;
}

HTMLTableCellElement.prototype.TableCellMergeRight = function () {
	var nextSibling = this.nextSibling;
	while (nextSibling && nextSibling.nodeType != 1) {
		nextSibling = nextSibling.nextSibling;
	}
	var child = nextSibling.firstChild;
	while (child) {
		this.appendChild(child);
		child = child.nextSibling;
	}
	this.normalize();
	nextSibling.parentNode.removeChild(nextSibling);
	var colspan = this.getAttribute("colspan");
	if (!colspan) {
		colspan = 1;
	}
	this.setAttribute("colspan", colspan+1);
}

HTMLTableCellElement.prototype.TableCellMergeDown = function () {

	var pos = this.findPosition();
	var thisRowspan = 1;
	if (this.hasAttribute("rowspan")) {
		thisRowspan = this.getAttribute("rowspan");
	}
	this.setAttribute("rowspan",thisRowspan+1);

	// find the same cell in the row below..
	var tr = null;
	// find next Row

	var nextSibling = this.parentNode.nextSibling
	while(nextSibling) {
		if (nextSibling.nodeType == 1 && nextSibling.localName.toLowerCase() == "tr") {
			tr = nextSibling;
			break;
		}
		nextSibling = nextSibling.nextSibling;
	}

	if (!tr) {
		alert("no next table row found");
		return;
	}

	nextSibling = tr.firstChild;
	var nextpos = 1;
	while(nextSibling) {
		if (nextSibling.nodeType == 1 && nextSibling.localName.toLowerCase() == "td") {
			if (nextSibling.hasAttribute("colspan")) {
				nextpos += parseInt( nextSibling.getAttribute("colspan"));
			} else {
				nextpos++;
			}
			if (nextpos > pos) {
				break;
			}
		}
		nextSibling = nextSibling.nextSibling;
	}

	var child = nextSibling.firstChild;
	while (child) {
		this.appendChild(child);
		child = child.nextSibling;
	}
	this.normalize();
	tr.removeChild(nextSibling);
}

HTMLTableCellElement.prototype.TableCellSplitRight = function () {

	var cssr = window.getSelection().getEditableRange();
	var ip = documentCreateInsertionPoint(cssr.top, cssr.startContainer, cssr.startOffset);
	ip.splitContainedLine();

	var colspan = this.getAttribute("colspan");
	if (colspan > 2) {
		this.setAttribute("colspan", colspan-1);
	} else {
		this.removeAttribute("colspan");
	}
	var nextSibling = this.nextSibling;
	while (nextSibling && nextSibling.nodeType != 1) {
		nextSibling = nextSibling.nextSibling;
	}
	if (nextSibling) {
		nextSibling.removeAttribute("colspan");
	}

}

HTMLTableCellElement.prototype.TableCellSplitDown = function() {
	var pos = this.findPosition();
	var tr = this.parentNode;
	var cssr = window.getSelection().getEditableRange();
	var ip = documentCreateInsertionPoint(cssr.top, cssr.startContainer, cssr.startOffset);
	ip.splitContainedLine();

	var rowspan = this.getAttribute("rowspan");
	if (rowspan > 2) {
		this.setAttribute("rowspan", rowspan-1);
	} else {
		this.removeAttribute("rowspan");
	}
	var nextSibling = this.nextSibling;
	while (nextSibling && nextSibling.nodeType != 1) {
		nextSibling = nextSibling.nextSibling;
	}
	if (nextSibling) {
		nextSibling.removeAttribute("rowspan");
	}

	var nexttr = tr.nextSibling;
	while (nexttr) {
		if (nexttr.nodeType == 1 && nexttr.localName.toLowerCase() == "tr") {
			var cell = nexttr.findCellPosition(pos-1);
			if (cell) {
				nexttr.insertBefore(nextSibling,cell.nextSibling);
			}
			break;
		}
		nexttr = nexttr.nextSibling;
	}

}
HTMLTableRowElement.prototype.findCellPosition = function(pos) {
	var cell = this.firstChild;
	var nextpos = 1;

	while (cell) {
		if (cell.nodeType == 1 && cell.localName.toLowerCase() == "td") {
			if (nextpos >= pos) {
				return cell;
			}
			if (cell.hasAttribute("colspan")) {
				nextpos += parseInt( cell.getAttribute("colspan"));
			} else {
				nextpos++;
			}
		}
		cell = cell.nextSibling;
	}

}

<|endoftext|>


<commit_before>var sides = ["N", "E", "S", "W"];
var suit_image_template = "";
var big_suit_image_template = "";
var pass_dbl_rdbl = ["pass", "dbl", "rdbl"];

var lead_count;
var my_side;
var tid;
var ind_int = window.setInterval(function(){}, 9999);
var first_deal = true;

var update_handlers = new Array();
update_handlers["move"] = process_move;
update_handlers["bid"] = process_bid;
update_handlers["hand"] = process_hand;
update_handlers["player.sit"] = user_sit;
update_handlers["player.leave"] = user_leave;
update_handlers["tricks"] = show_tricks;
update_handlers["start.bidding"] = kick_bidding;
update_handlers["start.play"] = kick_play;
update_handlers["end.play"] = end_play;
update_handlers["chat.add"] = handle_chat_add;
update_handlers["chat.message"] = handle_table_chat_message;

function on_body_load() {
    $("body").ajaxError(ajaxErrorHandler);
    parse_params();
    start_updator(update_handlers);
    $("#table").data("wid", "table_" + tid);
    init_chat();
    $("#alert_text").width($("#bidbox").width());
    $("#popup_res").text("Waiting for partners");
    $(".popup").bPopup();
}

function parse_params() {
    params = location.search.split("/");
    tid = params[0].substr(1);
    if (params.length > 1) {
	my_side = $.inArray(params[1], sides);
    }
}

function ajaxErrorHandler(event, xhr, opts, error) {
    // retry should be here for some requests
    window.alert("operation failed");
}

function process_hand(v) {
    var side = v.side;
    var cards = v.cards;
    cards.sort(card_sort);
    var h = $("#" + side + "_hand");
    h.children().remove();
    $.each(cards,
	   function(idx, value) {
	       h.append(create_card(side, value).css({"z-index": idx + 1, "left": idx * 9 + "%"}));
	   });
}

function card_sort(c1, c2) {
    if (Math.floor(c1/13) + Math.floor(c2/13) == 1) { /* show clubs before diamonds */
	return c1 - c2;
    } else {
	return c2 - c1;
    }
}

function create_card(side, card) {
    var s = document.createElement("span");
    $(s).addClass("card card_" + side + " suit_" + Math.floor(card/13));
    $(s).attr("id", "card_" + card);
    var bg = "url(images/cards.png) " + (card * -71) +  "px 0";
    return $(s).css("background", bg);
}

function indicator(selector, interval) {
    $(selector).toggleClass("indicator");
    window.setTimeout(function(){$(selector).toggleClass("indicator");}, interval);
}

function indicate_turn(side, my_turn) {
    window.clearInterval(ind_int)
    if (my_turn) {
	window.focus();
    }
    ind_int = window.setInterval(function(){indicator("." + side + "_user", 500)}, 1000);
}

function process_bid(v) {
    var side = v.side;
    var bid = v.bid;
    var alert = v.alert;
    var dbl_rdbl_allowed = v.dbl_mode;
    var bid_html;
    var idx = $.inArray(bid, pass_dbl_rdbl);
    if (idx == -1) {
	var r = bid[0];
	var s = bid[1];
	if (s != 'Z') {
	    var img = suit_image_template.replace("{suit}", s.toLowerCase()).replace("{alt_suit}", s);
	    bid_html = r + img;
	} else {
	    bid_html = r + "NT";
	}

	disallow_lower_bids(parseInt(r), s);
    } else {
	bid_html = bid;
    }
    var bid_cell = $("#bidding_area tr:last td:eq(" + side + ")");
    bid_cell.html(bid_html);
    if (alert != null) {
	bid_cell.CreateBubblePopup({innerHtml: decodeURIComponent(alert), themePath: "images/popup-themes"})
	    .addClass("alert_bid");
    }
    if (side == 3) {
	$("#bidding_area").append("

");
    }
    ns = (side + 1) % 4;
    var my_turn = ns == my_side;
    indicate_turn(sides[ns], my_turn);
    if (my_turn) {
	if (dbl_rdbl_allowed == "dbl") {
	    allow_bid("#bid_dbl");
	} else if (dbl_rdbl_allowed == "rdbl") {
	    allow_bid("#bid_rdbl");
	}
	allow_bid(".bidbox_pass");
	$(".bidbox_bid:not(.prohibited_bid)").bind("click", do_bid).addClass("clickable");
    } else if (side == my_side) {
	$("#alert_text").val("Alert");
    }
}

function prohibit_bid(bid_selector) {
    $(bid_selector).unbind("click").removeClass("clickable").addClass("prohibited_bid");
}

function allow_bid(bid_selector) {
    $(bid_selector).bind("click", do_bid).addClass("clickable").removeClass("prohibited_bid");
}

function disallow_lower_bids(r, s) {
    var bid_id = "bid_" + r + s;
    var allowed_bids = $(".bidbox_bid:not(.prohibited_bid)");
    var filtered = allowed_bids.filter(function(index){return this.id <= bid_id});
    filtered.addClass("prohibited_bid");
}

function process_move(v) {
    if (lead_count % 4 == 0) {
	for (var i = 0; i < 4; i += 1) {
	    $("#" + sides[i] + "_last span").remove();
	    $("#" + sides[i] + "_last")
		.append($("#" + sides[i] + "_lead span").detach());
   	}
	lead_count = 0;
    }

    var side = v.side;
    var card = v.card;
    var allowed = v.allowed;
    var trick = v.trick;
    var card_div_id = "#card_" + card;
    var lead_div_id = "#" + side + "_lead";
    if (trick != null) {
	$("#" + trick + "_tricks").text(trick_inc);
    }

    $(card_div_id).remove();
    $(lead_div_id).append(create_card(side, card).css({"z-index": lead_count, "left": 0}));
    lead_count += 1;
    var np;
    if (v.next != null) {
	ns = v.next;
    } else {
	ns = next_side(side);
    }
    var my_turn = allowed != null;
    indicate_turn(ns, my_turn);
    if (!my_turn) {
	prohibit_cards(".card");
	return;
    }
    prohibit_cards(".card");
    if (allowed == "any") {
	allow_cards(".card_" + ns, ns);
    } else {
	var np_suit_class = ".card_" + ns + ".suit_" + allowed;
	allow_cards(np_suit_class, ns);
    }
}

function prohibit_cards(selector) {
    return $(selector).unbind("click dblclick").removeClass("clickable");
}

function allow_cards(selector, side) {
    return $(selector).bind("click", side, highlight_for_move)
	.bind("dblclick", side, do_move).addClass("clickable");
}

function next_side(side) {
    var idx = $.inArray(side, sides);
    return sides[(idx + 1) % 4]
}

function do_move(event) {
    var side = event.data;
    var splitted_id = event.target.id.split("_");
    var number = splitted_id[1];
    var url = "action.json?move/" + tid + "/" + side + "/" + number;
    $.post(url);
    prohibit_cards(".card");
    $(event.target).remove();
}

function img_by_suit(suit) {
    var c = suit.charAt(0);
    return suit_image_template.replace("{suit}", c.toLowerCase()).replace("{alt_suit}", c.toUpperCase());
}

function kick_bidding(v) {
    if (first_deal) {
	$(".popup").bPopup().close();
	first_deal = false;
    }
    prohibit_bid(".bidbox_pass,.bidbox_dbl,.bidbox_rdbl");
    if (v.vuln & 1) {
	$(".vuln_NS").addClass("vulnerable");
    }

    if (v.vuln & 2) {
	$(".vuln_EW").addClass("vulnerable");
    }

    side = sides[v.dealer];
    indicate_turn(side);
    $("#dealer_" + side).addClass("dealer");
    if (my_side == v.dealer) {
    	$(".bidbox_bid").bind("click", do_bid).addClass("clickable");
	allow_bid(".bidbox_pass");
    }
}

function kick_play(v) {
    var contract = v.contract;
    var lead_maker = v.lead;
    lead_count = 0;
    $("#bidbox").css("display", "none").after($("#bidding_area").detach());
    $("#alert_text").addClass("hidden");
    $("#bidbox_cell").css("text-align", "center");
    $("#lead_area").removeClass("hidden");
    indicate_turn(sides[lead_maker]);
    if (lead_maker == my_side) {
	s = sides[my_side];
	allow_cards(".card_" + s, s);
    }
    var csuit = contract[1];
    var cntrct_html;
    if (csuit != "Z") {
	cntrct_html = contract[0] +
	    big_suit_image_template.replace("{suit}", csuit.toLowerCase())
	    .replace("{alt_suit}", csuit.toUpperCase());
    } else {
	cntrct_html = contract[0] + "NT";
    }
    $("#contract").html(cntrct_html);
    $("#contract_by").text(" by " + contract.substr(contract.length - 1))
}

function highlight_for_move(event) {
    var splitted_id = event.target.id.split("_");
    var number = splitted_id[1];
    allow_cards(".highlighted", event.data).removeClass("highlighted");
    $("#card_" + number).addClass("highlighted").bind("click", event.data, do_move);
}

function do_bid(event) {
    var splitted_id = event.currentTarget.id.split("_");
    var bid = splitted_id[1];
    $(".bidbox_bid:not(.prohibited_bid)").unbind("click").removeClass("clickable");
    prohibit_bid(".bidbox_pass,.bidbox_dbl,.bidbox_rdbl");
    var url = "action.json?bid/" + tid + "/" + my_side + "/" + bid;
    var alert = $("#alert_text").val();
    if (alert != "" && alert != "Alert") {
	url += "/" + alert;
    }
    $.post(url);
}

function trick_inc(i, s) {
    if (s.length == 0) {
	return 1;
    } else {
	return parseInt(s) + 1;
    }
}

function show_tricks(v) {
    if (v.NS > 0) {
	$("#NS_tricks").text(v.NS);
    }
    if (v.EW > 0) {
	$("#EW_tricks").text(v.EW);
    }
}

function end_play(v) {
    $(".vuln_NS,.vuln_EW").removeClass("vulnerable");
    $("#dealer_N,#dealer_E,#dealer_S,#dealer_W").removeClass("dealer");
    $("#bidding_area").removeClass("hidden");
    $("#bidbox").css("display", "inline-block");
    $("#bidbox_cell").css("text-align", "right");
    $("#lead_area").addClass("hidden");
    $("#contract,#contract_by,.tricks").html("");
    $("#bidding_area tr:gt(1)").remove();
    $("#bidding_area tr td").text("").RemoveBubblePopup();
    $("#alert_text").removeClass("hidden");
    $(".hand_container").children().remove();
    $(".hand_container").append($(""));
    $(".bidbox_bid,.bidbox_pass,.bidbox_dbl,.bidbox_rdbl")
	.unbind("click").removeClass("prohibited_bid clickable");
    $(".lead").text("");
    $("#lead_area").before($("#bidding_area").detach());
    var contract = v.contract;
    var decl = v.declearer;
    var points = v.points;
    var tricks = v.tricks;
    var url = v.protocol_url;
    var sign = "";
    if (points > 0) {
	sign = "+";
    }
    var contract_html;
    if (contract == "pass"){
	contract_html = "pass";
    } else {
	var r = contract[0];
	var s = contract[1];
	if (s != "Z") {
	    var img = suit_image_template.replace("{suit}", s.toLowerCase()).replace("{alt_suit}", s);
	    contract_html = r + img;
	} else {
	    contract_html = r + "NT";
	}
    }
    contract_html += contract.substr(2, 2);
    $("#popup_res").html("" +  tricks
			 + " tricks, " + sign + points + "");
    $("#popup_contract").html(contract_html + " by " + decl);
    $(".popup").bPopup();
}

function user_sit(v) {
    if (v.tid == tid) {
	var pos = v.position;
	var name = v.name;
	$("." + pos + "_user").text(name);
    }
}

function user_leave(v) {
    if (v.tid == tid) {
	var pos = v.position;
	$("." + pos + "_user").text("");
    }
}

function handle_table_chat_message(v) {
    var wid = v.wid;
    var idx = wid.indexOf("@");
    if (idx >= 0) {
	wid = wid.substr(0, idx);
    }
    if (wid != $("." + sides[(my_side + 2) % 4] + "_user").text()) {
	handle_chat_message(v);
    }
}
<commit_msg>add top css value to leads<commit_after>var sides = ["N", "E", "S", "W"];
var suit_image_template = "";
var big_suit_image_template = "";
var pass_dbl_rdbl = ["pass", "dbl", "rdbl"];

var lead_count;
var my_side;
var tid;
var ind_int = window.setInterval(function(){}, 9999);
var first_deal = true;

var update_handlers = new Array();
update_handlers["move"] = process_move;
update_handlers["bid"] = process_bid;
update_handlers["hand"] = process_hand;
update_handlers["player.sit"] = user_sit;
update_handlers["player.leave"] = user_leave;
update_handlers["tricks"] = show_tricks;
update_handlers["start.bidding"] = kick_bidding;
update_handlers["start.play"] = kick_play;
update_handlers["end.play"] = end_play;
update_handlers["chat.add"] = handle_chat_add;
update_handlers["chat.message"] = handle_table_chat_message;

function on_body_load() {
    $("body").ajaxError(ajaxErrorHandler);
    parse_params();
    start_updator(update_handlers);
    $("#table").data("wid", "table_" + tid);
    init_chat();
    $("#alert_text").width($("#bidbox").width());
    $("#popup_res").text("Waiting for partners");
    $(".popup").bPopup();
}

function parse_params() {
    params = location.search.split("/");
    tid = params[0].substr(1);
    if (params.length > 1) {
	my_side = $.inArray(params[1], sides);
    }
}

function ajaxErrorHandler(event, xhr, opts, error) {
    // retry should be here for some requests
    window.alert("operation failed");
}

function process_hand(v) {
    var side = v.side;
    var cards = v.cards;
    cards.sort(card_sort);
    var h = $("#" + side + "_hand");
    h.children().remove();
    $.each(cards,
	   function(idx, value) {
	       h.append(create_card(side, value).css({"z-index": idx + 1, "left": idx * 9 + "%"}));
	   });
}

function card_sort(c1, c2) {
    if (Math.floor(c1/13) + Math.floor(c2/13) == 1) { /* show clubs before diamonds */
	return c1 - c2;
    } else {
	return c2 - c1;
    }
}

function create_card(side, card) {
    var s = document.createElement("span");
    $(s).addClass("card card_" + side + " suit_" + Math.floor(card/13));
    $(s).attr("id", "card_" + card);
    var bg = "url(images/cards.png) " + (card * -71) +  "px 0";
    return $(s).css("background", bg);
}

function indicator(selector, interval) {
    $(selector).toggleClass("indicator");
    window.setTimeout(function(){$(selector).toggleClass("indicator");}, interval);
}

function indicate_turn(side, my_turn) {
    window.clearInterval(ind_int)
    if (my_turn) {
	window.focus();
    }
    ind_int = window.setInterval(function(){indicator("." + side + "_user", 500)}, 1000);
}

function process_bid(v) {
    var side = v.side;
    var bid = v.bid;
    var alert = v.alert;
    var dbl_rdbl_allowed = v.dbl_mode;
    var bid_html;
    var idx = $.inArray(bid, pass_dbl_rdbl);
    if (idx == -1) {
	var r = bid[0];
	var s = bid[1];
	if (s != 'Z') {
	    var img = suit_image_template.replace("{suit}", s.toLowerCase()).replace("{alt_suit}", s);
	    bid_html = r + img;
	} else {
	    bid_html = r + "NT";
	}

	disallow_lower_bids(parseInt(r), s);
    } else {
	bid_html = bid;
    }
    var bid_cell = $("#bidding_area tr:last td:eq(" + side + ")");
    bid_cell.html(bid_html);
    if (alert != null) {
	bid_cell.CreateBubblePopup({innerHtml: decodeURIComponent(alert), themePath: "images/popup-themes"})
	    .addClass("alert_bid");
    }
    if (side == 3) {
	$("#bidding_area").append("

");
    }
    ns = (side + 1) % 4;
    var my_turn = ns == my_side;
    indicate_turn(sides[ns], my_turn);
    if (my_turn) {
	if (dbl_rdbl_allowed == "dbl") {
	    allow_bid("#bid_dbl");
	} else if (dbl_rdbl_allowed == "rdbl") {
	    allow_bid("#bid_rdbl");
	}
	allow_bid(".bidbox_pass");
	$(".bidbox_bid:not(.prohibited_bid)").bind("click", do_bid).addClass("clickable");
    } else if (side == my_side) {
	$("#alert_text").val("Alert");
    }
}

function prohibit_bid(bid_selector) {
    $(bid_selector).unbind("click").removeClass("clickable").addClass("prohibited_bid");
}

function allow_bid(bid_selector) {
    $(bid_selector).bind("click", do_bid).addClass("clickable").removeClass("prohibited_bid");
}

function disallow_lower_bids(r, s) {
    var bid_id = "bid_" + r + s;
    var allowed_bids = $(".bidbox_bid:not(.prohibited_bid)");
    var filtered = allowed_bids.filter(function(index){return this.id <= bid_id});
    filtered.addClass("prohibited_bid");
}

function process_move(v) {
    if (lead_count % 4 == 0) {
	for (var i = 0; i < 4; i += 1) {
	    $("#" + sides[i] + "_last span").remove();
	    $("#" + sides[i] + "_last")
		.append($("#" + sides[i] + "_lead span").detach());
   	}
	lead_count = 0;
    }

    var side = v.side;
    var card = v.card;
    var allowed = v.allowed;
    var trick = v.trick;
    var card_div_id = "#card_" + card;
    var lead_div_id = "#" + side + "_lead";
    if (trick != null) {
	$("#" + trick + "_tricks").text(trick_inc);
    }

    $(card_div_id).remove();
    var topv = 0;
    var sidedif = Math.abs(my_side - $.inArray(side, sides));
    if (sidedif == 3) {
	sidedif = 1;
    }
    topv += sidedif * 5;
    $(lead_div_id).append(create_card(side, card).css({"z-index": lead_count, "left": 0, "top": topv+"px"}));
    lead_count += 1;
    var np;
    if (v.next != null) {
	ns = v.next;
    } else {
	ns = next_side(side);
    }
    var my_turn = allowed != null;
    indicate_turn(ns, my_turn);
    if (!my_turn) {
	prohibit_cards(".card");
	return;
    }
    prohibit_cards(".card");
    if (allowed == "any") {
	allow_cards(".card_" + ns, ns);
    } else {
	var np_suit_class = ".card_" + ns + ".suit_" + allowed;
	allow_cards(np_suit_class, ns);
    }
}

function prohibit_cards(selector) {
    return $(selector).unbind("click dblclick").removeClass("clickable");
}

function allow_cards(selector, side) {
    return $(selector).bind("click", side, highlight_for_move)
	.bind("dblclick", side, do_move).addClass("clickable");
}

function next_side(side) {
    var idx = $.inArray(side, sides);
    return sides[(idx + 1) % 4]
}

function do_move(event) {
    var side = event.data;
    var splitted_id = event.target.id.split("_");
    var number = splitted_id[1];
    var url = "action.json?move/" + tid + "/" + side + "/" + number;
    $.post(url);
    prohibit_cards(".card");
    $(event.target).remove();
}

function img_by_suit(suit) {
    var c = suit.charAt(0);
    return suit_image_template.replace("{suit}", c.toLowerCase()).replace("{alt_suit}", c.toUpperCase());
}

function kick_bidding(v) {
    if (first_deal) {
	$(".popup").bPopup().close();
	first_deal = false;
    }
    prohibit_bid(".bidbox_pass,.bidbox_dbl,.bidbox_rdbl");
    if (v.vuln & 1) {
	$(".vuln_NS").addClass("vulnerable");
    }

    if (v.vuln & 2) {
	$(".vuln_EW").addClass("vulnerable");
    }

    side = sides[v.dealer];
    indicate_turn(side);
    $("#dealer_" + side).addClass("dealer");
    if (my_side == v.dealer) {
    	$(".bidbox_bid").bind("click", do_bid).addClass("clickable");
	allow_bid(".bidbox_pass");
    }
}

function kick_play(v) {
    var contract = v.contract;
    var lead_maker = v.lead;
    lead_count = 0;
    $("#bidbox").css("display", "none").after($("#bidding_area").detach());
    $("#alert_text").addClass("hidden");
    $("#bidbox_cell").css("text-align", "center");
    $("#lead_area").removeClass("hidden");
    indicate_turn(sides[lead_maker]);
    if (lead_maker == my_side) {
	s = sides[my_side];
	allow_cards(".card_" + s, s);
    }
    var csuit = contract[1];
    var cntrct_html;
    if (csuit != "Z") {
	cntrct_html = contract[0] +
	    big_suit_image_template.replace("{suit}", csuit.toLowerCase())
	    .replace("{alt_suit}", csuit.toUpperCase());
    } else {
	cntrct_html = contract[0] + "NT";
    }
    $("#contract").html(cntrct_html);
    $("#contract_by").text(" by " + contract.substr(contract.length - 1))
}

function highlight_for_move(event) {
    var splitted_id = event.target.id.split("_");
    var number = splitted_id[1];
    allow_cards(".highlighted", event.data).removeClass("highlighted");
    $("#card_" + number).addClass("highlighted").bind("click", event.data, do_move);
}

function do_bid(event) {
    var splitted_id = event.currentTarget.id.split("_");
    var bid = splitted_id[1];
    $(".bidbox_bid:not(.prohibited_bid)").unbind("click").removeClass("clickable");
    prohibit_bid(".bidbox_pass,.bidbox_dbl,.bidbox_rdbl");
    var url = "action.json?bid/" + tid + "/" + my_side + "/" + bid;
    var alert = $("#alert_text").val();
    if (alert != "" && alert != "Alert") {
	url += "/" + alert;
    }
    $.post(url);
}

function trick_inc(i, s) {
    if (s.length == 0) {
	return 1;
    } else {
	return parseInt(s) + 1;
    }
}

function show_tricks(v) {
    if (v.NS > 0) {
	$("#NS_tricks").text(v.NS);
    }
    if (v.EW > 0) {
	$("#EW_tricks").text(v.EW);
    }
}

function end_play(v) {
    $(".vuln_NS,.vuln_EW").removeClass("vulnerable");
    $("#dealer_N,#dealer_E,#dealer_S,#dealer_W").removeClass("dealer");
    $("#bidding_area").removeClass("hidden");
    $("#bidbox").css("display", "inline-block");
    $("#bidbox_cell").css("text-align", "right");
    $("#lead_area").addClass("hidden");
    $("#contract,#contract_by,.tricks").html("");
    $("#bidding_area tr:gt(1)").remove();
    $("#bidding_area tr td").text("").RemoveBubblePopup().removeClass("alertBid");
    $("#alert_text").removeClass("hidden");
    $(".hand_container").children().remove();
    $(".hand_container").append($(""));
    $(".bidbox_bid,.bidbox_pass,.bidbox_dbl,.bidbox_rdbl")
	.unbind("click").removeClass("prohibited_bid clickable");
    $(".lead").text("");
    $("#lead_area").before($("#bidding_area").detach());
    var contract = v.contract;
    var decl = v.declearer;
    var points = v.points;
    var tricks = v.tricks;
    var url = v.protocol_url;
    var sign = "";
    if (points > 0) {
	sign = "+";
    }
    var contract_html;
    if (contract == "pass"){
	contract_html = "pass";
    } else {
	var r = contract[0];
	var s = contract[1];
	if (s != "Z") {
	    var img = suit_image_template.replace("{suit}", s.toLowerCase()).replace("{alt_suit}", s);
	    contract_html = r + img;
	} else {
	    contract_html = r + "NT";
	}
    }
    contract_html += contract.substr(2, 2);
    $("#popup_res").html("" +  tricks
			 + " tricks, " + sign + points + "");
    $("#popup_contract").html(contract_html + " by " + decl);
    $(".popup").bPopup();
}

function user_sit(v) {
    if (v.tid == tid) {
	var pos = v.position;
	var name = v.name;
	$("." + pos + "_user").text(name);
    }
}

function user_leave(v) {
    if (v.tid == tid) {
	var pos = v.position;
	$("." + pos + "_user").text("");
    }
}

function handle_table_chat_message(v) {
    var wid = v.wid;
    var idx = wid.indexOf("@");
    if (idx >= 0) {
	wid = wid.substr(0, idx);
    }
    if (wid != $("." + sides[(my_side + 2) % 4] + "_user").text()) {
	handle_chat_message(v);
    }
}
<|endoftext|>


<commit_before>/* tools.js */

/*
 *	inputType
 *	returns the type of file @fileName is, based on the extension
 *	options so far are 'nifti' and 'image'
 *
 *
 */
function inputType(fileName) {
	var idx = fileName.lastIndexOf('.');

	if (idx == 0) {
		return 0;
	}

	var ext = fileName.substr(idx + 1);
	var file = fileName.substr(0, idx);

	// if it's .gz', recurse. This may fail for jpg.gz, etc...
	if (ext.localeCompare('gz') == 0) {
		assert(inputType(file).localeCompare('nifti') == 0, 'wrong inputType (' + inputType(file) + ')');
		return 'nifti';
	} else if (ext.localeCompare('jpg') == 0 || ext.localeCompare('png') == 0) {
		return 'image';
	} else if (ext.localeCompare('nii') == 0) {
		return 'nifti';
	} else {
		return undefined;
	}
}

function randString() {
	return Math.random().toString(36).slice(2);
}

function openDataURL(target) {
	window.open(getDataURL(), target);
}

/** Standard assert function
 * source: http://cse.csusb.edu/turner/wiki/Javascript_Assert_Function
 * @param expression - the expression to assert
 * @param msg [optional] - the message if assertion fails
 */
function assert(expression, msg) {
	if (!expression) {
		if (msg === undefined) {
			window.alert("Assertion failed.");
		} else {
			window.alert("Assertion failed: " + msg);
		}
		throw "stop execution";
	}
}

/** Obtain mouse position inside canvas
 *
 * @param canvas - the canvas
 * @param evt - the event.
 * @returns object with x and y variables
 */
function getMousePos(canvas, evt) {
	var rect = canvas.getBoundingClientRect();
	return {
		x : evt.clientX - rect.left,
		y : evt.clientY - rect.top
	};
}

/**
 * Transform an integer array to a img object.
 *
 * Note: This function uses TMP_DISPLAY to write and read the image, so be aware of race conditions
 * Example: TMP_DISPLAY is 'mainDisplayTest' in tipiX site
 *
 * @param array the integer array to transform into an image object
 * @param width the width of the image object
 * @param height the height of the image object. width * height should be the size of the given array
 * @param TMP_DISPLAY a temporary canvas
 *
 * @TODO make height and TMP_DISPLAY optional. if TMP_DISPLAY not provided, make a random string and
 * 	create a canvas with that name.
 */
function array2img(array, width, height, isColor, TMP_DISPLAY) {

	// first, get image data
	var canvas = document.getElementById(TMP_DISPLAY);
	var ctx = canvas.getContext('2d');
	var imgData = array2imgData(array, width, height, isColor, TMP_DISPLAY);

	// put the imgData in the canvas
	// NOTSURE: need to set canvas width and height for when you do toDataURL?
	canvas.width = width;
	canvas.height = height;
	ctx.putImageData(imgData, 0, 0);

	// get the image from the hidden canvas?
	var img = document.createElement("img");
	img.src = canvas.toDataURL("image/png");

	// return
	return img;
}

/**
 * Transform an integer array to a imgData object.
 *
 * Note: This function uses TMP_DISPLAY to write and read the image, so be aware of race conditions
 * Example: TMP_DISPLAY is 'mainDisplayTest' in tipiX site
 *
 * @param array the integer array to transform into an image object
 * @param width the width of the image object
 * @param height the height of the image object. width * height should be the size of the given array
 * @param TMP_DISPLAY a temporary canvas
 *
 * @TODO make height and TMP_DISPLAY optional. if TMP_DISPLAY not provided, make a random string and
 * 	create a canvas with that name.
 */
function array2imgData(array, width, height, isColor, TMP_DISPLAY) {

	// first, get image data
	var canvas = document.getElementById(TMP_DISPLAY);
	var ctx = canvas.getContext('2d');
	var imgData = ctx.createImageData(width, height);
	var data = imgData.data;

	//console.log(array.length);
	//console.log(width * height);

	// copy img byte-per-byte into our ImageData
	for (var i = 0, len = width * height * 4; i < len; i += 4) {
		var j = i/4
		if (isColor) {k = j + width*height; l = k + width*height; }
		else {k = j; l = j;}
		data[i] = array[j];
		data[i+1] = array[k];
		data[i+2] = array[l];
		data[i+3] = 255;
	}

	// return the image data
	return imgData

}

function onOff(containerName) {

	state = document.getElementById(containerName).className
	if (state == 'on')
		document.getElementById(containerName).className = 'off';
	else
		document.getElementById(containerName).className = 'on';
}

function updownContainer(containerName) {

	state = document.getElementById(containerName).className
	if (state == 'up')
		document.getElementById(containerName).className = 'down';
	else
		document.getElementById(containerName).className = 'up';
}

function inoutContainer(containerName) {

	state = document.getElementById(containerName).className
	if (state == 'in')
		document.getElementById(containerName).className = 'out';
	else
		document.getElementById(containerName).className = 'in';
}<commit_msg>comment fix<commit_after>/* tools.js */

/*
 *	inputType
 *	returns the type of file @fileName is, based on the extension
 *	options so far are 'nifti' and 'image'
 *
 *
 */
function inputType(fileName) {
	var idx = fileName.lastIndexOf('.');

	if (idx == 0) {
		return 0;
	}

	var ext = fileName.substr(idx + 1);
	var file = fileName.substr(0, idx);

	// if it's .gz', recurse. This may fail for jpg.gz, etc...
	if (ext.localeCompare('gz') == 0) {
		assert(inputType(file).localeCompare('nifti') == 0, 'wrong inputType (' + inputType(file) + ')');
		return 'nifti';
	} else if (ext.localeCompare('jpg') == 0 || ext.localeCompare('png') == 0) {
		return 'image';
	} else if (ext.localeCompare('nii') == 0) {
		return 'nifti';
	} else {
		return undefined;
	}
}

function randString() {
	return Math.random().toString(36).slice(2);
}

function openDataURL(target) {
	window.open(getDataURL(), target);
}

/** Standard assert function
 * source: http://cse.csusb.edu/turner/wiki/Javascript_Assert_Function
 * @param expression - the expression to assert
 * @param msg [optional] - the message if assertion fails
 */
function assert(expression, msg) {
	if (!expression) {
		if (msg === undefined) {
			window.alert("Assertion failed.");
		} else {
			window.alert("Assertion failed: " + msg);
		}
		throw "stop execution";
	}
}

/** Obtain mouse position inside canvas
 *
 * @param canvas - the canvas
 * @param evt - the event.
 * @returns object with x and y variables
 */
function getMousePos(canvas, evt) {
	var rect = canvas.getBoundingClientRect();
	return {
		x : evt.clientX - rect.left,
		y : evt.clientY - rect.top
	};
}

/**
 * Transform an integer array to a img object.
 *
 * Note: This function uses TMP_DISPLAY to write and read the image, so be aware of race conditions
 * Example: TMP_DISPLAY is 'mainDisplayTest' in tipiX site
 *
 * @param array the integer array to transform into an image object
 * @param width the width of the image object
 * @param height the height of the image object. width * height should be the size of the given array
 * @param TMP_DISPLAY a temporary canvas
 *
 * @TODO make height and TMP_DISPLAY optional. if TMP_DISPLAY not provided, make a random string and
 * 	create a canvas with that name.
 */
function array2img(array, width, height, isColor, TMP_DISPLAY) {

	// first, get image data
	var canvas = document.getElementById(TMP_DISPLAY);
	var ctx = canvas.getContext('2d');
	var imgData = array2imgData(array, width, height, isColor, TMP_DISPLAY);

	// put the imgData in the canvas
	// NOTSURE: need to set canvas width and height for when you do toDataURL?
	canvas.width = width;
	canvas.height = height;
	ctx.putImageData(imgData, 0, 0);

	// get the image from the hidden canvas
	var img = document.createElement("img");
	img.src = canvas.toDataURL("image/png");

	// return
	return img;
}

/**
 * Transform an integer array to a imgData object.
 *
 * Note: This function uses TMP_DISPLAY to write and read the image, so be aware of race conditions
 * Example: TMP_DISPLAY is 'mainDisplayTest' in tipiX site
 *
 * @param array the integer array to transform into an image object
 * @param width the width of the image object
 * @param height the height of the image object. width * height should be the size of the given array
 * @param TMP_DISPLAY a temporary canvas
 *
 * @TODO make height and TMP_DISPLAY optional. if TMP_DISPLAY not provided, make a random string and
 * 	create a canvas with that name.
 */
function array2imgData(array, width, height, isColor, TMP_DISPLAY) {

	// first, get image data
	var canvas = document.getElementById(TMP_DISPLAY);
	var ctx = canvas.getContext('2d');
	var imgData = ctx.createImageData(width, height);
	var data = imgData.data;

	//console.log(array.length);
	//console.log(width * height);

	// copy img byte-per-byte into our ImageData
	for (var i = 0, len = width * height * 4; i < len; i += 4) {
		var j = i/4
		if (isColor) {k = j + width*height; l = k + width*height; }
		else {k = j; l = j;}
		data[i] = array[j];
		data[i+1] = array[k];
		data[i+2] = array[l];
		data[i+3] = 255;
	}

	// return the image data
	return imgData

}

function onOff(containerName) {

	state = document.getElementById(containerName).className
	if (state == 'on')
		document.getElementById(containerName).className = 'off';
	else
		document.getElementById(containerName).className = 'on';
}

function updownContainer(containerName) {

	state = document.getElementById(containerName).className
	if (state == 'up')
		document.getElementById(containerName).className = 'down';
	else
		document.getElementById(containerName).className = 'up';
}

function inoutContainer(containerName) {

	state = document.getElementById(containerName).className
	if (state == 'in')
		document.getElementById(containerName).className = 'out';
	else
		document.getElementById(containerName).className = 'in';
}<|endoftext|>


<commit_before>// setup canvas
const canvas = document.getElementById("fractalCanvas")
const context = canvas.getContext('2d')

// draws a line
function drawLine(startPoint, endPoint) {
    context.beginPath()
    context.moveTo(startPoint.x, startPoint.y)
    context.lineTo(endPoint.x, endPoint.y)
    context.stroke()
}

// converts a degree angle to radians
function degToRad(angleDeg) {
    return angleDeg * (Math.PI / 180)
}

// draws a tree (recursively)
function drawTree(startPoint, endPoint, angleDeg) {

    // exit condition for recursion
    const diffX = startPoint.x - endPoint.x
    const diffY = startPoint.y - endPoint.y
    const lineLength = Math.sqrt(Math.pow(diffX, 2) + Math.pow(diffY, 2))

    if(lineLength<1) {
        return
    }

    // draw line between the two points
    drawLine(startPoint, endPoint)

    // calculate length of next lines
    const newLength = lineLength * 2/3

    // calculate angle between the two points
    const existingAngle = Math.atan2(endPoint.y - startPoint.y, endPoint.x - startPoint.x)

    // calculate new end points
    const pointRight = {
        x: endPoint.x + newLength * Math.cos((existingAngle - degToRad(angleDeg))),
        y: endPoint.y + newLength * Math.sin((existingAngle - degToRad(angleDeg)))
    }

    const pointLeft = {
        x: endPoint.x + newLength * Math.cos((existingAngle + degToRad(angleDeg))),
        y: endPoint.y + newLength * Math.sin((existingAngle + degToRad(angleDeg)))
    }

    drawTree(endPoint, pointRight, angleDeg)
    drawTree(endPoint, pointLeft, angleDeg)

}

//start the recursion
drawTree({x: 400, y: 700}, {x: 400, y: 550}, 30)<commit_msg>animated version possible<commit_after>// setup canvas
const canvas = document.getElementById("fractalCanvas")
const context = canvas.getContext('2d')

// drawing parameters
const shortenFactor = 0.7

// draws a line
function drawLine(startPoint, endPoint) {
    context.beginPath()
    context.moveTo(startPoint.x, startPoint.y)
    context.lineTo(endPoint.x, endPoint.y)
    context.stroke()
}

// converts a degree angle to radians
function degToRad(angleDeg) {
    return angleDeg * (Math.PI / 180)
}

// draws a tree (recursively)
function drawTree(startPoint, endPoint, angleDeg) {

    // exit condition for recursion
    const diffX = startPoint.x - endPoint.x
    const diffY = startPoint.y - endPoint.y
    const lineLength = Math.sqrt(Math.pow(diffX, 2) + Math.pow(diffY, 2))

    if(lineLength<1) {
        return
    }

    // draw line between the two points
    drawLine(startPoint, endPoint)

    // calculate length of next lines
    const newLength = lineLength * shortenFactor

    // calculate angle between the two points
    const existingAngle = Math.atan2(endPoint.y - startPoint.y, endPoint.x - startPoint.x)

    // calculate new end points
    const pointRight = {
        x: endPoint.x + newLength * Math.cos((existingAngle - degToRad(angleDeg))),
        y: endPoint.y + newLength * Math.sin((existingAngle - degToRad(angleDeg)))
    }

    const pointLeft = {
        x: endPoint.x + newLength * Math.cos((existingAngle + degToRad(angleDeg))),
        y: endPoint.y + newLength * Math.sin((existingAngle + degToRad(angleDeg)))
    }

    drawTree(endPoint, pointRight, angleDeg)
    drawTree(endPoint, pointLeft, angleDeg)

}

// static
drawTree({x: 400, y: 700}, {x: 400, y: 550}, 45)

// // animated
// let direction = 1
// let angle = 1

// setInterval(function() {
//     context.clearRect(0, 0, canvas.width, canvas.height)

//     if(angle === 0 || angle === 90) {
//         direction = - direction
//     }

//     drawTree({x: 400, y: 700}, {x: 400, y: 550}, angle)

//     angle += direction

// }, 5)<|endoftext|>


<commit_before>var LinkModel = Backbone.Model.extend({
  defaults: function() {
    return {
      title: null,
      desc: null,
      url: null
    };
  },
});

var LinkCollection = Backbone.Collection.extend({
  model: LinkModel,
  url: 'links.json'
});

var LinkView = Backbone.View.extend({
  tagName: 'li',
  template: _.template($('#item-template').html()),

  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});

var LinksView = Backbone.View.extend({
  el: "#link-list",
  wasSearching: false,
  initialize: function() {
    this.listenTo(Links, 'add', this.addOne);
    this.listenTo(Links, 'reset', this.displaySearch);
    Links.fetch();
  },
  addOne: function(linkModel) {
    if(this.wasSearching === true) {
      this.clearView();
      this.wasSearching = false;
    }

    var view = new LinkView({model: linkModel});
    this.$el.append(view.render().el);
  },
  displaySearch: function(newModel) {
    var _this = this;

    this.clearView();
    newModel.models.forEach(function(model) {
      _this.addOne(model);
    });
    this.wasSearching = true;
  },

  clearView: function() {
    this.$el.children().remove();
    this.$el.empty();
  }
});

var Links = new LinkCollection();
var listView = new LinksView();
var searching = null;

$('#search').keyup(function(ev) {
  if(searching !== null) {
    clearTimeout(searching);
  }
  var textToFind = ev.target.value;
  if(textToFind.trim().length === 0) {
    Links.fetch();
  } else {
    searching = startSearch(textToFind);
  }
});

function startSearch(word) {
  return setTimeout(function() {
    var filtered = Links.filter(function(elem) {
      var searchInTitle = elem.get('title') === undefined ? -1 : elem.get('title').toLowerCase().indexOf(word);
      var searchInDesc = elem.get('desc') === undefined ? -1 : elem.get('desc').toLowerCase().indexOf(word);
      var searchInUrl = elem.get('url') === undefined ? -1 : elem.get('url').toLowerCase().indexOf(word);

      return searchInTitle > -1 ||
             searchInUrl > -1 ||
             searchInDesc > -1;
    });
    Links.reset(filtered);
  }, 1000);
}<commit_msg>Check for null instead of undefined<commit_after>var LinkModel = Backbone.Model.extend({
  defaults: function() {
    return {
      title: null,
      desc: null,
      url: null
    };
  },
});

var LinkCollection = Backbone.Collection.extend({
  model: LinkModel,
  url: 'links.json'
});

var LinkView = Backbone.View.extend({
  tagName: 'li',
  template: _.template($('#item-template').html()),

  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});

var LinksView = Backbone.View.extend({
  el: "#link-list",
  wasSearching: false,
  initialize: function() {
    this.listenTo(Links, 'add', this.addOne);
    this.listenTo(Links, 'reset', this.displaySearch);
    Links.fetch();
  },
  addOne: function(linkModel) {
    if(this.wasSearching === true) {
      this.clearView();
      this.wasSearching = false;
    }

    var view = new LinkView({model: linkModel});
    this.$el.append(view.render().el);
  },
  displaySearch: function(newModel) {
    var _this = this;

    this.clearView();
    newModel.models.forEach(function(model) {
      _this.addOne(model);
    });
    this.wasSearching = true;
  },

  clearView: function() {
    this.$el.children().remove();
    this.$el.empty();
  }
});

var Links = new LinkCollection();
var listView = new LinksView();
var searching = null;

$('#search').keyup(function(ev) {
  if(searching !== null) {
    clearTimeout(searching);
  }
  var textToFind = ev.target.value;
  if(textToFind.trim().length === 0) {
    Links.fetch();
  } else {
    searching = startSearch(textToFind);
  }
});

function startSearch(word) {
  return setTimeout(function() {
    var filtered = Links.filter(function(elem) {
      var searchInTitle = elem.get('title') === null ? -1 : elem.get('title').toLowerCase().indexOf(word);
      var searchInDesc = elem.get('desc') === null ? -1 : elem.get('desc').toLowerCase().indexOf(word);
      var searchInUrl = elem.get('url') === null ? -1 : elem.get('url').toLowerCase().indexOf(word);

      return searchInTitle > -1 ||
             searchInUrl > -1 ||
             searchInDesc > -1;
    });
    Links.reset(filtered);
  }, 1000);
}
<|endoftext|>


<commit_before>// -------------------------------------------------
// ------------------ Utils ------------------------
// -------------------------------------------------

function DebugMessage(message) {
    console.log(message);
}

function abort() {
    DebugMessage("Abort execution.");
    sys.PrintState();
    throw new Error('Abort javascript');
}

// big endian to little endian and vice versa
function Swap32(val) {
    return ((val & 0xFF) << 24) | ((val & 0xFF00) << 8) | ((val >>> 8) & 0xFF00) | ((val >>> 24) & 0xFF);
}

// cast an integer so a signed integer
function int32(val) {
    return (val >> 0);
}

// cast an integer so a unsigned integer
function uint32(val) {
    return (val >>> 0);
}

function hex8(x) {
    var val = uint32(x);
    return ("0x" + ("00000000" + val.toString(16)).substr(-8).toUpperCase());
}

function CopyBinary(to, from, size, buffersrc, bufferdest) {
    var i = 0;
    for (i = 0; i < size; i++) {
        bufferdest[to + i] = buffersrc[from + i];
    }
}

function LoadBinaryResource(url, OnLoadFunction) {
    var req = new XMLHttpRequest();
    req.open('GET', url, true);
    req.responseType = "arraybuffer";
    req.onreadystatechange = function () {
        if (req.readyState != 4) {
            return;
        }
        if ((req.status != 200) && (req.status != 0)) {
            DebugMessage("Error: Could not load file " + url);
            return;
        }
        var arrayBuffer = req.response;
        if (arrayBuffer) {
            OnLoadFunction(arrayBuffer);
        }
    };
    /*
        req.onload = function(e)
        {
                var arrayBuffer = req.response;
                if (arrayBuffer) {
                    OnLoadFunction(arrayBuffer);
                }
        };
    */
    req.send(null);
}

<commit_msg>Add Swap16<commit_after>// -------------------------------------------------
// ------------------ Utils ------------------------
// -------------------------------------------------

function DebugMessage(message) {
    console.log(message);
}

function abort() {
    DebugMessage("Abort execution.");
    sys.PrintState();
    throw new Error('Abort javascript');
}

// big endian to little endian and vice versa
function Swap32(val) {
    return ((val & 0xFF) << 24) | ((val & 0xFF00) << 8) | ((val >>> 8) & 0xFF00) | ((val >>> 24) & 0xFF);
}

function Swap16(val) {
    return ((val & 0xFF) << 8) | ((val >> 8) & 0xFF);
}

// cast an integer so a signed integer
function int32(val) {
    return (val >> 0);
}

// cast an integer so a unsigned integer
function uint32(val) {
    return (val >>> 0);
}

function hex8(x) {
    var val = uint32(x);
    return ("0x" + ("00000000" + val.toString(16)).substr(-8).toUpperCase());
}

function CopyBinary(to, from, size, buffersrc, bufferdest) {
    var i = 0;
    for (i = 0; i < size; i++) {
        bufferdest[to + i] = buffersrc[from + i];
    }
}

function LoadBinaryResource(url, OnLoadFunction) {
    var req = new XMLHttpRequest();
    req.open('GET', url, true);
    req.responseType = "arraybuffer";
    req.onreadystatechange = function () {
        if (req.readyState != 4) {
            return;
        }
        if ((req.status != 200) && (req.status != 0)) {
            DebugMessage("Error: Could not load file " + url);
            return;
        }
        var arrayBuffer = req.response;
        if (arrayBuffer) {
            OnLoadFunction(arrayBuffer);
        }
    };
    /*
        req.onload = function(e)
        {
                var arrayBuffer = req.response;
                if (arrayBuffer) {
                    OnLoadFunction(arrayBuffer);
                }
        };
    */
    req.send(null);
}

<|endoftext|>


<commit_before>// Some general purpose JS functions for the iTop application

//IE 8 compatibility, copied from: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/IndexOf
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
    	"use strict";
        if (this == null) {
        	throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
        	return -1;
        }
        var n = 0;
        if (arguments.length > 1) {
        	n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
            	n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
            	n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
        	return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
        	if (k in t && t[k] === searchElement) {
            	return k;
            }
        }
        return -1;
    }
}
/**
 * Reload a truncated list
 */
aTruncatedLists = {}; // To keep track of the list being loaded, each member is an ajaxRequest object

function ReloadTruncatedList(divId, sSerializedFilter, sExtraParams)
{
	$('#'+divId).block();
	//$('#'+divId).blockUI();
	if (aTruncatedLists[divId] != undefined)
	{
		try
		{
			aAjaxRequest = aTruncatedLists[divId];
			aAjaxRequest.abort();
		}
		catch(e)
		{
			// Do nothing special, just continue
			console.log('Uh,uh, exception !');
		}
	}
	aTruncatedLists[divId] = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?style=list',
	   { operation: 'ajax', filter: sSerializedFilter, extra_params: sExtraParams },
	     function(data)
	     {
			 aTruncatedLists[divId] = undefined;
			 if (data.length > 0)
			 {
				 $('#'+divId).html(data);
				 $('#'+divId+' .listResults').tableHover(); // hover tables
				 $('#'+divId+' .listResults').each( function()
					{
						var table = $(this);
						var id = $(this).parent();
						aTruncatedLists[divId] = undefined;
						var checkbox = (table.find('th:first :checkbox').length > 0);
						if (checkbox)
						{
							// There is a checkbox in the first column, don't make it sortable
							table.tablesorter( { headers: { 0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ).tablesorterPager({container: $("#pager")}); // sortable and zebra tables
						}
						else
						{
							// There is NO checkbox in the first column, all columns are considered sortable
							table.tablesorter( { widgets: ['myZebra', 'truncatedList']} ).tablesorterPager({container: $("#pager"), totalRows:97, filter: sSerializedFilter, extra_params: sExtraParams }); // sortable and zebra tables
						}
					});
				 $('#'+divId).unblock();
			 }
		}
	 );
}
/**
 * Truncate a previously expanded list !
 */
function TruncateList(divId, iLimit, sNewLabel, sLinkLabel)
{
	$('#'+divId).block();
	var iCount = 0;
	$('#'+divId+' table.listResults tr:gt('+iLimit+')').each( function(){
			$(this).remove();
	});
	$('#lbl_'+divId).html(sNewLabel);
	$('#'+divId+' table.listResults tr:last td').addClass('truncated');
	$('#'+divId+' table.listResults').addClass('truncated');
	$('#trc_'+divId).html(sLinkLabel);
	$('#'+divId+' .listResults').trigger("update"); //  Reset the cache
	$('#'+divId).unblock();
}
/**
 * Reload any block -- used for periodic auto-reload
 */
function ReloadBlock(divId, sStyle, sSerializedFilter, sExtraParams)
{
	// Check if the user is not editing the list properties right now
	var bDialogOpen = false;
	var oDataTable = $('#'+divId+' :itop-datatable');
	if (oDataTable.length > 0)
	{
		bDialogOpen = oDataTable.datatable('IsDialogOpen');
	}
	if (!bDialogOpen)
	{
		$('#'+divId).block();

		$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?style='+sStyle,
		   { operation: 'ajax', filter: sSerializedFilter, extra_params: sExtraParams },
		   function(data){
			 $('#'+divId).empty();
			 $('#'+divId).append(data);
			 $('#'+divId).removeClass('loading');
			}
		 );
	}
}

/**
 * Update the display and value of a file input widget when the user picks a new file
 */
function UpdateFileName(id, sNewFileName)
{
	var aPath = sNewFileName.split('\\');
	var sNewFileName = aPath[aPath.length-1];

	$('#'+id).val(sNewFileName);
	$('#'+id).trigger('validate');
	$('#name_'+id).text(sNewFileName);
	return true;
}
/**
 * Reload a search form for the specified class
 */
function ReloadSearchForm(divId, sClassName, sBaseClass, sContext)
{
    var oDiv = $('#ds_'+divId);
	oDiv.block();
	// deprecated in jQuery 1.8
	//var oFormEvents = $('#ds_'+divId+' form').data('events');
	var oForm = $('#ds_'+divId+' form');
	var oFormEvents = $._data(oForm[0], "events");

	// Save the submit handlers
    aSubmit = new Array();
	if ( (oFormEvents != null) && (oFormEvents.submit != undefined))
	{
		for(var index = 0; index < oFormEvents.submit.length; index++)
		{
			aSubmit [index ] = { data:oFormEvents.submit[index].data, namespace:oFormEvents.submit[index].namespace, handler:  oFormEvents.submit[index].handler};
		}
	}
	sAction =  $('#ds_'+divId+' form').attr('action');

	// Save the current values in the form
	var oMap = {};
	$('#ds_'+divId+" form :input[name!='']").each(function() {
		oMap[this.name] = this.value;
	});
	oMap.operation = 'search_form';
	oMap.className = sClassName;
	oMap.baseClass = sBaseClass;
	oMap.currentId = divId;
	oMap.action = sAction;

	$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?'+sContext, oMap,
	   function(data) {
		   oDiv.empty();
		   oDiv.append(data);
		   if (aSubmit.length > 0)
		   {
			    var oForm = $('#ds_'+divId+' form'); // Form was reloaded, recompute it
				for(var index = 0; index < aSubmit.length; index++)
				{
					// Restore the previously bound submit handlers
					if (aSubmit[index].data != undefined)
					{
						oForm.bind('submit.'+aSubmit[index].namespace, aSubmit[index].data, aSubmit[index].handler)
					}
					else
					{
						oForm.bind('submit.'+aSubmit[index].namespace, aSubmit[index].handler)
					}
				}
		   }
		   oDiv.unblock();
		   oDiv.parent().resize(); // Inform the parent that the form has just been (potentially) resized
	   }
	 );
}

/**
 * Stores - in a persistent way - user specific preferences
 * depends on a global variable oUserPreferences created/filled by the iTopWebPage
 * that acts as a local -write through- cache
 */
function SetUserPreference(sPreferenceCode, sPrefValue, bPersistent)
{
	sPreviousValue = undefined;
	try
	{
		sPreviousValue = oUserPreferences[sPreferenceCode];
	}
	catch(err)
	{
		sPreviousValue = undefined;
	}
    oUserPreferences[sPreferenceCode] = sPrefValue;
    if (bPersistent && (sPrefValue != sPreviousValue))
    {
    	ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php',
    						  { operation: 'set_pref', code: sPreferenceCode, value: sPrefValue} ); // Make it persistent
    }
}

/**
 * Get user specific preferences
 * depends on a global variable oUserPreferences created/filled by the iTopWebPage
 * that acts as a local -write through- cache
 */
function GetUserPreference(sPreferenceCode, sDefaultValue)
{
	var value = sDefaultValue;
	if ( oUserPreferences[sPreferenceCode] != undefined)
	{
		value = oUserPreferences[sPreferenceCode];
	}
	return value;
}

/**
 * Check/uncheck a whole list of checkboxes
 */
function CheckAll(sSelector, bValue)
{
	var value = bValue;
	$(sSelector).each( function() {
		if (this.checked != value)
		{
			this.checked = value;
			$(this).trigger('change');
		}
	});
}

/**
 * Toggle (enabled/disabled) the specified field of a form
 */
function ToogleField(value, field_id)
{
	if (value)
	{
		$('#'+field_id).removeAttr('disabled');
	}
	else
	{
		$('#'+field_id).attr('disabled', 'disabled');
	}
	$('#'+field_id).trigger('update');
	$('#'+field_id).trigger('validate');
}

/**
 * For the fields that cannot be visually disabled, they can be blocked
 * @return
 */
function BlockField(field_id, bBlocked)
{
	if (bBlocked)
	{
		$('#'+field_id).block({ message: ' ** disabled ** '});
	}
	else
	{
		$('#'+field_id).unblock();
	}
}

/**
 * Updates (enables/disables) a "duration" field
 */
function ToggleDurationField(field_id)
{
	// Toggle all the subfields that compose the "duration" input
	aSubFields = new Array('d', 'h', 'm', 's');

	if ($('#'+field_id).attr('disabled'))
	{
		for(var i=0; i<aSubFields.length; i++)
		{
			$('#'+field_id+'_'+aSubFields[i]).attr('disabled', 'disabled');
		}
	}
	else
	{
		for(var i=0; i<aSubFields.length; i++)
		{
			$('#'+field_id+'_'+aSubFields[i]).removeAttr('disabled');
		}
	}
}

/**
 * PropagateCheckBox
 */
function PropagateCheckBox(bCurrValue, aFieldsList, bCheck)
{
	if (bCurrValue == bCheck)
	{
		for(var i=0;i<aFieldsList.length;i++)
		{
			$('#enable_'+aFieldsList[i]).attr('checked', bCheck);
			ToogleField(bCheck, aFieldsList[i]);
		}
	}
}

function FixTableSorter(table)
{
	if ($('th.header', table).length == 0)
	{
		// Table is not sort-able, let's fix it
		var checkbox = (table.find('th:first :checkbox').length > 0);
		if (checkbox)
		{
			// There is a checkbox in the first column, don't make it sort-able
			table.tablesorter( { headers: { 0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ); // sort-able and zebra tables
		}
		else
		{
			// There is NO checkbox in the first column, all columns are considered sort-able
			table.tablesorter( { widgets: ['myZebra', 'truncatedList']} ); // sort-able and zebra tables
		}
	}
}

function DashletCreationDlg(sOQL)
{
	$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', {operation: 'dashlet_creation_dlg', oql: sOQL}, function(data){
		$('body').append(data);
	});
	return false;
}

function ShortcutListDlg(sOQL, sContext)
{
	$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?'+sContext, {operation: 'shortcut_list_dlg', oql: sOQL}, function(data){
		$('body').append(data);
	});
	return false;
}<commit_msg>Forget about IE 8 support ???<commit_after>// Some general purpose JS functions for the iTop application

//IE 8 compatibility, copied from: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/IndexOf
if (!Array.prototype.indexOf) {

	if (false) // deactivated since it causes troubles: for(k in aData) => returns the indexOf function as first element on empty arrays !
	{
	Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
    	"use strict";
        if (this == null) {
        	throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
        	return -1;
        }
        var n = 0;
        if (arguments.length > 1) {
        	n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
            	n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
            	n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
        	return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
        	if (k in t && t[k] === searchElement) {
            	return k;
            }
        }
        return -1;
    }
	}
}
/**
 * Reload a truncated list
 */
aTruncatedLists = {}; // To keep track of the list being loaded, each member is an ajaxRequest object

function ReloadTruncatedList(divId, sSerializedFilter, sExtraParams)
{
	$('#'+divId).block();
	//$('#'+divId).blockUI();
	if (aTruncatedLists[divId] != undefined)
	{
		try
		{
			aAjaxRequest = aTruncatedLists[divId];
			aAjaxRequest.abort();
		}
		catch(e)
		{
			// Do nothing special, just continue
			console.log('Uh,uh, exception !');
		}
	}
	aTruncatedLists[divId] = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?style=list',
	   { operation: 'ajax', filter: sSerializedFilter, extra_params: sExtraParams },
	     function(data)
	     {
			 aTruncatedLists[divId] = undefined;
			 if (data.length > 0)
			 {
				 $('#'+divId).html(data);
				 $('#'+divId+' .listResults').tableHover(); // hover tables
				 $('#'+divId+' .listResults').each( function()
					{
						var table = $(this);
						var id = $(this).parent();
						aTruncatedLists[divId] = undefined;
						var checkbox = (table.find('th:first :checkbox').length > 0);
						if (checkbox)
						{
							// There is a checkbox in the first column, don't make it sortable
							table.tablesorter( { headers: { 0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ).tablesorterPager({container: $("#pager")}); // sortable and zebra tables
						}
						else
						{
							// There is NO checkbox in the first column, all columns are considered sortable
							table.tablesorter( { widgets: ['myZebra', 'truncatedList']} ).tablesorterPager({container: $("#pager"), totalRows:97, filter: sSerializedFilter, extra_params: sExtraParams }); // sortable and zebra tables
						}
					});
				 $('#'+divId).unblock();
			 }
		}
	 );
}
/**
 * Truncate a previously expanded list !
 */
function TruncateList(divId, iLimit, sNewLabel, sLinkLabel)
{
	$('#'+divId).block();
	var iCount = 0;
	$('#'+divId+' table.listResults tr:gt('+iLimit+')').each( function(){
			$(this).remove();
	});
	$('#lbl_'+divId).html(sNewLabel);
	$('#'+divId+' table.listResults tr:last td').addClass('truncated');
	$('#'+divId+' table.listResults').addClass('truncated');
	$('#trc_'+divId).html(sLinkLabel);
	$('#'+divId+' .listResults').trigger("update"); //  Reset the cache
	$('#'+divId).unblock();
}
/**
 * Reload any block -- used for periodic auto-reload
 */
function ReloadBlock(divId, sStyle, sSerializedFilter, sExtraParams)
{
	// Check if the user is not editing the list properties right now
	var bDialogOpen = false;
	var oDataTable = $('#'+divId+' :itop-datatable');
	if (oDataTable.length > 0)
	{
		bDialogOpen = oDataTable.datatable('IsDialogOpen');
	}
	if (!bDialogOpen)
	{
		$('#'+divId).block();

		$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?style='+sStyle,
		   { operation: 'ajax', filter: sSerializedFilter, extra_params: sExtraParams },
		   function(data){
			 $('#'+divId).empty();
			 $('#'+divId).append(data);
			 $('#'+divId).removeClass('loading');
			}
		 );
	}
}

/**
 * Update the display and value of a file input widget when the user picks a new file
 */
function UpdateFileName(id, sNewFileName)
{
	var aPath = sNewFileName.split('\\');
	var sNewFileName = aPath[aPath.length-1];

	$('#'+id).val(sNewFileName);
	$('#'+id).trigger('validate');
	$('#name_'+id).text(sNewFileName);
	return true;
}
/**
 * Reload a search form for the specified class
 */
function ReloadSearchForm(divId, sClassName, sBaseClass, sContext)
{
    var oDiv = $('#ds_'+divId);
	oDiv.block();
	// deprecated in jQuery 1.8
	//var oFormEvents = $('#ds_'+divId+' form').data('events');
	var oForm = $('#ds_'+divId+' form');
	var oFormEvents = $._data(oForm[0], "events");

	// Save the submit handlers
    aSubmit = new Array();
	if ( (oFormEvents != null) && (oFormEvents.submit != undefined))
	{
		for(var index = 0; index < oFormEvents.submit.length; index++)
		{
			aSubmit [index ] = { data:oFormEvents.submit[index].data, namespace:oFormEvents.submit[index].namespace, handler:  oFormEvents.submit[index].handler};
		}
	}
	sAction =  $('#ds_'+divId+' form').attr('action');

	// Save the current values in the form
	var oMap = {};
	$('#ds_'+divId+" form :input[name!='']").each(function() {
		oMap[this.name] = this.value;
	});
	oMap.operation = 'search_form';
	oMap.className = sClassName;
	oMap.baseClass = sBaseClass;
	oMap.currentId = divId;
	oMap.action = sAction;

	$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?'+sContext, oMap,
	   function(data) {
		   oDiv.empty();
		   oDiv.append(data);
		   if (aSubmit.length > 0)
		   {
			    var oForm = $('#ds_'+divId+' form'); // Form was reloaded, recompute it
				for(var index = 0; index < aSubmit.length; index++)
				{
					// Restore the previously bound submit handlers
					if (aSubmit[index].data != undefined)
					{
						oForm.bind('submit.'+aSubmit[index].namespace, aSubmit[index].data, aSubmit[index].handler)
					}
					else
					{
						oForm.bind('submit.'+aSubmit[index].namespace, aSubmit[index].handler)
					}
				}
		   }
		   oDiv.unblock();
		   oDiv.parent().resize(); // Inform the parent that the form has just been (potentially) resized
	   }
	 );
}

/**
 * Stores - in a persistent way - user specific preferences
 * depends on a global variable oUserPreferences created/filled by the iTopWebPage
 * that acts as a local -write through- cache
 */
function SetUserPreference(sPreferenceCode, sPrefValue, bPersistent)
{
	sPreviousValue = undefined;
	try
	{
		sPreviousValue = oUserPreferences[sPreferenceCode];
	}
	catch(err)
	{
		sPreviousValue = undefined;
	}
    oUserPreferences[sPreferenceCode] = sPrefValue;
    if (bPersistent && (sPrefValue != sPreviousValue))
    {
    	ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php',
    						  { operation: 'set_pref', code: sPreferenceCode, value: sPrefValue} ); // Make it persistent
    }
}

/**
 * Get user specific preferences
 * depends on a global variable oUserPreferences created/filled by the iTopWebPage
 * that acts as a local -write through- cache
 */
function GetUserPreference(sPreferenceCode, sDefaultValue)
{
	var value = sDefaultValue;
	if ( oUserPreferences[sPreferenceCode] != undefined)
	{
		value = oUserPreferences[sPreferenceCode];
	}
	return value;
}

/**
 * Check/uncheck a whole list of checkboxes
 */
function CheckAll(sSelector, bValue)
{
	var value = bValue;
	$(sSelector).each( function() {
		if (this.checked != value)
		{
			this.checked = value;
			$(this).trigger('change');
		}
	});
}

/**
 * Toggle (enabled/disabled) the specified field of a form
 */
function ToogleField(value, field_id)
{
	if (value)
	{
		$('#'+field_id).removeAttr('disabled');
	}
	else
	{
		$('#'+field_id).attr('disabled', 'disabled');
	}
	$('#'+field_id).trigger('update');
	$('#'+field_id).trigger('validate');
}

/**
 * For the fields that cannot be visually disabled, they can be blocked
 * @return
 */
function BlockField(field_id, bBlocked)
{
	if (bBlocked)
	{
		$('#'+field_id).block({ message: ' ** disabled ** '});
	}
	else
	{
		$('#'+field_id).unblock();
	}
}

/**
 * Updates (enables/disables) a "duration" field
 */
function ToggleDurationField(field_id)
{
	// Toggle all the subfields that compose the "duration" input
	aSubFields = new Array('d', 'h', 'm', 's');

	if ($('#'+field_id).attr('disabled'))
	{
		for(var i=0; i<aSubFields.length; i++)
		{
			$('#'+field_id+'_'+aSubFields[i]).attr('disabled', 'disabled');
		}
	}
	else
	{
		for(var i=0; i<aSubFields.length; i++)
		{
			$('#'+field_id+'_'+aSubFields[i]).removeAttr('disabled');
		}
	}
}

/**
 * PropagateCheckBox
 */
function PropagateCheckBox(bCurrValue, aFieldsList, bCheck)
{
	if (bCurrValue == bCheck)
	{
		for(var i=0;i<aFieldsList.length;i++)
		{
			$('#enable_'+aFieldsList[i]).attr('checked', bCheck);
			ToogleField(bCheck, aFieldsList[i]);
		}
	}
}

function FixTableSorter(table)
{
	if ($('th.header', table).length == 0)
	{
		// Table is not sort-able, let's fix it
		var checkbox = (table.find('th:first :checkbox').length > 0);
		if (checkbox)
		{
			// There is a checkbox in the first column, don't make it sort-able
			table.tablesorter( { headers: { 0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ); // sort-able and zebra tables
		}
		else
		{
			// There is NO checkbox in the first column, all columns are considered sort-able
			table.tablesorter( { widgets: ['myZebra', 'truncatedList']} ); // sort-able and zebra tables
		}
	}
}

function DashletCreationDlg(sOQL)
{
	$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', {operation: 'dashlet_creation_dlg', oql: sOQL}, function(data){
		$('body').append(data);
	});
	return false;
}

function ShortcutListDlg(sOQL, sContext)
{
	$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?'+sContext, {operation: 'shortcut_list_dlg', oql: sOQL}, function(data){
		$('body').append(data);
	});
	return false;
}<|endoftext|>