/* Prototypes */
Math.randomInt = function(max) {
	return Math.round(Math.random() * max);
}
Number.prototype.inflect = function(w1, w2, w3) {
	var n = this + " ";
	var w = n.match(/([^1]|^)1 /) ? w1 : (n.match(/([^1]|^)[234] /) ? w2 : w3);
	return n + w;
}
Number.prototype.constrain = function(min, max) {
	return (this < min) ? min : ((this > max) ? max : this);
}
Number.prototype.toPercents = function(n) {
	return (this * 100).toFixed(n) + "%";
}
Array.prototype.last = function() {
	return this[this.length - 1];
}
Array.prototype.random = function() {
	return this[Math.randomInt(this.length - 1)];
}
Array.prototype.merge = function(arr) {
	if (typeof arr != "Array") arr = [arr];
	return $.merge(this, arr);
}
Array.prototype.filter = function(value) {
	return $.grep(this, function(item) {
		return item != value;
	});
}
String.prototype.contains = function(str) {
	return (this.indexOf(str) > -1);
}
String.prototype.trim = function() {
	return $.trim(this);
}
Function.prototype.use = function(self) {
    var method = this;
    return function() {
        return method.apply(self, arguments);
    }
}
function contentsOf(arr) {
	var hash = {};
	for (var i = arr.length; i--;) {
		hash[arr[i]] = true;
	}
	return hash;
}

/* JQuery extensions */
$.fn.extend({  
scrollToNode: function(node, margin) {
	var offset = margin || 0;
	var box = $(this), node = $(node);
	var nt = node.position().top;
	var mt = box.height() - node.height();
	if (nt < offset) {
		box.scrollTop(box.scrollTop() + nt - offset);
	} else if (nt > mt - offset) {
		box.scrollTop(box.scrollTop() + nt - mt + offset);
	}
	return this;
},
cssSprite: function(l, t) {
	var bpl = -l + (l ? "px" : "");
	var bpt = -t + (t ? "px" : "");
	$(this).css("background-position", bpl + " " + bpt);
	return this;
}
});

/* Ajax */
var ajaxRequests = {};
function ajaxFor(fname) {
	return ajaxRequests[fname] || setAjaxFor(fname);
}
function setAjaxFor(fname, process) {
	var request = new ajaxRequest(fname, process);
	return ajaxRequests[fname] = request;
}
function ajaxRequest(fname, process) {
	this.fname = fname;
	this.process = process;
}
ajaxRequest.prototype = {
send: function(data, options) {
	options = options || {};
	if (options.control) this.toggleControl(options.control, true);
	if (options.state) $(options.state).html("Соединение…").show();
	data = data || {};
	data.fname = this.fname;
	$.ajax({
		type: "POST",
		url: "/ajax/",
		dataType: "html",
		timeout: 10000,
		data: data,
		self: this,
		success: this.callSuccess,
		error: this.callError,
		options: options
	});
},
toggleControl: function(control, mode) {
	c = $(control);
	if (c.is("input,button")) {
		c.get(0).disabled = mode;
	} else {
		c.toggleClass("disabled", mode);
	}
},
callError: function(s) {
	var text = "Не удалось соединиться с сервером";
	this.self.processError(text, this.options);
},
callSuccess: function(s) {
	var self = this.self, options = this.options;
	if (s && s.indexOf("ERROR") == 0) {
		self.processError(s.substr(6), options);
	} else {
		if (options.control) self.toggleControl(options.control, false);
		if (options.state) $(options.state).html("").hide();
		if (self.process) self.process(s, options);
	}
},
processError: function(s, options) {
	if (options.control) this.toggleControl(options.control, false);
	if (options.state) $(options.state).html("").hide();
	alert(s);
}
};

/* Cookies */
var Cookie = function(name, value, date) {
	if (arguments.length > 1) {
		var expires = value != undefined ? (date ? date.toGMTString() : "") : "Thu, 01-Jan-1970 00:00:01 GMT";
		if (expires) expires = "expires=" + expires + ";";
		document.cookie = name + "=" + escape(value) + ";" + expires + "path=/";
		return value;
	} else {
		var pattern = new RegExp("(?:^" + name + "|; ?" + name + ")=([^;]*)", "g");
		var result = pattern.exec(document.cookie);
		return (result) ? unescape(result[1]) : null;
	}
}

/* Browsers */
var msie = navigator.appName.contains("Microsoft");
if (msie) {
	try {document.execCommand("BackgroundImageCache", false, true);} catch(e) {}
}
if (navigator.platform.contains("Mac") && navigator.vendor.contains("Apple")) {
	var de = document.documentElement;
	de.className = [de.className, "macos-safari"].join(" ");
}
