(function($) {

  this.GLOBAL = {
    debug: true,

    // Глобальный объект для переинициализации всего,
    // в ответ на аякс например
    aInit: [],
    reInit: function(func){
      try{
        if(func && $.isFunction(func)){
          func.call();
          this.aInit.push(func);
        } else {
          $.each(this.aInit, function(){
            this.call();
          })
        }
      } catch(e){
        debug(e);
      }
    }
  }

  this.debug = function(str) {
  	if (window.console && window.console.log && GLOBAL.debug)
  	window.console.log("[GLOBAL: '" + str + "']\n" + debug.caller.toString());
  };

  if( typeof(String.prototype.trim) === "undefined" ) {
    String.prototype.trim = function(){
      return String(this).replace(/^\s+|\s+$/g, '');
    };
  }

  if( typeof(Array.prototype.uniq) === "undefined" ) {
    Array.prototype.uniq = function() {
      var o = {}, i, l = this.length, r = [];
      for(i=0; i<l;i++) o[this[i]] = this[i];
      for(i in o) r.push(o[i]);
      return r;
    };
  }


})(jQuery);

// Inspired by base2 and Prototype

(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  // The base Class implementation (does nothing)
  this._Class = function(){};

  // Create a new Class that inherits from this class
  _Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function _Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    _Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    _Class.constructor = _Class;

    // And make this class extendable
    _Class.extend = arguments.callee;

    return _Class;
  };
})();

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed

