(function( window, undefined ) {

var jWps = function(selector, context) {
		return new jWps.fn.init(selector, context);
	},
	
	_jWps = window.jWps,
	
	_$ = window.$,
	
	document = window.document,
	
	userAgent = navigator.userAgent,
	
	toString = Object.prototype.toString,
	hasOwnProperty = Object.prototype.hasOwnProperty,
	push = Array.prototype.push,
	slice = Array.prototype.slice,
	indexOf = Array.prototype.indexOf;
	
jWps.fn = jWps.prototype = {
	init: function(selector, context){
		
		if(selector == undefined){
			return;
		}
		// Если selector DOMElement
		if(selector.nodeType || selector === window){
			this[0] = selector;
			this.length = 1;
			return this;
		}
		
		// Если требуется вернуть элемент body
		if(selector === "body" && !context){
			this.context = document;
			this[0] = document.body;
			this.selector = "body";
			this.length = 1;
			return this;
		}
		
		if(typeof selector === 'string'){
			selector = jWps.find(selector, context);
		}
		selector = jWps.merge(this, selector);
		return selector;
	},
	
	selector: "",
	
	jWps: "0.0.1",
	
	length: 0,
	
	find: function(selector){
		var i = 0, oldthis = [], length = this.length;
		jWps.merge(oldthis, this);
		
		for(var n = 0; n < length; n++){
			delete this[n];
		}
		this.length = 0;
		for(; i < length; i++){
			selector = jWps.find(selector, oldthis[i]);
			jWps.merge(this, selector);
		}
		
		return this;
	}
}

jWps.fn.init.prototype = jWps.fn;
	
jWps.extend = jWps.fn.extend = function(){
	// copy ссылка на текущий объект
	var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
	
	if(typeof target === "boolean"){
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i=2;
	}
	
	if ( typeof target !== "object" && !jWps.isFunction(target) ) {
		target = {};
	}
	
	if(length === i){
		target = this;
		--i;
	}
	
	for( ; i<length; i++){
		// Только не null объекты
		if((options = arguments[i]) != null){
			// Расширяем базовый объект
			for(var name in options){
				src = target[ name ];
				copy = options[ name ];
				// Предотвращаем бесконечный цикл
				if(target === copy){
					continue;
				}
				/*
				if (deep && copy && typeof copy === "object" && !copy.nodeType){
					target[name] = _jWps.extend(deep, src || (copy.length != null ? [] : {}), copy);
				}else if(copy !== undefined){ 
					target[name]=copy;
				}*/
				
				// Recurse if we're merging object literal values or arrays
				if(deep && copy && (jWps.isPlainObject(copy) || jWps.isArray(copy))){
					var clone = src && (jWps.isPlainObject(src) || jWps.isArray(src)) ? src
						: jWps.isArray(copy) ? [] : {};

					// Never move original objects, clone them
					target[name] = jWps.extend(deep, clone, copy);

				// Не копировать объект, если он undefined
				}else if(copy !== undefined) {
					target[name] = copy;
				}
			}
		}
	}
	// Возврат модифицированного объекта
	return target;
};

// Внутренние методы
jWps.extend({
	merge: function(first, second){
		var i = first.length, j = 0, l;
		
		if(i == undefined){
			i = 0;
		}
		
		if(typeof second.length === "number"){
			for(l = second.length; j < l; j++){
				first[i++] = second[j];
			}
		}else{
			while(second[j] !== undefined){
				first[i++] = second[j++];
			}
		}
		
		first.length = i;

		return first;
	},
	
	isFunction: function(obj) {
		return toString.call(obj) === "[object Function]";
	},
	
	isArray: function(obj) {
		return toString.call(obj) === "[object Array]";
	},
	
	isInt: function(x){
		var y = parseInt(num); 
		if (isNaN(y)) return false; 
		return (x == y && x.toString() == y.toString());
	},
	isPlainObject: function(obj) {
		// Must be an Object.
		// Because of IE, we also have to check the presence of the constructor property.
		// Make sure that DOM nodes and window objects don't pass through, as well
		if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) {
			return false;
		}
		
		// Not own constructor property must be Object
		if ( obj.constructor
			&& !hasOwnProperty.call(obj, "constructor")
			&& !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) {
			return false;
		}
		
		// Own properties are enumerated firstly, so to speed up,
		// if last one is own, then all properties are own.
	
		var key;
		for ( key in obj ) {}
		
		return key === undefined || hasOwnProperty.call( obj, key );
	},
	
	each: function(obj, callback){
		var name, i = 0, length = obj.length;
		
		if(length === undefined){
			for(name in obj){
				if(callback.call(obj[name], name, obj[name]) === false)
					break;
			}
		}else
			for(var value = obj[0];
				i < length && callback.call( value, i, value ) !== false; value = obj[++i] ){}
		return obj;
	},
	
	clone: function clone(obj) {
		var newObj = {};
		
		for(var i in obj) {
			newObj[i] = obj[i];
		}
		
		return newObj;
	},
	
	uaMatch: function(ua){
		ua = ua.toLowerCase();

		var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
			/(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) ||
			/(msie) ([\w.]+)/.exec( ua ) ||
			!/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) ||
		  	[];

		return { browser: match[1] || "", version: match[2] || "0" };
	},

	browser: {}
});

var browserMatch = jWps.uaMatch(userAgent);
if(browserMatch.browser){
	jWps.browser[browserMatch.browser] = true;
	jWps.browser.version = browserMatch.version;
}

// Deprecated, use jWps.browser.webkit instead
if(jWps.browser.webkit){
	jWps.browser.safari = true;
}

// Внешние методы
jWps.fn.extend({
	
});

/**
* jWps включает механизм поиска DOM объектов,
* за счет использования быстрых конструкций поиска,
* доступных для конкретного браузера
*/
jWps.extend({
	find: function(selector, context){
		context = context || document;
		var ret = [];
	
		if(/^([\.|#])?([\w-]+)$/.test(selector)){
			switch(selector.charAt(0)){
			case '#':
				ret = jWps.ID(selector, context);
				break;
			case '.':
				ret = jWps.CLASS(selector, context);
				break;
			default:
				ret = jWps.TAG(selector, context);
				break;
			}
		}else{
			if(/\[name=['"]*((?:[\w\u00c0-\uFFFF\u005B\u005D-]|\\.)+)['"]*\]/.test(selector)){
				selector = /\[name=['"]*((?:[\w\u00c0-\uFFFF\u005B\u005D-]|\\.)+)['"]*\]/.exec(selector);
				ret = jWps.NAME(selector, context);
			}
			// Если пользователь ввел не CSS1 селекторы
		}
		return ret;
	}
});

jWps.extend({
	ID: function(selector, context){
		selector = selector.slice(1);
		var ret = document.getElementById(selector);
		return ret ? [ret] : [];
	},
	CLASS: function(selector, context){
		selector = selector.slice(1);
		var nodes = context.getElementsByTagName('*'), i=0, node, ret=[];
		
		while (node = nodes[i++]) {
			if(node.className == selector){
				ret.push(node);
			}
		}
		return ret;
	},
	TAG: function(selector, context){
		return context.getElementsByTagName(selector);
	},
	NAME: function(selector, context){
		selector = selector.slice(1);
		var nodes = context.getElementsByTagName('*'), i=0, node, ret=[];
		
		while (node = nodes[i++]) {
			if(node.getAttribute("name") == selector){
				ret.push(node);
			}
		}
		return ret;
	}
});

// Если браузер поддерживает getElementsByClassName, то используем
// для поиска класса
if(document.getElementsByClassName){
	jWps.CLASS = function(selector, context){
		selector = selector.slice(1);
		return context.getElementsByClassName(selector);
	}
};

// Если браузер поддерживает querySelectorAll, используем его для поиска класса
// В сафари браузерах не использовать querySelectorAll, работает медленнее
if(document.querySelectorAll && !jWps.browser.safari){
	jWps.CLASS = function(selector, context){
		return context.querySelectorAll(selector);
	}
};

// Расширение: Кэширование
function now(){ return (new Date).getTime(); }

var expando = "jWps" + now(), uuid = 0, windowData = {};

jWps.extend({
	cache: {},
	
	expando:expando,

	// The following elements throw uncatchable exceptions if you
	// attempt to add expando properties to them.
	noData: {
		"embed": true,
		"object": true,
		"applet": true
	},

	data: function(elem, name, data){
		if(elem.nodeName && jWps.noData[elem.nodeName.toLowerCase()]){
			return;
		}

		elem = elem == window ? windowData : elem;

		var id = elem[expando], cache = jWps.cache, thisCache;

		if (!id && typeof name === "string" && data === undefined){
			return null;
		}

		// Compute a unique ID for the element
		if(!id){ 
			id = ++uuid;
		}

		// Avoid generating a new cache unless none exists and we
		// want to manipulate it.
		if(typeof name === "object"){
			elem[expando] = id;
			thisCache = cache[id] = jWps.extend(true, {}, name);

		}else if(!cache[id]){
			elem[expando] = id;
			cache[id] = {};
		}

		thisCache = cache[id];

		// Prevent overriding the named cache with undefined values
		if (data !== undefined) {
			thisCache[name] = data;
		}

		return typeof name === "string" ? thisCache[name] : thisCache;
	},

	removeData: function(elem, name) {
		if(elem.nodeName && jWps.noData[elem.nodeName.toLowerCase()]){
			return;
		}

		elem = elem == window ? windowData : elem;

		var id = elem[expando], cache = jWps.cache, thisCache = cache[id];

		// If we want to remove a specific section of the element's data
		if(name){
			if(thisCache){
				// Remove the section of cache data
				delete thisCache[name];

				// If we've removed all the data, remove the element's cache
				if(jWps.isEmptyObject(thisCache)){
					jWps.removeData(elem);
				}
			}

		// Otherwise, we want to remove all of the element's data
		}else{
			if(jWps.support.deleteExpando){
				delete elem[jWps.expando];

			}else if(elem.removeAttribute){
				elem.removeAttribute(jWps.expando);
			}

			// Completely remove the data cache
			delete cache[id];
		}
	}
});

// Расширение: Работа с событиями
jWps.event = {
	add: function(elem, types, handler){
		if(elem.nodeType === 3 || elem.nodeType === 8){
			return;
		}
		
		// For whatever reason, IE has trouble passing the window object
		// around, causing it to be cloned in the process
		if(elem.setInterval && (elem !== window && !elem.frameElement)){
			elem = window;
		}
		
		var data = jWps.data;
		
		var events = data(elem, "events") || data(elem, "events", []),
      handle = data(elem, "handle") || data(elem, "handle", function(){
        jWps.event.handle.apply(arguments.callee.elem, arguments);
      });
			
		// Add elem as a property of the handle function
		// This is to prevent a memory leak with non-native
		// event in IE.
		handle.elem = elem;
		
		jWps.each(types.split(/\s+/), function(index, type) {
			var handlers = events[type];
			if (!handlers) {
				handlers = events[type] = new Array();
				
				if (elem.addEventListener)
					elem.addEventListener(type, handle, false);
				else if (elem.attachEvent)
					elem.attachEvent('on' + type, handle);
			}
			handlers.push(handler);
		});

		elem = null;
	},
	
	remove: function(elem, type, handler){
		
		if(elem.nodeType === 3 || elem.nodeType === 8){
			return;
		}
		
		var data = jWps.data;
		
		var events = data(elem, "events");
		
		if (events) {
			if (typeof(type) == 'string' && jWps.isArray(events[type])) {
				if (jWps.isFunction(handler)) {
					for (var i = 0; i < events[type].length; i++) {
						if (events[type][i] == handler) {
							delete events[type][i];
							break;
						}
					}
				} else {
					for (var i = 0; i < events[type].length; i++) {
						delete events[type][i];
					}
				}
			} else {
				for (var i in events) {
					jWps.event.remove(elem, i);
				}
				return;
			}
			for (var ret in events[type]) break;
			if (!ret && data(elem, "handle")) {

				if (elem.removeEventListener)
					elem.removeEventListener(type, data(elem, "handle"), false);
				else if (elem.detachEvent)
					elem.detachEvent("on" + type, data(elem, "handle"));
			}
			ret = null;
			delete events[type];
		}
	},
	
	cancel: function(event){
		var e = event.originalEvent || event;
		if (e.preventDefault)
				e.preventDefault();
		if (e.stopPropagation)
				e.stopPropagation();
		e.cancelBubble = true;
		e.returnValue = false;
		return false;
	},
	
	handle: function(event){
		event = event || window.event;
		
		var data = jWps.data;
		
		var originalEvent = event;
		event = jWps.clone(originalEvent);
		event.originalEvent = originalEvent;

		if (!event.target)
			event.target = event.srcElement || document;

		// check if target is a textnode (safari)
		if ( event.target.nodeType == 3 )
			event.target = event.target.parentNode;

		if (!event.relatedTarget && event.fromElement)
			event.relatedTarget = event.fromElement == event.target

		if ( event.pageX == null && event.clientX != null ) {
			var doc = document.documentElement, body = document.body;
			event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
			event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
		}

		if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
			event.which = event.charCode || event.keyCode;

		// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
		if ( !event.metaKey && event.ctrlKey )
			event.metaKey = event.ctrlKey;

		// Add which for click: 1 == left; 2 == middle; 3 == right
		// Note: button is not normalized, so don't use it
		if ( !event.which && event.button )
			event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));

		var handlers = data(this, "events");
		if (!handlers || typeof(event.type) != 'string' || !handlers[event.type] || !handlers[event.type].length) {
			return;
		}
		try {
			//fixed: handlers[event.type] = undefined
			for (var i = 0; i < (handlers[event.type] || []).length; i++) {
				if (event.type == 'mouseover' || event.type == 'mouseout') {
					var parent = event.relatedElement;
					// Traverse up the tree
					while ( parent && parent != this )
						try { parent = parent.parentNode; }
						catch(e) { parent = this; }
					if (parent == this) {
						continue
					}
				}
				var ret = handlers[event.type][i].apply(this, arguments);
				if (ret === false) {
					jWps.event.cancel(event);
				}
			}
		} catch (e) {
			alert(event.target.id+"."+event.type+": "+e.message);
		}
	}
	
};

jWps.each(["bind"], function(i, name){
	jWps.fn[name] = function(type, fn){
		var length = this.length;
		
		for(var i = 0; i < length; i++){		
			jWps.event.add(this[i], type, fn);
		}
		
		return this;
	}
});

jWps.each(["unbind"], function(i, name){
	jWps.fn[name] = function(type, fn){
		var length = this.length;
		
		for(var i = 0; i < length; i++){
			jWps.event.remove(this[i], type, fn);
		}
		
		return this;
	}
});

jWps.fn.extend({
	
	'hover': function(fnOver, fnOut){
		if(!this[0]) return;
		for(var i=0; i<this.length; i++){
			jWps.event.add(this[i], 'mouseover', fnOver);
			jWps.event.add(this[i], 'mouseout', fnOut || fnOver);
		}
		return this;
	}
	
});
// Расширение: Анимация
jWps.fn.extend({
	'speeds':{
		slow: 600,
		fast: 200,
		_default: 400
	},
	
	'animate': function(param, speed){
		if(param.colorFrom && param.colorTo){
			if(/(\d+), (\d+), (\d+)/.test(param.colorFrom)){ // rgb(RRR, GGG, BBB)
				color = /(\d+), (\d+), (\d+)/.exec(param.colorFrom);
				param.colorFrom = jWps.dec2hex(parseInt(color[1])) + jWps.dec2hex(parseInt(color[2])) + jWps.dec2hex(parseInt(color[3]));
			}else if(/^#/.test(param.colorFrom)){ // #RRGGBB
				param.colorFrom = param.colorFrom.slice(1);
			}
			jWps.fn.animateTo(this[0],function(elem, progress){
				elem.style.color = '#' + jWps.getColor(param.colorFrom, param.colorTo, 100 * progress);
				
			}, jWps.fn.speeds[speed] || speed);
		}
	},
	
	'animateTo': function(elem, fn, speed){
		var duration = speed || speeds._default;
		var start = new Date().getTime();
		
		setTimeout(function(){
			var now = (new Date().getTime()) - start;
			var progress = now / duration;
			
			fn(elem, progress);
			
			if(progress < 1) elem.timeid = setTimeout(arguments.callee,10);
		}, 10);
	},
	
	'stop': function(){
		if(this[0].timeid){
			clearTimeout(this[0].timeid);
		}
		return this;
	}
});
// Расширение: Работа с DOM
jWps.fn.extend({
	text: function(text){
		if(typeof text === "string" && text !== undefined){
			this.append(document.createTextNode(text))
		}
		return this;
	},
	
	append: function(elem){
		if(this[0].nodeType === 1){
			this[0].appendChild(elem);
		}
		return this;
	},
	
	prepend: function(elem, before){
		if(this[0].nodeType === 1){
			this[0].insertBefore(elem, (before) ? before : this[0].firstChild);
		}
	},
	
	before: function(elem){
		if(elem.nodeType === 1){
			elem.parentNode.insertBefore(this[0], elem);
		}
		return this;
	},
	
	after: function(elem){
		if(elem.nodeType === 1){
			elem.parentNode.insertBefore(this[0], elem.nextSibling);
		}
		return this;
	},
	
	parent: function(){
		if(this[0].nodeType === 1){
			this[0] = (this[0].parentElement) ? this[0].parentElement : this[0].parentNode;
		}
		return this;
	},
	
	next: function(){
		if(this[0].nodeType === 1){
			var elem = this[0];
			while ( (elem = elem.nextSibling) && elem.nodeType !== 1 ) {}
			this[0] = elem;
		}
		return this;
	},
	
	prev: function(){
		if(this[0].nodeType === 1){
			var elem = this[0];
			while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
			this[0] = elem;
		}
		return this;
	},
	
	html: function(html){
		if(html == undefined) html = '';
		for(var i=0; i<this.length; i++){
			this[i].innerHTML = html;
		}
		return this;
	},
	
	remove: function(){
		var i=0, elem, l = this.length;
		for(; i < l; i++){
			elem = this[i];
			if(elem.parentNode){
				elem.parentNode.removeChild(elem);
			}
		}
		return this;
	},
	
	getPosition: function(){
		if(this[0] == undefined) return;
		
		var left = 0, top = 0, obj = this[0];
		
		do{
				left += obj.offsetLeft;
				top += obj.offsetTop;
		}while(obj = obj.offsetParent);
		
		return {x:left, y:top};
	}
});

// Расширение: Работа с CSS
jWps.fn.extend({
	hasClass: function(selector){
		for(var i=0; i<this.length; i++){
			if((new RegExp('(\\s|^)' + selector + '(\\s|$)')).test(this[i].className)){
				return true;
			}
		}
		return false;
	},
	
	addClass: function(selector){
		if(!this[0]) return;
		
		for(var i=0; i<this.length; i++){
			if(!this.hasClass(selector)){
				this[i].className = (this[i].className ? this[i].className + ' ' : '') + selector;
			}
		}
		return this;
	},
	
	removeClass:function(selector){
		if(!this[0]) return;
		
		for(var i=0; i<this.length; i++){
			if(this.hasClass(selector)){
				this[i].className = this[i].className.replace((new RegExp('(\\s|^)' + selector + '(\\s|$)')), '');
			}
		}
		return this;
	},
	
	toggleClass: function(first, second){
		if(this.hasClass(first) == true){
			this.removeClass(first).addClass(second);
		}else{
			this.removeClass(second).addClass(first);
		}
		return this;
	},
	
	setStyle: function(name, value){
		if(typeof this[0] != "object") return;

		this[0].style[name] = typeof(value) == 'number' && !(/z-?index|font-?weight|opacity|zoom|line-?height/i).test(name) ? value + 'px': value;
	},
	
	hide: function(){
		if(!this[0]) return;
		
		for(var i=0; i<this.length; i++){
			this[i].style.display = 'none';
		}
		
		return this;
	},
	
	show: function(){
		if(!this[0]) return;
		
		for(var i=0; i<this.length; i++){
			this[i].style.display = 'block';
		}
		
		return this;
	},
	toggle: function(){
		if(!this[0]) return;
		
		for(var i=0; i<this.length; i++){
			(this[i].style.display == 'block') ? this[i].style.display = 'none' : this[i].style.display = 'block';
		}
		
		return this;
	},
	setOpacity: function(value){
		if(!this[0]) return;
		if(value > 1) value = 1; 
		if(value < 0) value = 0;
		
		for(var i=0; i<this.length; i++){
			this[0].style.opacity = value;
			this[0].style.opacity =  'alpha(opacity=' + value * 100 + ')';
			this[0].style.opacity =  '-moz-opacity:' + value;
			this[0].style.opacity =  'khtml-opacity:' + value;
		}
	},
	setSize: function(w, h, callback, time){
		if(!this[0]) return;
		
		var duration = 1000; 
		if(time > 0) duration = time;
		
		var start = new Date().getTime(), el = this[0];
		var old_w = el.clientWidth, old_h = el.clientHeight;
		setTimeout(function(){
			var now = (new Date().getTime()) - start;
			var progress = now / duration;
			var width = (w - old_w) * progress + old_w;
			var height = (h - old_h) * progress + old_h;
			el.style.width = width + 'px';
			el.style.height = height + 'px';
			
			if(progress < 1) setTimeout(arguments.callee, 10);
			else{
				if(width < w || width > w) el.style.width = w + 'px';
				if(height < h || height > h) el.style.height = h + 'px';
				if(jWps.isFunction(callback)) callback();
			}
		}, 10);
	}
});

// Расширение: Различные функции
jWps.extend({
	replace: function(search, replace, obj){
		return obj.split(search).join(replace);
	},
	
	clientWidth: function(){
		return document.documentElement.clientWidth == 0 ? document.body.clientWidth : document.documentElement.clientWidth;
	},
	
	clientHeight: function(){
		return document.documentElement.clientHeight == 0 ? document.body.clientHeight : document.documentElement.clientHeight;
	},
	
	documentWidth: function(){
		return Math.max(
			document.documentElement["clientWidth"],
			document.body["scrollWidth"], document.documentElement["scrollWidth"],
			document.body["offsetWidth"], document.documentElement["offsetWidth"]
		);
	},
	
	documentHeight: function(){
		return Math.max(
			document.documentElement["clientHeight"],
			document.body["scrollHeight"], document.documentElement["scrollHeight"],
			document.body["offsetHeight"], document.documentElement["offsetHeight"]
		);
	},
	
	// Полный вариант кода: http://forum.dklab.ru/js/advises/DocumentCreateelementext.html
	create: function(tag, p){
		var i, k, elem = document.createElement(tag);
		
		if(!elem) return false;
		
		for(i in p){
			if(p.constructor.prototype[i] && p[i] === p.constructor.prototype[i]) continue;
			
			switch(i){
				case "id": elem.id = p[i]; break; 
				case "class": elem.setAttribute('class', p[i]); elem.setAttribute('className', p[i]); break;
				case "style": for(k in p[i]) { if(p[i].constructor.prototype[k] && p[i][k] === p[i].constructor.prototype[k]) continue; elem.style[k] = p[i][k]; } break;
				case "param": for(k in p[i]) { if(p[i].constructor.prototype[k] && p[i][k] === p[i].constructor.prototype[k]) continue; try {el[k] = p[i][k]} catch(e){} } break;
			}
		}
		
		return elem;
	},
	

	htmlspecialchars: function(str){
		str = str.toString();
		
		str = jWps.replace('&', '&amp;', str);
    str = jWps.replace('<', '&lt;', str);
    str = jWps.replace('>', '&gt;', str);
    str = jWps.replace('"', '&quot;', str);
		
		return str;
	},
	htmlspecialchars_decode: function(str){
		if(!str) return '';
		str = str.toString();

		str = jWps.replace('&amp;',  '&', str);
    str = jWps.replace('&lt;',   '<', str);
    str = jWps.replace('&gt;',   '>', str);
    str = jWps.replace('&quot;', '"', str);
		
		return str;
	},
	
	openURL: function(href, target){
		if(href !== undefined){
			if(target == 'blank'){
				window.open(href);
			}else{
				location.href = href;
			}
		}
	},
	
	declension: function(count, expressions){
		var result;
		if(expressions.length < 3) expressions[2] = expressions[1];
		//count = (int)count;
		count = count % 100;
		
		if(count >= 5 && count <= 20){
			result = expressions[2];
		}else{
			count = count % 10;
			if(count == 1){
				result = expressions[0];
			}else if(count >= 2 && count <= 4){
				result = expressions[1];
			}else{
				result = expressions[2];
			}
		}
		return result;
	},
	
	bindReady: function(handler){
		var called = false;
		function ready(){
        if (called) return;
        called = true;
        handler();
    }
		if(document.addEventListener){
			document.addEventListener( "DOMContentLoaded", function(){ ready();	}, false);
    }else if(document.attachEvent){
			if(document.documentElement.doScroll && window == window.top){
				function tryScroll(){
					if(called) return;
					if(!document.body) return;
						try{
							document.documentElement.doScroll("left");
							ready();
						}catch(e){
							setTimeout(tryScroll, 0);
						}
				}
				tryScroll();
			}
			document.attachEvent("onreadystatechange", function(){ if(document.readyState === "complete"){ ready(); } })
    }
    if(window.addEventListener)
			window.addEventListener('load', ready, false);
    else if (window.attachEvent)
			window.attachEvent('onload', ready);
	},
	
	readyList: [],
	
	onDomReady: function(handler){
		if(!jWps.readyList.length){
			jWps.bindReady(function() {
				for(var i=0; i<jWps.readyList.length; i++) {
					jWps.readyList[i]();
				}
			});
    }
    jWps.readyList.push(handler);
	},
	
	addTag: function(obj, str1, str2){
		obj.focus();
		// Для IE
		if(document.selection){
			var s = document.selection.createRange();
			if(s.text){
				s.text = str1 + s.text + str2;
			}else{
				obj.value = obj.value + str1 + str2;
			}
			return true;
		}
		// Opera, FireFox
		else if(typeof(obj.selectionStart) == "number"){
			if(obj.selectionStart != obj.selectionEnd){
				var start = obj.selectionStart;
				var end = obj.selectionEnd;
				s = obj.value.substr(start,end-start);
				obj.value = obj.value.substr(0, start) + str1 + s + str2 + obj.value.substr(end);
			}else{
				obj.value = obj.value + str1 + str2;
			}
			return true;
		}
		return false;
	},
	
	setCookie: function(name, value){
		var valueEscaped = escape(value); 
		var expiresDate = new Date(); 
		expiresDate.setTime(expiresDate.getTime() + 365 * 24 * 60 * 60 * 1000); // срок - 1 год
		var expires = expiresDate.toGMTString(); 
		var newCookie = name + "=" + valueEscaped + "; path=/; expires=" + expires; 
		if(valueEscaped.length <= 4000) document.cookie = newCookie + ";"; 
	},
	
	getCookie: function(name){
		var prefix = name + "="; 
		var cookieStartIndex = document.cookie.indexOf(prefix); 
		if (cookieStartIndex == -1) return null; 
		var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length); 
		if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length; 
		return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex)); 
	},
	
	tpl_compare: function(template, params){
		for(var key in params){
			var value = params[key];
			template = jWps.replace('[#'+key+']',value,template);
		}
		return template;
	},
	
	'dec2hex': function(dec){ return dec.toString(16); },
	
	'hex2dec': function(hex){ return parseInt(hex, 16); },
	
	'getColor': function(start, end, percent){
		var 
			r1 = jWps.hex2dec(start.slice(0,2)),
			g1 = jWps.hex2dec(start.slice(2,4)),
			b1 = jWps.hex2dec(start.slice(4,6)),
			
			r2 = jWps.hex2dec(end.slice(0,2)),
			g2 = jWps.hex2dec(end.slice(2,4)),
			b2 = jWps.hex2dec(end.slice(4,6));
		
		percent = percent / 100;
		
		r = Math.floor(r1 + (percent * (r2 - r1)) + .5);
		g = Math.floor(g1 + (percent * (g2 - g1)) + .5);
		b = Math.floor(b1 + (percent * (b2 - b1)) + .5);
		return (jWps.dec2hex(r) + jWps.dec2hex(g) + jWps.dec2hex(b));
	},
	
	'addFavorite': function(elem){
		var 
			title = document.title,
			url = document.location;

		try{ // Internet Explorer
			window.external.AddFavorite(url, title);
		}catch(e){
			try{ // Mozilla
				window.sidebar.addPanel(title, url, "");
			}catch(e){
				if(typeof(opera) == "object"){ // Opera
					elem.rel = "sidebar";
					elem.title = title;
					elem.url = url;
					return true;
				}else{ // Unknown
					alert('Press "Ctrl + D" to add page in favorite.');
				}
			}
		}
		return false;
	},
	
	'getGMT': function(){
		var gmt = /(GMT|UTC)((\+|\-)?[0-9]+)/.exec(String(new Date()))[2];
		return ((gmt.slice(0,1)=='-')?'-':'') + ((gmt.slice(3,5) == '00') ? ((gmt.slice(1,2) == '0') ? gmt.slice(2,3) : gmt.slice(1,3)) : 
			((parseInt((gmt.slice(1,2) == 0) ? gmt.slice(2,3) : gmt.slice(1,3)) * 60) + parseInt(gmt.slice(3,5))));
	},
	
	'changeRegion': function(theme){
		jWps.setCookie('Theme', theme);
		var ajax = new Ajax();
		ajax.post({'module':'region', 'theme':theme}, function(){
			location.reload();
		});
	},
	
	'trim': function(text){
		return (text || "").replace(/^\s+|\s+$/g, "");
	}
});

window.jWps = jWps;
	
})(window);