(function(){
  var cache = {};

  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(str) :

      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +

        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +

        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");

    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();
/*
  Required:
    — jQuery
    — jQuery Easing plugin
    — John Resig Simple JavaScript Inheritance (object: "_Class")
*/

(function( $ ){

  this.classAnimate = _Class.extend({
    init: function( step, duration, easing, callback ){
    	this.opt = {
    		step: step,
    		complete: callback ? callback : function(){}
    	};
    	if( $.isFunction(easing) ){
    	  this.opt.complete = easing;
    	}

    	this.now = 0;
    	this.duration = duration;

    	this.easing = !$.isFunction(easing) ? easing : "swing";

    	this._init();
    },

  	_init: function(){
  		var self = this;
  		this.startTime = ( new Date() ).getTime();
  		this.timerId = setInterval(function(){
  			self.next();
  		}, 13);
  	},

  	next: function(){
  		this.prev = this.now;
  		var t = ( new Date() ).getTime();
  		this.step = t - this.startTime;

  		if( this.step > this.duration ){
  			this.step = this.duration;
  			this.exec();
  			clearInterval(this.timerId);
  			this.opt.complete.apply(this);

  			return;
  		}

  		this.exec();
  	},

  	exec: function(){
  		this.state = this.step / this.duration;
  		this.now = $.easing[this.easing](this.state, this.step, 0, 1, this.duration);
  		this.opt.step.apply(this, [this.now, this.prev]);
  	},

  	stop: function(){
  		clearInterval(this.timerId);
  	}

  })

})( jQuery );

/*
  Required:
    — jQuery
    — John Resig Simple JavaScript Inheritance (object: "_Class")
*/

(function( $ ){

  this.classDraggable = _Class.extend({

  	isDefault: {
  		drag: false,
  		clicked: false,
  		toclick: true,
  		mouseup: false
  	},

    // Main init method
  	init: function(){
  		if(arguments.length > 0){
  			this.ptr = $(arguments[0]);
  			this.outer = $(".draggable-outer");

  			this.is = {};
  			$.extend(this.is, this.isDefault);

  			var _offset = this.ptr.offset();
  			this.d = {
  				left: _offset.left,
  				top: _offset.top,
  				width: this.ptr.width(),
  				height: this.ptr.height()
  			};

  			this.oninit.apply(this, arguments);

  			this._events();
  		}
  	},


  	// Methods for re-init in child class
  	oninit: function(){},
  	events: function(){},
  	onmousedown: function(){
  		this.ptr.css({ position: "absolute" });
  	},
  	onmousemove: function(evt, x, y){
  		this.ptr.css({ left: x, top: y });
  	},
  	onmouseup: function(){},


    // Basic events and method
  	_events: function(){
  		var oThis = this;

  		$(document)
  			.mousemove(function(evt){
  				if(oThis.is.drag){
  					oThis._mousemove(evt);
  					return false;
  				}
  			})
  			.mouseup(function(evt){
  				oThis._mouseup(evt);
  			})
  			.bind("dragstart", function(){
  				return false;
  			});

  		this.ptr
  			.mousedown(function(evt){
  				oThis._mousedown(evt);
  				return false;
  			})
  			.mouseup(function(evt){
  				oThis._mouseup(evt);
  			});

  		this.ptr.find("a")
  			.click(function(){
  				oThis.is.clicked = true;
  				if(!oThis.is.toclick){
  					oThis.is.toclick = true;
  					return false;
  				}
  			})
  			.mousedown(function(oEvt){
  				oThis._mousedown(oEvt);
  				return false;
  			})
  			.bind("dragstart", function(){
  				return false;
  			});


  		this.events();
  	},
  	_mousedown: function(evt){
  		this.is.drag = true;
  		this.is.clicked = false;
  		this.is.mouseup = false;

  		var _offset = this.ptr.offset();
  		this.cx = evt.pageX - _offset.left;
  		this.cy = evt.pageY - _offset.top;

  		$.extend(this.d, {
  			left: _offset.left,
  			top: _offset.top,
  			width: this.ptr.width(),
  			height: this.ptr.height()
  		});

  		if(this.outer && this.outer.get(0)){
  			this.outer.css({ height: Math.max(this.outer.height(), $(document.body).height()), overflow: "hidden" });
  		}

  		this.onmousedown(evt);
  	},
  	_mousemove: function(evt){
  		this.is.toclick = false;
  		this.onmousemove(evt, evt.pageX - this.cx, evt.pageY - this.cy);
  	},
  	_mouseup: function(evt){
  		var oThis = this;
  		if(this.is.drag){
  			this.is.drag = false;

  			if(this.outer && this.outer.get(0)){

  				if($.browser.mozilla) {
  					this.outer.css({ overflow: "hidden" });
  				} else {
  					this.outer.css({ overflow: "visible" });
  				}

  				if($.browser.msie && $.browser.version == '6.0') {
  					this.outer.css({ height: "100%" });
  				} else {
  					this.outer.css({ height: "auto" });
  				}
  			}

  			this.onmouseup(evt);
  		}
  	}


  })


})( jQuery );

/*
 * jQuery EasIng v1.1.2 - http://gsgd.co.uk/sandbox/jquery.easIng.php
 *
 * Uses the built In easIng capabilities added In jQuery 1.1
 * to offer multiple easIng options
 *
 * Copyright (c) 2007 George Smith
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// t: current time, b: begInnIng value, c: change In value, d: duration

jQuery.extend( jQuery.easing,
{
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

(function(b){function d(e,f){this.options=e;if(!e.cacheLength||e.cacheLength<1){this.options.cacheLength=1}this.persistent={};if(this.options.data){this.initPersistent(this.options.data)}this.flush()}d.prototype={flush:function(){this.data={};this.length=0},initPersistent:function(j){var e="",g={},l=[];for(var h=0;h<j.length;h++){l=j[h].trim();if(l.length>0){e=l.substring(0,1).toLowerCase();if(!g[e]){g[e]=[]}g[e].push(l)}}for(var f in g){this.addToPersistent(f,g[f])}},addToPersistent:function(f,e){if(!e||!f){return}this.persistent[f]=e},lookup:function(e){return this.merge(this.lookupPersistent(e),this.lookupTemp(e))},merge:function(g,f){var e=[];if(g){for(var h=0;h<g.length;h++){e[h]=g[h]}}if(f){for(h=0;h<f.length;h++){if(e.indexOf(f[h])==-1){e[e.length]=f[h]}}}return e.length>0?e:null},lookupTemp:function(e){return this.lookupCache(e,this.data)},lookupPersistent:function(e){return this.lookupCache(e,this.persistent)},lookupCache:function(m,g){if(!m||!g){return null}if(g[m]){return g[m]}if(this.options.matchSubset){var l=[];for(var k=m.length-1;k>=this.options.minChars;k--){var f=m.substr(0,k);var n=g[f];if(n){for(var h=0;h<n.length;h++){var e=n[h];if(l.indexOf(e)==-1&&this.matchSubset(e,m)){l[l.length]=e}}}}l=l.uniq();if(l.length>0){g[m]=l;return l}}return null},matchSubset:function(g,f){if(!g){return false}if(!this.options.matchCase){g=g.toLowerCase()}var e=g.indexOf(f);if(e==-1){return false}return e===0||this.options.matchContains},store:function(f,e){if(!e||!f){return}if(!this.length){this.flush();this.length++}else{if(!this.data[f]){this.length++}}this.data[f]=e}};function a(e,g,f){var h=g.get(0);document.body.appendChild(h);this.results=b(h);this.timeout=null;this.input=e;this.results.hide();this.options=f;this.active=-1;if(typeof(this.options.width)=="string"){this.options.width=parseInt(this.options.width,10)}if(this.options.width>0){this.results.css("width",this.options.width)}}a.prototype={moveUp:function(){this.moveSelect(-1)},moveDown:function(){this.moveSelect(1)},moveSelect:function(g){var f=b("li",this.results);if(!f){return}this.active+=g;if(this.active<0){this.active=0}else{if(this.active>=f.size()){this.active=f.size()-1}}f.removeClass("selected");b(f[this.active]).addClass("selected");if(this.options.autoFill){var e=b(f[this.active]).get(0);this.input.autoFill(e.selectData||e.selectValue)}},hideNow:function(){if(this.timeout){clearTimeout(this.timeout)}if(this.results.is(":visible")){this.results.hide()}if(this.options.mustMatch){var e=this.input.value();if(e!=this.input.lastSelected){this.selectItem(null)}}},hide:function(){if(this.timeout){clearTimeout(this.timeout)}var e=this;this.timeout=setTimeout(function(){e.hideNow()},200)},selectCurrent:function(){var e=b("li.selected",this.results)[0];if(!e){var f=b("li",this.results);if(this.options.selectOnly){if(f.length==1){e=f[0]}}else{if(this.options.selectFirst){e=f[0]}}}if(e){this.selectItem(e);return true}else{return false}},show:function(){var f=(this.input.input.offset().top+this.input.input.get(0).offsetHeight);var e=this.input.input.offset().left;this.results.css({position:"absolute",width:(this.options.width+6)+"px",top:f+"px",left:e+"px",zIndex:999}).show().find("li:first").addClass("selected").end()},selectItem:function(e){if(!e){e=document.createElement("li");e.extra=[];e.selectValue=""}var f=b.trim(e.selectValue?e.selectValue:e.innerHTML);this.results.html("");this.input.trigger("valueselected",[f]);if(this.options.onItemSelect){setTimeout(function(){this.options.onItemSelect(e)},1)}},dataToDom:function(e){var h=document.createElement("ul");var g=e.length;var m=this;if((this.options.maxItemsToShow>0)&&(this.options.maxItemsToShow<g)){g=this.options.maxItemsToShow}for(var f=0;f<g;f++){var n=e[f];var k=document.createElement("li");if(this.options.formatItem){k.innerHTML=this.options.formatItem(n,f,g);k.selectValue=n}else{if(typeof(n)!="string"){k.innerHTML="";for(var j in n){if(n[j]){k.innerHTML+="<span>"+n[j]+"</span>"}}k.selectValue=n[this.options.select];k.selectData=n}else{k.innerHTML=n;k.selectValue=n}}h.appendChild(k)}var l=b(h).find("li");l.hover(function(){l.removeClass("selected");b(this).addClass("selected");m.active=l.indexOf(b(this).get(0))},function(){b(this).removeClass("selected")}).click(function(i){i.preventDefault();i.stopPropagation();m.selectItem(this)});return h},loadData:function(e){this.results.html("");if(b.browser.msie){}this.active=0;this.results.append(this.dataToDom(e))}};function c(f,h,g){this.input=b(f);this.input.get(0).autocompleter=h;this.input.attr("autocomplete","off");this.id="#"+this.input.attr("id");this.spinner=b(this.id+"_auto_complete_indicator");this.spinner.css("left",(parseInt(this.input.css("width"),10)-15)+"px");this.options=g;if(g.inputClass){this.input.addClass(g.inputClass)}this.hasFocus=false;this.lastKeyPressCode=null;var i=null;this.prev="";var e=this;this.input.keydown(function(j){this.lastKeyPressCode=j.keyCode;switch(j.keyCode){case 38:j.preventDefault();e.input.trigger("moveup");break;case 40:j.preventDefault();e.input.trigger("movedown");break;case 13:e.input.trigger("selectcurrent");j.preventDefault();return false;break;default:if(i){clearTimeout(i)}i=setTimeout(function(){e.change()},g.delay);break}}).focus(function(){e.hasFocus=true}).blur(function(){e.hasFocus=false;e.input.trigger("valuehide")})}c.prototype={change:function(){if(this.lastKeyPressCode==46||(this.lastKeyPressCode>8&&this.lastKeyPressCode<32)){return this.input.trigger("hide")}var e=this.value();if(e==this.prev){return}this.prev=e;if(e.length>=this.options.minChars){this.startLoad();this.input.trigger("valuechange",[e])}else{this.stopLoad();this.input.trigger("valuehide")}},startLoad:function(){this.input.addClass(this.options.loadingClass)},stopLoad:function(){this.input.removeClass(this.options.loadingClass);this.hideSpinner()},showSpinner:function(){this.spinner.show()},hideSpinner:function(){this.spinner.hide()},value:function(){var e=this.input.val().split(",").map(function(f){return f.trim()});return e.length>0?e[e.length-1]:""},setValue:function(e){var g=this.input.val().split(",").map(function(h){return h.trim()});var f=g.pop();g[g.length]=e;this.input.val(g.join(",")).trigger("valueSet",e)},currentStartPosition:function(){var e=this.input.val().lastIndexOf(",");return e>0?e+1:0},createSelection:function(i,f){var g=this.input.get(0);var h=this.currentStartPosition();i=h+i;f=h+f;if(g.createTextRange){var e=g.createTextRange();e.collapse(true);e.moveStart("character",i);e.moveEnd("character",f);e.select()}else{if(g.setSelectionRange){g.setSelectionRange(i,f)}else{if(g.selectionStart){g.selectionStart=i;g.selectionEnd=f}}}g.focus()},autoFill:function(e){var g=typeof(e)=="string"?e:e[this.options.select];if(this.lastKeyPressCode==8){return false}if(typeof(e)!="string"&&this.options.fieldPrefix){for(var f in e){b("#"+this.options.fieldPrefix+"_"+f).val(e[f])}}this.setValue(g);this.createSelection(this.prev.length,g.length)},receiveData:function(f,e){if(!this.hasFocus||!e.length){return false}if(this.options.autoFill&&(this.value().toLowerCase()==f.toLowerCase())){this.autoFill(e[0])}return true},trigger:function(e,f){this.input.trigger(e,f)}};b.autocomplete=function(j,o){var m=new c(j,this,o);if(!o.width>0){o.width=m.input.css("width")}var i=new a(m,b(m.id+"_auto_complete"),o);var e=new d(o,o.data);var n=false;var l=false;var h=null;function g(s){var p=o.url+"?q="+encodeURI(s);for(var r in o.extraParams){p+="&"+r+"="+encodeURI(o.extraParams[r])}if(o.with_params&&typeof(o.with_params)=="function"){p+=o.with_params()}return p}function k(r,p){if(p){m.stopLoad();if(!m.receiveData(r,p)){return i.hideNow()}i.loadData(p);i.show()}else{i.hideNow()}}function f(p,r){if(!o.matchCase){r=r.toLowerCase()}var s=e.lookup(r);if(s){k(r,s)}if((!s||s.length<o.maxItemsToShow)&&(typeof o.url=="string")&&(o.url.length>0)){h=b.ajax({url:g(r),async:true,beforeSend:function(){m.showSpinner()},dataType:"json",complete:function(){m.hideSpinner()},success:function(q){e.store(r,q);k(r,e.merge(s,q))}})}else{m.stopLoad()}}m.input.bind("moveup",function(){i.moveUp()}).bind("movedown",function(){i.moveDown()}).bind("selectcurrent",function(){i.selectCurrent()}).bind("valuehide",function(){i.hide();m.stopLoad()}).bind("valuechange",f).bind("valueselected",function(q,p){m.lastSelected=p;this.prev=p;if(h){m.hideSpinner();h=null}m.setValue(p);e.flush()})};jQuery.fn.autocomplete=function(f,e,g){e=e||{};e.url=f;e.data=(g&&(typeof g=="object")&&(g.constructor==Array))?g:null;e.inputClass=e.inputClass||"ac_input";e.resultsClass=e.resultsClass||"ac_results";e.lineSeparator=e.lineSeparator||"\n";e.cellSeparator=e.cellSeparator||"|";e.minChars=e.minChars||2;e.delay=e.delay||400;e.matchCase=e.matchCase||0;e.matchSubset=e.matchSubset||true;e.matchContains=e.matchContains||false;e.cacheLength=e.cacheLength||1;e.mustMatch=e.mustMatch||0;e.extraParams=e.extraParams||{};e.loadingClass=e.loadingClass||"ac_loading";e.selectFirst=e.selectFirst||false;e.selectOnly=e.selectOnly||false;e.maxItemsToShow=e.maxItemsToShow||8;e.autoFill=e.autoFill||true;e.width=parseInt(e.width,10)||0;this.each(function(){var h=this;var i=new jQuery.autocomplete(h,e)});return this};jQuery.fn.autocompleteArray=function(f,e){return this.autocomplete(null,e,f)};jQuery.fn.indexOf=function(g){for(var f=0;f<this.length;f++){if(this[f]==g){return f}}return -1}})(jQuery);
(function(d){d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(f,e){d.fx.step[e]=function(g){if(g.state==0){g.start=c(g.elem,e);g.end=b(g.end)}g.elem.style[e]="rgb("+[Math.max(Math.min(parseInt((g.pos*(g.end[0]-g.start[0]))+g.start[0]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[1]-g.start[1]))+g.start[1]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[2]-g.start[2]))+g.start[2]),255),0)].join(",")+")"}});function b(f){var e;if(f&&f.constructor==Array&&f.length==3){return f}if(e=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)){return[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])]}if(e=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)){return[parseFloat(e[1])*2.55,parseFloat(e[2])*2.55,parseFloat(e[3])*2.55]}if(e=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}if(e=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}return a[d.trim(f).toLowerCase()]}function c(g,e){var f;do{f=d.curCSS(g,e);if(f!=""&&f!="transparent"||d.nodeName(g,"body")){break}e="backgroundColor"}while(g=g.parentNode);return b(f)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
/*
 * Depend Class v0.1b : attach class based on first class in list of current element
 * File: jquery.dependClass.js
 * Copyright (c) 2009 Egor Hmelyoff, hmelyoff@gmail.com
 */


(function($) {
	// Init plugin function
	$.baseClass = function( obj ){
	  obj = $(obj);
	  var sClass = obj.get(0).className.match(/([^ ]+)/);
	  if( sClass && sClass[1] )
	    return sClass[1];

	  return false;
	};

	$.fn.addDependClass = function( className, delimiter ){
		var options = {
		  delimiter: delimiter ? delimiter : '-'
		}
		return this.each(function(){
		  var baseClass = $.baseClass(this);
		  if( baseClass )
    		$(this).addClass(baseClass + options.delimiter + className);
    	else {
    	  this.baseClass = false;
    	  $(this).addClass(className);
    	}

		});
	};

	$.fn.removeDependClass = function( className, delimiter ){
		var options = {
		  delimiter: delimiter ? delimiter : '-'
		}
		return this.each(function(){
		  var baseClass = $.baseClass(this);

    	if( this.className == className || this.baseClass === false )
    	  $(this).removeClass(className);

		  else if( baseClass )
    		$(this).removeClass(baseClass + options.delimiter + className);

		});
	};

	$.fn.toggleDependClass = function( className, delimiter ){
		var options = {
		  delimiter: delimiter ? delimiter : '-'
		}
		return this.each(function(){
		  var baseClass = $.baseClass(this);
		  if( baseClass )
		    if( $(this).is("." + baseClass + options.delimiter + className) )
    		  $(this).removeClass(baseClass + options.delimiter + className);
    		else
    		  $(this).addClass(baseClass + options.delimiter + className);
		});
	};

	// end of closure
})(jQuery);
jQuery.cookie=function(b,j,m){if(typeof j!="undefined"){m=m||{};if(j===null){j="";m.expires=-1}var e="";if(m.expires&&(typeof m.expires=="number"||m.expires.toUTCString)){var f;if(typeof m.expires=="number"){f=new Date();f.setTime(f.getTime()+(m.expires*24*60*60*1000))}else{f=m.expires}e="; expires="+f.toUTCString()}var l=m.path?"; path="+(m.path):"";var g=m.domain?"; domain="+(m.domain):"";var a=m.secure?"; secure":"";document.cookie=[b,"=",encodeURIComponent(j),e,l,g,a].join("")}else{var d=null;if(document.cookie&&document.cookie!==""){var k=document.cookie.split(";");for(var h=0;h<k.length;h++){var c=jQuery.trim(k[h]);if(c.substring(0,b.length+1)==(b+"=")){d=decodeURIComponent(c.substring(b.length+1));break}}}return d}};
(function(c){var a=c.scrollTo=function(f,e,d){c(window).scrollTo(f,e,d)};a.defaults={axis:"xy",duration:parseFloat(c.fn.jquery)>=1.3?0:1};a.window=function(d){return c(window)._scrollable()};c.fn._scrollable=function(){return this.map(function(){var e=this,d=!e.nodeName||c.inArray(e.nodeName.toLowerCase(),["iframe","#document","html","body"])!=-1;if(!d){return e}var f=(e.contentWindow||e).document||e.ownerDocument||e;return c.browser.safari||f.compatMode=="BackCompat"?f.body:f.documentElement})};c.fn.scrollTo=function(f,e,d){if(typeof e=="object"){d=e;e=0}if(typeof d=="function"){d={onAfter:d}}if(f=="max"){f=9000000000}d=c.extend({},a.defaults,d);e=e||d.speed||d.duration;d.queue=d.queue&&d.axis.length>1;if(d.queue){e/=2}d.offset=b(d.offset);d.over=b(d.over);return this._scrollable().each(function(){var l=this,j=c(l),k=f,i,g={},m=j.is("html,body");switch(typeof k){case"number":case"string":if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(k)){k=b(k);break}k=c(k,this);case"object":if(k.is||k.style){i=(k=c(k)).offset()}}c.each(d.axis.split(""),function(q,r){var s=r=="x"?"Left":"Top",u=s.toLowerCase(),p="scroll"+s,o=l[p],n=a.max(l,r);if(i){g[p]=i[u]+(m?0:o-j.offset()[u]);if(d.margin){g[p]-=parseInt(k.css("margin"+s))||0;g[p]-=parseInt(k.css("border"+s+"Width"))||0}g[p]+=d.offset[u]||0;if(d.over[u]){g[p]+=k[r=="x"?"width":"height"]()*d.over[u]}}else{var t=k[u];g[p]=t.slice&&t.slice(-1)=="%"?parseFloat(t)/100*n:t}if(/^\d+$/.test(g[p])){g[p]=g[p]<=0?0:Math.min(g[p],n)}if(!q&&d.queue){if(o!=g[p]){h(d.onAfterFirst)}delete g[p]}});h(d.onAfter);function h(n){j.animate(g,e,d.easing,n&&function(){n.call(this,f,d)})}}).end()};a.max=function(j,i){var h=i=="x"?"Width":"Height",e="scroll"+h;if(!c(j).is("html,body")){return j[e]-c(j)[h.toLowerCase()]()}var g="client"+h,f=j.ownerDocument.documentElement,d=j.ownerDocument.body;return Math.max(f[e],d[e])-Math.min(f[g],d[g])};function b(d){return typeof d=="object"?d:{top:d,left:d}}})(jQuery);

(function($) {

	$.fn.LAMswitcher = function( callback, options ){
		var OPTIONS = $.extend({
		  className: "selected",
		  delay: 0
		}, options ? options : {});

		var self = this;

		return this.each(function(){
			$(this).click(function(){
			  var node = this;
			  self.removeDependClass(OPTIONS.className);
			  $(this).addDependClass(OPTIONS.className);
			  if( $.isFunction(callback) )
			    if( OPTIONS.delay )
    			  setTimeout(function(){
    			    callback.call(node);
    			  }, OPTIONS.delay);
    			else
    			  callback.call(node);

			  return false;
			});
		});
	};

})(jQuery);


(function($) {

	$.fn.serializeOnly = function(){
	  var form = this.serializeArray();
	  var result = new Array()
	  for (var i=0; i < form.length; i++) {
	    for( var j=0; j < arguments.length; j++ ){
	     if( form[i].name == arguments[j] )
	      result.push(form[i]);
	    };

	  };

    return jQuery.param( result );
	};

})( jQuery );
/* Global browsers definition */

(function($) {

  if( !$.browser.msie ) $(document.documentElement).addClass("e-loaded");

  // default browser detection
	if( $.browser.safari ) $(document.documentElement) .addClass("e-webkit");
	if( $.browser.mozilla ) $(document.documentElement).addClass("e-gecko");
	if( $.browser.opera ) $(document.documentElement).addClass("e-opera");

  // mac browser detection
	var isMac = navigator.userAgent.indexOf('Mac') != -1;
	if(isMac){
	  $(document.documentElement).addClass("e-mac");
  	if( $.browser.safari ) $(document.documentElement) .addClass("e-webkit-mac");
  	if( $.browser.mozilla ) $(document.documentElement).addClass("e-gecko-mac");
  	if( $.browser.opera ) $(document.documentElement).addClass("e-opera-mac");
	}

})(jQuery);

/* Global browsers definition (end) */
/* Global base events definition */

(function($) {

	$(document).ready(function(){

	  $(".hovered, .j-hovered")
  	  .live("mouseover", function(){
    		$(this).addDependClass("hover");
  	  })
  	  .live("mouseout", function(){
    		$(this).removeDependClass("hover");
  	  })

  	$(".j-collapse")
  	  .live("click", function(){
  	    $(this).parents(".j-collapsed").toggleDependClass("collapsed");
  	    return false;
  	  })

	});

})(jQuery);

/* Global base events definition (end) */
/* Placeholder for inputs */

/* Button object */

(function($) {

  var buttons = new Array();

  this.b_button_OPTIONS = {
    selfInit: false,
    defaultName: "button",
    className: "b-button",
    formClass: "b-button_form",
    template:
      '<div class="b-button" bindEvents="mousedown,mouseup,mouseover,mouseout">' +
        '<table><tr><td>' +
          '<div class="b-button-bg">' +
            '<i class="l g-png"></i><i class="r g-png"></i>' +
          '</div>' +
          '<div class="b-button-text" attachData="value">' +
            '<i class="b-button-icon g-png"></i>' +
          '</div>' +
        '</td></tr></table>' +
      '</div>'
  };

  this.b_button_IDs = 0;

  if(b_button_OPTIONS.selfInit){
    //Self-init:
    $(document).ready(function(){
      GLOBAL.reInit(function(){
        b_button_init();
      })
    })
  }

  // Force init:
  this.b_button_init = function(str){
    if(str){
      var obj = document.getElementById(str);
      if(obj){
        var jobj = $(obj);
        if(jobj.find(".b-button_form").length)
          new b_button_group(obj);
        else
          new b_button(obj);
      }
    } else {

      $("*[buttonType=group]").each(function(){
        new b_button_group(this);
      })
      $("button[buttonType]").each(function(){
        new b_button(this);
      })

    }
  }


  this.b_button = function(){
    return this.init.apply(this, arguments);
  }

  b_button.prototype = {
    init: function(obj, options){
      this.options = $.extend(b_button_OPTIONS, options ? options : {});

      this.domNode = $(obj);

      var b = this.isExist();
      if(b){ return b; }

      this.is = {
        prevent: true,
        stateBubble: true,
        template: false
      };

      if(this.domNode.find("." + this.options.className).length)
        this.is.template = true;

      this.old = {} // save here old states if it changes

      this.o = {
        type: this.domNode.attr("buttonType"),
        confirm: this.domNode.attr("confirm")
      };

      this.checked = false;
      this.name = this.domNode.attr("name") ? this.domNode.attr("name") : this.options.defaultName + b_button_IDs++;

      // events for append
      this.e = {
        list: ["mousedown", "mouseup", "mouseover", "mouseout"],
        onstatechange: this.domNode.attr("onstatechange") ? this.domNode.attr("onstatechange") : function(){}
      };


      if(!this.is.template){

        this.value = this.domNode.html();

        // data for append
        this.d = {
          value: this.value
        }

        var checkedLabel = this.domNode.attr("checkedLabel");
        if(checkedLabel && checkedLabel.length){
          this.d.value = '' +
            '<span class="off">' + this.value + '</span>' +
            '<span class="on">' + checkedLabel + '</span>'
        }

        this.domNode
          .removeAttr("buttonType")
          .addClass(this.options.formClass)
          .html(this.parse(this.options.template)) // parse nodes and append events and data

      } else {
        this.parse(this.domNode);
      }

      this.bindEvents();

      if(this.domNode.get(0).disabled) // define disabled state
        this.setClass(this.domNode, "disabled")

      var checked = this.domNode.attr("checked");
      if(checked && (checked == 'true' || checked == 'checked') && this.o.type != "simple"){ // define checked state
        this.is.stateBubble = false;
        this.state("checked", true, true)
      }

      this.postCreate();

      obj.buttonHandler = this;
      buttons.push(this);
    },

    isExist: function(){
      for (var i=0; i < buttons.length; i++) {
        if(buttons[i].domNode.get(0) == this.domNode.get(0))
          return buttons[i];
      };
      return false;
    },

    postCreate: function(){

      var _on = this.domNode.find(".on");
      var _off = this.domNode.find(".off");
      var w = {
        on: _on.css({ display: "inline-block" }).width()+1,
        off: _off.css({ display: "inline-block" }).width()+1
      }
      _on.removeAttr("style");
      _off.removeAttr("style");

      if(w.on >= w.off){
        _on.css({ width: w.on });
        _off.css({ width: w.on });
      } else {
        _on.css({ width: w.off });
        _off.css({ width: w.off });
      }

    },

    bindEvents: function(){
      var $this = this;

      for (var i=0; i < this.e.list.length; i++) {
        var _event = this.e.list[i];
        if(this[_event]){

          (function(_event){
            $this.domNode.bind(_event, function(){
              $this[_event].apply($this, $this.e[_event] ? [$this.e[_event]] : null)
            });

            if(_event == 'mouseup')
              $(document).bind(_event, function(){
                $this[_event].apply($this, $this.e[_event] ? [$this.e[_event]] : null)
              })

          })(_event)

        }
      };

    },

    mousedown: function(node){
      var node = node ? node : this.domNode;

      switch(this.o.type){
        case 'trigger':
          if(this.checked){
            this.is.prevent = false;
          } else {
            this.state("checked", true);
            this.is.prevent = true;
          }
          break;

        case 'switcher':
          if(!this.checked)
            this.state("checked", true);

          break;

        case 'simple':
        default:
          this.is.prevent = false;
          this.setClass(node, "down");
          break;
      }

    },

    mouseup: function(node){
      var node = node ? node : this.domNode;

      if(!this.is.prevent){
        switch(this.o.type){
          case 'trigger':
            if(this.checked) this.state("checked", false);
            break;

          case 'trigger':

            break;

          case 'simple':
          default:
            this.setClass(node, "down", false);
            break
        }
      }

    },

    mouseover: function(node){
      var node = node ? node : this.domNode;
      this.setClass(node, "hover");
    },

    mouseout: function(node){
      var node = node ? node : this.domNode;
      this.setClass(node, "hover", false);
    },

    onstatechange: function(){
    },

    _onstatechange: function(){
      this.onstatechange.apply(this);
      if($.isFunction(this.e.onstatechange))
        this.e.onstatechange.apply(this)
      else
        eval(this.e.onstatechange)
    },

    parse: function(tpl){

      function bind( dom ){
        dom.filter("[bindEvents]").add(dom.find("*[bindEvents]")).each(function(){
          var node = $(this);
          jQuery.each(node.attr("bindEvents").split(/ *, */), function(){
            var _event = this.toString();
            $this.e[_event] = node;
          });
          node.removeAttr("bindEvents");
        })
      }

      function append( dom ){
        dom.filter("[attachData]").add(dom.find("*[attachData]")).each(function(){
          var node = $(this);
          jQuery.each(node.attr("attachData").split(/ *, */), function(){
            var _type = this.toString();
            node.append($this.d[_type]);
            $this.o[_type] = node;
          });
          $(this).removeAttr("attachData");
        })
      }

      var $this = this;

      switch(typeof tpl){

        case 'string':
          var tpl = $(tpl);
          bind(tpl);
          append(tpl);
          break;

        case 'object':
          bind(tpl);
          break;
      }

      return tpl;
    },

    setClass: function(node, sClass, b){
      if(b === false) node.removeClass(this.options.className + "_" + sClass);
      else node.addClass(this.options.className + "_" + sClass);
    },

    state: function(name, value, force){
      this.is.prevent = true;

      switch(name){
        case 'checked':
          if(force || !this.o.confirm || (this.o.confirm && confirm(this.o.confirm))){
            this.old[name] = this[name];
            this[name] = value;

            if(this.old[name] != this[name] && this.is.stateBubble)
              this._onstatechange()
            if(!this.is.stateBubble)
              this.is.stateBubble = true;

            if(!value)
              this.setClass(this.e.mouseup, "down", false);
            else
              this.setClass(this.e.mouseup, "down");
          }
          break;

        case 'disabled':

          this.old[name] = this[name];
          this[name] = value;

          if(value){
            this.setClass(this.domNode, name)
            this.domNode.attr(name, true)
          } else {
            this.setClass(this.domNode, name, false)
            this.domNode.removeAttr(name)
          }

          break;
      }
    }


  }

  function b_button_group(){
  	return this.init.apply(this, arguments);
  }

  b_button_group.prototype = {
    init: function(obj){
      var $this = this;

      this.domNode = $(obj);
      this.is = {
        template: false
      }

      if(this.domNode.find("."+ b_button_OPTIONS.className +"_left, ."+ b_button_OPTIONS.className +"_center, ."+ b_button_OPTIONS.className +"_right").length)
        this.is.template = true;

      this.e = {
        onstatechange: this.domNode.attr("onstatechange") ? this.domNode.attr("onstatechange") : function(){}
      };

      this.buttons = new Array();

      if(!this.is.template){
        var buttons = this.domNode.addClass(b_button_OPTIONS.className + "_group").find("button[buttonType]");

        buttons.each(function(i){
          var button = new b_button(this);
          var sClass = "center";
          if(i == 0) sClass = "left";
          if(i == buttons.length - 1) sClass = "right";

          if(buttons.length != 1)
            button.domNode.wrap($("<div>").addClass(b_button_OPTIONS.className + "_" + sClass))

          $this.buttons.push(button);
        })

      } else {
        this.domNode.find("."+ b_button_OPTIONS.className +"_form").each(function(){
          $this.buttons.push(this.buttonHandler);
        })
      }



      if(this.buttons.length != 1)
        this.bindEvents();
    },

    bindEvents: function(){
      $this = this;
      $.each(this.buttons, function(){
        this.onstatechange = function(){
          $this.onclick(this)
        };
      })
    },

    onclick: function(obj){
      var $this = this;

      state = {};
      state[obj.name] = true;
      state.new_state = obj.name;

      $.each(this.buttons, function(){
        if(this != obj){
          this.is.stateBubble = false;
          this.state("checked", false);
          if(this.old.checked == true && this.checked == false) {
            state[this.name] = false;
            state.old_state = this.name;
          }
        }
      })
      obj.is.prevent = true;


      if($.isFunction(this.e.onstatechange))
        this.e.onstatechange.apply(this)
      else
        (function(state){
          eval($this.e.onstatechange)
        }).call(obj, state)

    }

  };

})(jQuery);

/* Button object (end) */

var Calendar = classDraggable.extend({
	_default: { //current date
		year: (new Date()).getFullYear(),
		month: (new Date()).getMonth()+1,
		submit: "."
	},
	oninit: function(){
		var oThis = this;
		this.hSetting = {};
		jQuery.extend(this.hSetting, this._default, arguments[1] ? arguments[1] : {});

		jQuery.extend(this.is, {
			animate: false,
			controls: false,
			controlsState: false
		});

		function getDateText(date){
			return date.getDate() + ' ' + oThis.months.second[date.getMonth()] + ', ' + oThis.week_days[date.getDay()];
		}

		this.months = {
			first: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
			second: ['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря']
		};
		this.week_days = ['воскресенье', 'понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота'];

		this.aMonths = [];

		this.ptr.append("<div class='calendar-current'>" + getDateText(new Date()) + "</div>");
		this.ptr.append(
			"<div class='calendar-body'>" +
				"<div class='calendar-button calendar-button-left'><i></i></div>" +
				"<div class='calendar-button calendar-button-right'><i></i></div>" +
				"<div class='calendar-week'></div>" +
			"</div>");
		this.ptr.append(
			"<div class='calendar-controls'><div class='calendar-control-in'>" +
				"<span class='calendar-clear'>Отменить</span>" +
				"<button type='submit' id='editor_submit' class='b-button_form' buttontype='simple'>" +
				  "<div class='b-button'>" +
				    "<table><tbody><tr><td>" +
				      "<div class='b-button-bg'>" +
				        "<i class='l g-png'/><i class='r g-png'/>" +
				      "</div>" +
				      "<div attachdata='value' class='b-button-text'>" +
				        "<i class='b-button-icon g-png'/>" +
				        "Показать" +
				      "</div>" +
				    "</td></tr></tbody></table>" +
				  "</div>" +
				"</button>" +
			"</div></div>");

		this.ptr.append(
			'<form class="calendar-form" method="get" action="' + this.hSetting.submit + '">' +
				'<input type="hidden" name="dates" />' +
				'<input type="hidden" name="month" />' +
				'<input type="hidden" name="year" />' +
			'</form>');

		this.ptr = this.ptr.find("div.calendar-body");
		var curr = this.createMonth(this.hSetting);
		this.ptr.append(curr.ptr);

		if(curr.count > 35) {
			this.ptr.css({ height: 180 });
		}

		curr.current = true;
		this.aMonths.push(curr);
		this.redraw(curr);
		b_button_init();
		this.resize();
	},
	resize: function(){
		var _offset = this.ptr.offset();

		this.current = this.getCurrent();
		for(var key in this.current.items){
			var ptr = this.current.items[key].ptr;
			var _o = ptr.offset();
			this.current.items[key].left = _o.left - _offset.left;
			this.current.items[key].top = _o.top - _offset.top;
		}

		this.cx = _offset.left;
		this.cy = _offset.top;
	},
	events: function(){
		var oThis = this;
		this.ptr.find("div.calendar-button").mousedown(function(){
			jQuery(this).addClass("calendar-button-down");
		}).mouseup(function(evt){
			jQuery(this).removeClass("calendar-button-down");
			if(!oThis.is.animate) {
				oThis.onclick(this, evt);
			}
		});

		jQuery(document)
			.mousemove(function(evt){
				oThis._onmousemove(evt);
				return false;
			});

		var jsbutton = this.ptr.parents("div.calendar").find("button").click(function(){
			var form = oThis.ptr.parents("div.calendar").find("form.calendar-form");

			var dates = '';
			for (var i=0; i < oThis.aMonths.length; i++) {
				for(var k in oThis.aMonths[i].items){
					if(oThis.aMonths[i].items[k].selected){
						var d = new Date(k);
						dates += oThis.dateString(d) + ',';
					}
				}
			}
			dates = dates.replace(/,$/, '');

			var curr = oThis.getCurrent();
			form.
				find("input[name='dates']").val(dates);
			form.
				find("input[name='month']").val(curr.date.getMonth()+1);
			form.
				find("input[name='year']").val(curr.date.getFullYear());

			form.submit();

		});

		this.ptr.parents("div.calendar").find("span.calendar-clear").click(function(){
			oThis.empty();
			oThis.redraw(oThis.getCurrent());
		});

		jQuery(window).resize(function(){
			oThis.resize();
		});

		this.oArrow = this.ptr.parents("div.calendar").find("div.calendar-week").click(function(evt){
			oThis.selectByWeek(evt);
		});
	},
	onmousedown: function(evt){
		this.resize();

		var _s = this.getDay(this.current, evt.pageX-this.cx, evt.pageY-this.cy);
		if(_s){
			if(!evt.shiftKey) {
				this.empty(this.current);
			}

			this.start = new Date(_s);

			var curr = this.current.items[_s];
			if(curr.selected){
				curr.ptr.removeClass("selected");
				curr._selected = false;
				this.remove = true;
			} else {
				curr.ptr.addClass("selected");
				curr._selected = true;
				this.remove = false;
			}
			this.redraw(this.current);
			this.is.controls = true;
		}
	},
	_onmousemove: function(evt){
		var week = this.getWeek(this.current, evt.pageY - this.cy);
		if(week) {
			this.oArrow.css({ left: week.left-20, top: week.top }).show();
		} else {
			this.oArrow.hide();
		}
	},
	onmousemove: function(evt, x, y){
		function _mark(curr, obj){
			if(obj.remove){
				curr.ptr.removeClass("selected");
				curr._selected = false;
			} else {
				curr.ptr.addClass("selected");
				curr._selected = true;
			}
		}

		function _back(curr){
			curr._selected = curr.selected;
			if(curr.selected) {
				curr.ptr.addClass("selected");
			} else {
				curr.ptr.removeClass("selected");
			}
		}

		if(this.start){
			this.end = new Date(this.getDay(this.current, x, y));
			for(var k in this.current.items){
				var d = new Date(k);
				var curr = this.current.items[k];
				if(this.start < this.end) {
					if(d >= this.start && d <= this.end) {_mark(curr, this);}
					else{ _back(curr);}
				} else {
					if(d <= this.start && d >= this.end) {_mark(curr, this);}
					else {_back(curr);}
				}
			}
			this.redraw(this.current);
		}
	},
	onmouseup: function(){
		for(var k in this.current.items){
			var curr = this.current.items[k];
			curr.selected = curr._selected ? curr._selected : false;
		}
		this.redraw(this.current);

		if(this.is.controls) {
			this.showControls();
		}

		this.start = null;
		this.end = null;
	},
	onclick: function(obj, evt){
		function setCurrent(month){
			for (var i=0; i < oThis.aMonths.length; i++) {
				oThis.aMonths[i].current = false;
			}
			month.current = true;
		}
		function exist(hDate){
			var date = new Date(hDate.year, hDate.month-1);
			for (var i=0; i < oThis.aMonths.length; i++) {
				if(oThis.aMonths[i].date.valueOf() == date.valueOf()) {
					return true;
				}
			}
			return false;
		}

		function getMonth(hDate){
			var date = new Date(hDate.year, hDate.month-1);
			for (var i=0; i < oThis.aMonths.length; i++) {
				if(oThis.aMonths[i].date.valueOf() == date.valueOf()) {
					return oThis.aMonths[i];
				}
			}
		}
		var oThis = this;
		this.is.animate = true;

		var direction = 1;
		if(jQuery(obj).is(".calendar-button-left")) {
			direction = -1;
		}

		this.current = this.getCurrent();
		this.current.ptr.css({ position: "absolute", left: 0, top: 0 });
		var date = new Date(this.current.date.getFullYear(), this.current.date.getMonth()+direction);
		var newMonth = { year: date.getFullYear(), month: date.getMonth()+1 };
		if(!exist(newMonth)){
			newMonth = this.createMonth(newMonth);
			newMonth.ptr.css({ position: "absolute", left: direction*240, top: 0 });
			this.ptr.append(newMonth.ptr);
		} else {
			newMonth = getMonth(newMonth);
		}

		this.redraw(newMonth);

		newMonth.ptr.show();
		this.current.ptr.animate({ left: -1*direction*240 }, function(){
			jQuery(this).hide();
		});
		newMonth.ptr.animate({ left: 0 }, function(){
			oThis.is.animate = false;
		});
		if(newMonth.count != this.current.count){
			if(this.current.count < newMonth.count) {
				this.ptr.animate({ height: 180 });
			} else {
				this.ptr.animate({ height: 160 });
			}
		}

		this.aMonths.push(newMonth);

		setCurrent(newMonth);

	},

	showControls: function(){
		if(!this.is.controlsState){
			this.is.controlsState = true;
			this.ptr.parents("div.calendar").find("div.calendar-controls").css({ height: 0, overflow: "hidden" }).show().
				animate({ height: 40 });
		}
	},
	selectByDay: function(day, evt){

		if(!evt.shiftKey) {
			this.empty(this.current);
		}

		var k;
		jQuery(day).parent().find("li").each(function(i){
			if(day == this) {
				k = i;
			}
		});
		k++;
		if(k == 7) {k = 0;}
		this.current = this.getCurrent();
		for(var key in this.current.items){
			var date = new Date(key);
			if(date.getDay() == k){
				this.current.items[key]._selected = true;
				this.current.items[key].ptr.addClass("selected");
			}
		}
		this.is.controls = true;

		this.redraw(this.current);
		this.onmouseup();
	},

	selectByWeek: function(evt){
		var week = this.getWeek(this.current, evt.pageY - this.cy);

		if(!evt.shiftKey) {
			this.empty(this.current);
		}

		for(var key in this.current.items){
			if(this.current.items[key].top == week.top){
				this.current.items[key]._selected = true;
				this.current.items[key].ptr.addClass("selected");
			}
		}

		this.is.controls = true;

		this.redraw(this.current);
		this.onmouseup();

	},
	redraw: function(month){
		function check(d){
			return month.items[d.toString()] && month.items[d.toString()].ptr.is('.selected');
		}

		function add(){
			if(arguments.length > 1){
				if(d.getDay() == arguments[0]) {sClass += 'o';}
				else {add(arguments[1]);}
			} else {
				var _d = new Date(d.getFullYear(), d.getMonth(), d.getDate()+arguments[0]);
				if(check(_d)) {sClass += 'f';}
				else {sClass += 'o';}
			}
		}

		function removeClasses(day){
			var s = day.ptr.is(".selected");
			day.ptr.attr("class", day.sClass);
			if(s) {day.ptr.addClass("selected");}
		}

		for(var k in month.items){
			var curr = month.items[k];
			removeClasses(curr);
			if(curr.ptr.is(".selected")){
				var d = new Date(k);

				var sClass = '';
				add(-7);
				add(0, 1);
				add(7);
				add(1,-1);
				add(1,-8);

				curr.ptr.addClass(sClass);

			}
		}
	},
	empty: function(month){
		this.hSetting.dates = [];
		for (var i=0; i < this.aMonths.length; i++) {
			for(var k in this.aMonths[i].items){
				var curr = this.aMonths[i].items[k];
				curr.selected = curr._selected = false;
				curr.ptr.removeClass("selected");
			}
		}
	},

	getCurrent: function(){
		for (var i=0; i < this.aMonths.length; i++) {
			if(this.aMonths[i].current){
				return this.aMonths[i];
			}
		}
		return this.aMonths[0];
	},
	getDay: function(month, x, y){
		for(var k in month.items){
			if(((x >= month.items[k].left && x < month.items[k].left+20) || (x === null)) && y >= month.items[k].top && y < month.items[k].top+20) {
				return k;
			}
		}
	},
	getWeek: function(month, y){
		var k = this.getDay(month, null, y);
		return k ? month.items[k] : null;
	},

	createMonth: function(oDate){
		var oThis = this;
		function getDate(sDate){
			if(oThis.hSetting.dates) {
				for (var i=0; i < oThis.hSetting.dates.length; i++) {
					if(oThis.hSetting.dates[i] == sDate) {return true;}
				}
			}
			return false;
		}

		function events(month){
			month.ptr.find("ul.calendar-week-days li").click(function(evt){
				oThis.selectByDay(this, evt);
			});
			return month;
		}

		var now = new Date();
		now = new Date(now.getFullYear(), now.getMonth(), now.getDate());
		var date = new Date(oDate.year, oDate.month-1, 1);
		var next = new Date(oDate.year, oDate.month, 0);
		var month = {
		 	ptr: jQuery("<div class='calendar-month'><div class='calendar-month-in'><h1>" + this.months.first[date.getMonth()] + ((date.getFullYear() != now.getFullYear()) ? (', ' + date.getFullYear()) : '') + "</h1><ul class='calendar-week-days'><li>ПН</li><li>ВТ</li><li>СР</li><li>ЧТ</li><li>ПТ</li><li class='calendar-free'>СБ</li><li class='calendar-free'>ВС</li></ul><ul class='calendar-days'></ul></div></div>"),
			date: new Date(date.getFullYear(), date.getMonth()),
			items: {},
			current: false
		};
		var days = month.ptr.find("ul.calendar-days");

		date.setDate(- (date.getDay() === 0 ? 7 : date.getDay()) + 1);

		var diff = next.valueOf() - date.valueOf();
		var to = Math.round(diff/1000/60/60/24 + (7-(next.getDay() === 0 ? 7 : next.getDay())));
		month.count = to;

		for (var i=0; i < to; i++) {
			var sId = '';
			var sClass = '';
			date.setDate(date.getDate()+1);
			if(date.valueOf() == now.valueOf()) {
				sId += " id='calendar-current'";
			}

			if(date.valueOf() < now.valueOf()) {
				sClass += " past";
			}

			if(date.getMonth() != oDate.month-1){
				sClass += " another";
			}

			var day = jQuery("<li" + sId + " class='" + sClass + "'>" + (sId.length ? '<b>' : '') + date.getDate() + (sId.length ? '</b>' : '') + "</li>");
			var sDate = this.dateString(date);
			var bCheck = getDate(sDate);
			if(bCheck) {day.addClass("selected");}
			month.items[date.toString()] = { ptr: day, sClass: sClass, selected: bCheck ? true : false, _selected: bCheck ? true : false };
			days.append(day);
		}
		return events(month);

	},

	dateString: function(date){
		return ( date.getFullYear() + "-" + (((date.getMonth()+1) < 10) ? ('0' + (date.getMonth()+1)) : (date.getMonth()+1)) + "-" + ((date.getDate() < 10) ? ('0' + date.getDate()) : date.getDate()));
	}

});