window.onerror = function(message, url, line){
	var ajax = new newAjax();
	ajax.post({'module':'jserror','message':message,'url':url,'line':line});
	return true;
}

/*********************
* Start Ajax class
**/

var newAjax = Ajax = function(){ // Создание класса Ajax
  var _t = this,
		xhr = null,
		url = "ajax.php",
		global = true,
		dataType = "json",
		contentType = "application/x-www-form-urlencoded",
		processData = true,
		async = true
		strquery = '',
		savequery = {},
		callback = null;
	var cache = {'query':[],'callback':[]}, blocked = 0;
	
	this.onStart = function(){};
	this.onError = function(){};
	this.onComplete = function(){};
	
	this.setup = function(s){
		if(s.url !== undefined){
			url = s.url;
		}
		if(s.dataType !== undefined){
			dataType = s.dataType;
		}
		if(typeof s.onStart === 'function'){
			this.onStart = s.onStart;
		}
		if(typeof s.onError === 'function'){
			this.onError = s.onError;
		}
		if(typeof s.onComplete === 'function'){
			this.onComplete = s.onComplete;
		}
	}
	
	try {
    xhr = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        xhr = null;
      }
    }
  }
	
	var readystatechange = function(){
		if(xhr.readyState == 4){
			if(xhr.status == 200){
				var data = (dataType == 'json') ? json(xhr.responseText) : xhr.responseXML;
				var text = xhr.responseText;
				if(callback){ callback(data, text, savequery); readyCache(); }
				else if(_t.onComplete){_t.onComplete(data, text, savequery); readyCache(); }
			}else{
				if(_t.onError){_t.onError(strquery, savequery); readyCache(); }
			}
		}
  }
	
	function readyCache(){
		blocked = 0;
		if(cache['query'].length > 0){
			cache['query'].reverse(); cache['callback'].reverse();
			_t.post(cache['query'].pop(), cache['callback'].pop());
			cache['query'].reverse(); cache['callback'].reverse();
		}
	}
	
	this.post = function(query, fn, nocache){
		if(nocache) blocked = 0;
		if(blocked == 0){
			if(jWps.isFunction(fn)){
				callback = fn;
			}else if(typeof fn === 'object'){
				if(typeof fn.onComplete === "function"){
					callback = fn.onComplete;
				}else callback = null;
			}else callback = null;
			blocked = 1;
			
			if(typeof fn === 'object'){
				if(typeof fn.onStart === "function") fn.onStart(query);
			}else if(_t.onStart){_t.onStart(query);}
			
			savequery = query;
			strquery = query2url(query);
			xhr.open("POST", url, async);
			xhr.onreadystatechange = readystatechange;
			xhr.setRequestHeader("Content-Type", contentType);
			xhr.send(strquery);
		}else{
			cache['query'][cache['query'].length] = query;
			cache['callback'][cache['callback'].length] = fn;
		}
  };
	
	function json(text){
		var et;
		try{
			et = eval('('+ text +')');
		}catch (failed) {
			//alert(text);
		}
		return et;
	}
	
	function query2url(qa){ 
		var query = [], q, i =0;
		
		for (var key in qa) {
			if(qa[key] === undefined || qa[key] === null || typeof(qa[key]) == 'function') continue;
			if(jWps.isArray(qa[key])){
				for(var i = 0; i < qa[key].length; ++i) {
					if(qa[key][i] === undefined || qa[key][i] === null || typeof(qa[key][i]) == 'function') continue;
					query.push(escapeurl(key) + '[]=' + escapeurl(qa[key][i]));
				}
			}else{
				query.push(escapeurl(key) + '=' + escapeurl(qa[key]));
			}
		}
		query.push(escapeurl('dataType') + '=' + escapeurl(dataType));
		return query.join('&');
	}
	
	// Инициализируем таблицу перевода
	var trans = [];
	for (var i = 0x410; i <= 0x44F; i++)
		trans[i] = i - 0x350; // А-Яа-я
	trans[0x401] = 0xA8;    // Ё
	trans[0x451] = 0xB8;    // ё
	trans[0x457] = 0xBF;    // ї
	trans[0x407] = 0xAF;    // Ї
	trans[0x456] = 0xB3;    // і
	trans[0x406] = 0xB2;    // І
	trans[0x404] = 0xBA;    // є
	trans[0x454] = 0xAA;    // Є
	
	// Сохраняем стандартную функцию escape() для работы с русскими символами
	var escapeOrig = window.escape;

	// Переопределяем функцию escape()
	function escapeurl(str){
		if(jWps.isInt) str = String(str);
		str = str.replace(/\+/g,'%2B',str);
		var ret = [];
		// Составляем массив кодов символов, попутно переводим кириллицу
		for (var i = 0; i < str.length; i++){
			var n = str.charCodeAt(i);
			if (typeof trans[n] != 'undefined')
				n = trans[n];
			if (n <= 0xFF)
				ret.push(n);
		}
		return escapeOrig(String.fromCharCode.apply(null, ret));
	}
}
/**
* End Ajax class
*********************/

var input = {
	'placeholder': function(input, color){
		if (!input) return null;
		
		// Do nothing if placeholder supported by the browser (Webkit, Firefox 3.7)
		if(input.placeholder && 'placeholder' in document.createElement(input.tagName)) return null;
		
		var default_color = input.style.color;
		color = color || default_color;
		var placeholder = input.getAttribute('placeholder');
		
		if(input.value === '' || input.value == placeholder){
			input.value = placeholder;
			input.style.color = color;
			input.setAttribute('data-placeholder-visible', 'true');
		}
		
		jWps.event.add(input, 'focus', function(){
			input.style.color = default_color;
			if(input.getAttribute('data-placeholder-visible')){
				input.setAttribute('data-placeholder-visible', '');
				input.value = '';
			}
		});
		
		jWps.event.add(input, 'blur', function(){
			if(input.value === ''){
				input.setAttribute('data-placeholder-visible', 'true');
				input.value = placeholder;
				input.style.color = color;
			}else{
				input.style.color = default_color;
				input.setAttribute('data-placeholder-visible', '');
			}
		});
		return input;
	}
};

// Кроссбраузерная инциализаци placeholder у input text/textarea
jWps.onDomReady(function(){
	var nodes = document.getElementsByTagName('*'), i=0, node, elemets=[];
	while (node = nodes[i++]){
		if((node.tagName == 'INPUT' && node.type == 'text') || node.tagName == 'TEXTAREA'){
			if(node.getAttribute('placeholder')){
				elemets.push(node);
			}
		}
	}
	if(!elemets.length) return null;
	
	for(var i=0; i<elemets.length; i++){		
		input.placeholder(elemets[i]);
	}
});

/***** Block Account *****/
var baccount = (function(){
	var ajax = new newAjax();
	var act, act_type;
	
	var status_box, status_preloader, status_box_edit, status_text, status_time, status_history, status_edit_input, status_text_value;
	
	var tpl_hrow = '';
	
	jWps.onDomReady(function(){
		var account_status_box = jWps('.account_status_box')[0];
		status_box = jWps('.status_box', account_status_box);
		status_box_edit = jWps('.status_box_edit', account_status_box);
		status_preloader = jWps('.status_preloader', account_status_box);
		status_text = jWps('.status_text', account_status_box);
		status_time = jWps('.status_time', account_status_box);
		status_history = jWps('.status_history', account_status_box);
		status_edit_input = jWps('#status_edit_input', account_status_box);
		status_text_value = jWps('#status_text_value', account_status_box);
	});
	
	
	ajax.setup({
		onStart: function(){
			if(act == 'status'){
				if(act_type == 'del'){
					status_preloader.show();
				}else if(act_type == 'history'){
					status_preloader.show();
				}else{
					status_box.hide();
					status_box_edit.hide();
					status_preloader.show();
				}
			}
		},
		onComplete: function(data, text){
			if(data.error > 0){
				alert(data.error_msg);
			}else{
				if(act == 'status'){
					if(act_type == 'del'){
						jWps('#hrow'+act_id).remove();
						if(data.tpl_hrow != '') tpl_hrow = data.tpl_hrow;
						if(data.hrows && tpl_hrow){
							var html = tpl_hrow;
							html = jWps.replace('[#hid]',data.hrows['hid'],html);
							html = jWps.replace('[#added]',data.hrows['added'],html);
							html = jWps.replace('[#text]',data.hrows['text'],html);
							var nhrow = jWps.create('div');
							status_history.append(nhrow);
							jWps(nhrow).html(html);
						}
						status_preloader.hide();
					}else if(act_type == 'history'){
						if(data.tpl_hrow != '') tpl_hrow = data.tpl_hrow;
						if(data.hrows && tpl_hrow){
							var html = '', l = data.hrows.length;
							for(var i=0; i<l; i++){
								var item = data.hrows[i];
								html+= tpl_hrow;
								html = jWps.replace('[#hid]',item['hid'],html);
								html = jWps.replace('[#added]',item['added'],html);
								html = jWps.replace('[#text]',item['text'],html);
							}
							status_history.html(html);
						}
						status_preloader.hide();
					}else{
						status_text_value[0].value = data.value;
						status_text.html(data.text);
						status_time.html(data.time);
						status_preloader.hide();
						status_box.show();
					}
				}
			}
		},
		onError: function(query){
			if(query.act == 'status'){
				status[act_type]();
			}
		}
	});
	
	var status = {
		'edit': function(){
			status_history.html('');
			status_box.hide();
			status_edit_input[0].value = status_text_value[0].value;
			status_box_edit.show();
			status_edit_input[0].focus();
			
			act = 'status';
			act_type = 'history';
			ajax.post({'block':'account', 'act': act, 'act_type': act_type});
		},
		cancel: function(){
			status_box_edit.hide();
			status_box.show();
		},
		save: function(){
			act = 'status';
			act_type = 'save';
			ajax.post({'block':'account', 'act': act, 'act_type': act_type, 'text':status_edit_input[0].value});
		},
		clear: function(){
			act = 'status';
			act_type = 'clear';
			ajax.post({'block':'account', 'act': act, 'act_type': act_type, 'text':''});
		},
		set: function(id){
			act = 'status';
			act_type = 'set';
			act_id = id;
			ajax.post({'block':'account', 'act': act, 'act_type': act_type, 'id':act_id});
		},
		del: function(id){
			act = 'status';
			act_type = 'del';
			act_id = id;
			ajax.post({'block':'account', 'act': act, 'act_type': act_type, 'id':act_id});
		}
	}
	
	return{
		'status': {
			'edit': function(){
				status.edit();
			},
			'cancel': function(){
				status.cancel();
			},
			'save': function(){
				status.save();
			},
			'clear': function(){
				status.clear();
			},
			'set': function(id){
				status.set(id);
			},
			'del': function(id){
				status.del(id);
			}
		}
	}
})();

/**********
* Photo Viewer
*/

var pvm = (function(){
	var module = 'photoviewer';
	var ajax = new newAjax();
	var init_t, pvm_canvas = null, pvm_bg = null;
	var photos = [], curphotoid = 0;
	var showed = 0;
	var maxWidth = 800;
	var maxHeight = 800;
	
	function createCanvas(data){
		var tpl_canvas_body = '<div class="pvm_action_wrap"><div class="pvm_close" onclick="pvm.close();"></div></div><table cellspacing="2" cellpadding="0" border="0"><tr>'+
			'<td class="pvm_prew" onclick="pvm.prew();" [#prewstyle]><table width="100%"><tr><td valign="middle" align="center"><i></i></td></tr></table></td>'+
			'<td align="center"><div class="pvm_photoarea_wrap"><div class="pvm_photoarea" style="width:[#width]px; height:[#height]px;"><img src="[#photosrc]" id="pvm_photo" width="[#width]" height="[#height]" />'+
			'<div id="pvm_preloading"><table><tr><td align="center" valign="middle"><i></i></td></tr></table></div></div>'+
			'</td><td class="pvm_next" onclick="pvm.next();" [#nextstyle]><table width="100%"><tr><td valign="middle" align="center"><i></i></td></tr></table></td>'+
			'</tr><tr><td[#prewstyle]></td><td><div id="pvm_photoinfo">[#info]</div></div></td><td[#nextstyle]></td></tr></table></div>';
		tpl_canvas_body = jWps.replace('[#photosrc]', data.src, tpl_canvas_body);
		tpl_canvas_body = jWps.replace('[#info]', (data.info) ? data.info : '', tpl_canvas_body);
		if(init_t == 'p'){
			tpl_canvas_body = jWps.replace('[#prewstyle]', ' style="display: none;"', tpl_canvas_body);
			tpl_canvas_body = jWps.replace('[#nextstyle]', ' style="display: none;"', tpl_canvas_body);
		}else{
			tpl_canvas_body = jWps.replace('[#prewstyle]', '', tpl_canvas_body);
			tpl_canvas_body = jWps.replace('[#prewstyle]', '', tpl_canvas_body);
		}
		
		pvm_canvas = jWps.create('div',{'id':'pvm_canvas'});
		var image = new Image();
		image.onload = function(){
			var width = image.width;
			var height = image.height;
			if(width > height){
				if(width > maxWidth){
					height = maxWidth / (width / height);
					width = maxWidth;
				}
			}else{
				if(height > maxHeight){
					width = maxHeight / (height / width);
					height = maxHeight;
				}
			}
			
			tpl_canvas_body = jWps.replace('[#height]', height, tpl_canvas_body);
			tpl_canvas_body = jWps.replace('[#width]', width, tpl_canvas_body);
			pvm_canvas.innerHTML = tpl_canvas_body;
			showCanvas();
		};
		image.src = data.src;
		curphotoid = 0;
	}
	
	function showCanvas(){
		var offset_top = document.body.scrollTop || document.documentElement.scrollTop;
		var offset_left = document.body.scrollLeft || document.documentElement.scrollLeft;
		jWps('html').setStyle('overflowY', 'hidden');
		jWps('html').setStyle('overflowX', 'hidden');
		var width = jWps.clientWidth();
		var height = jWps.clientHeight();
		
		pvm_bg = jWps.create('div',{'id':'pvm_bg','style':{'width':width+offset_left+'px','height':height+offset_top+'px'}});
		jWps('body').append(pvm_bg);
		jWps('body').append(pvm_canvas);
		
		jWps('#pvm_photo')[0].onclick = function(){
			(init_t == 'p') ? pvm.close() : pvm.next();
		}
		
		pvm_canvas.style.left = (jWps.clientWidth() - pvm_canvas.clientWidth) / 2 + offset_left + 'px';
		pvm_canvas.style.top = 50 + offset_top + 'px';
		
		pvm_bg.onclick = function(){ closeCanvas(); };
		
		window.onresize = function(){
			var offset_top = document.body.scrollTop || document.documentElement.scrollTop;
			var offset_left = document.body.scrollLeft || document.documentElement.scrollLeft;
			var width = jWps.clientWidth();
			var height = jWps.clientHeight();
			
			pvm_bg.style.width = width + offset_top + 'px';
			pvm_bg.style.height =  height + offset_top + 'px';
			
			
			pvm_canvas.style.left = (width - pvm_canvas.clientWidth) / 2 + offset_left + 'px';
			pvm_canvas.style.top = 50 + offset_top + 'px';
		}
		
		addEventsHandler();
	}
	
	function closeCanvas(){
		jWps(pvm_bg).remove();
		jWps(pvm_canvas).remove();
		removeEventsHandler();
		jWps('html').setStyle('overflowY', 'scroll');
		jWps('html').setStyle('overflowX', 'scroll');
		showed = 0;
	}
	
	function prewPhoto(){
		if(curphotoid > 0){
			curphotoid--;
			showPhoto(curphotoid);
		}
	}
	
	function nextPhoto(){
		if(curphotoid < photos.length - 1){
			curphotoid++;
			showPhoto(curphotoid);
		}else{
			closeCanvas();
		}
	}
	
	function showPhoto(photoid){
		var preloading = jWps('#pvm_preloading');
		var photo = jWps('#pvm_photo');
		preloading.show();
		photo.hide();
		
		var image = new Image();		
		image.onload = function(){
			if(image.height != photo[0].height || image.width != photo[0].width){
				photo.hide();
				preloading.show();
				jWps('.pvm_photoarea').setSize(image.width, image.height, function(){
					photo[0].src = image.src;
					photo[0].height = image.height;
					photo[0].width = image.width;
					preloading.hide();
					photo.show();
					jWps('#pvm_photoinfo').html(photos[photoid].info);
				}, 500);
			}else{
				photo[0].src = photos[photoid].src;
				jWps('#pvm_photoinfo').html(photos[photoid].info);
				
				preloading.hide();
				photo.show();
			}
		};
		image.src = photos[photoid].src;
	}
	
	function addEventsHandler(){
		var browser = jWps.browser;
		var keyev = (!browser.msie && !browser.safari && !browser.webkit) ? 'keypress' : 'keydown';
		jWps(document).bind(keyev, onKeyDown);
	}
	
	function removeEventsHandler(){
		var browser = jWps.browser;
		var keyev = (!browser.msie && !browser.safari && !browser.webkit) ? 'keypress' : 'keydown';
		jWps(document).unbind(keyev, onKeyDown);
	}
	
	function onKeyDown(e){
		var key = e.keyCode || e.charCode;
		switch(key){
			case 27:  // Esc
				closeCanvas();
				break;
			case 37: // <--
				prewPhoto();
				break;
			case 39:  // -->
				nextPhoto();
				break;
		}
	}
	
	return{
		'inita': function(aid){
			if(showed) return;
			init_t = 'a';
			ajax.post({'module':module,'act':'inita','aid':aid}, function(data){
				if(data.photos){
					photos = data.photos;
					createCanvas({'src':photos[0].src,'info':photos[0].info});
				}
			});
			showed = 1;
		},
		'initp': function(pid){
			if(showed) return;
			init_t = 'p';
			ajax.post({'module':module,'act':'initp','pid':pid}, function(data){
				if(data.src){
					createCanvas(data);
				}
			});
			showed = 1;
		},
		'inits': function(src){
			if(showed) return;
			init_t = 'p';
			if(typeof(src) !== 'string'){
				if(src.tagName == 'IMG') src = src.src;
				else if(src.tagName == 'A') src = src.href;
			}
			createCanvas({'src':src});
			showed = 1;
		},
		'close': function(){
			closeCanvas();
		},
		'prew': function(){
			prewPhoto();
		},
		'next': function(){
			nextPhoto();
		}
	}
})();


/*
* End Photo Viewer
**********/

/***** Votes *****/
var votes = {
	'submit': function(vid, pid){
		var ajax = new Ajax();
		ajax.post({'module':'votes', 'act':'submit', 'vid':vid, 'pid':pid}, function(data){ votes.parse(data, vid); });
	},
	'revote': function(vid){
		var ajax = new newAjax();
		ajax.post({'module':'votes', 'act':'revote', 'vid':vid}, function(data, text){ votes.parse(data, vid); });
	},
	'open': function(vid){
		var ajax = new newAjax();
		ajax.post({'module':'votes', 'act':'open', 'vid':vid}, function(data){ votes.parse(data, vid); });
	},
	'close': function(vid){
		var ajax = new newAjax();
		ajax.post({'module':'votes', 'act':'close', 'vid':vid}, function(data){ votes.parse(data, vid); });
	},
	'parse': function(data, vid){
		if(data.params) jWps('#vote' + vid).find('.vote_params').html(data.params);
		if(data.action) jWps('#vote' + vid).find('.vote_action').html(data.action);
	}
}

var blockJobs = (function(){
	var ajax = new Ajax();
	
	return{
		'switch': function(e){
			ajax.post({'block':jobs, 'act':'switch'}, function(data){
				
				
				
			});
		}
	}
})();

function jobSwitch(e){
	var jtype = (jWps.getCookie('bj_type') == 1) ? 0 : 1;
	jWps.setCookie('bj_type',jtype);
	var ajax = new Ajax();
	ajax.post({'block':'jobs'}, function(data){
		e.innerHTML = data.type;
		e.title = data.typetitle;
		jWps('#jobswitch').html(data.html);
		jWps('#jobswitchall').html(data.alltext)[0].href = data.allhref;
		jWps('#jobswitchadd').html(data.addtext)[0].href = data.addhref;
		jWps('#jobswitchtitle').html(data.title);
	});
}
