var ms = {};
(
	function() {
		this.errors = '';
	}
)();
window.addEvent('domready', function() {
    ms.errors = new ms.Error(); 
});
ms.getNum = function(value) {
	return value === null || isNaN(parseInt(value, 10)) ? 0 : parseInt(value, 10);
};
ms.Location = function(link, question) {
	if ( question && !confirm(question) ) {
		return;
	}
  if ( link ) {
	  document.location.href = link;
  }
};
ms.Translate = function(str, question) {
  var re = /[\/"'`~<>\\*?|,.{}\[\]\(\)@!#$%^&\-=+;:\№]/g; 
  str = str.replace(re, "");
  var arr_rus = ["А","Б","В","Г","Д","Е","Ё","Ж","З","И","Й","К","Л","М","Н","О","П","Р","С","Т","У","Ф","Х","Ц","Ч","Ш","Щ","Э","Ю","Я","а","б","в","г","д","е","ё","ж","з","и","й","к","л","м","н","о","п","р","с","т","у","ф","х","ц","ч","ш","щ","ь","ы","ъ","э","ю","я"," "];
  var arr_tran = ["a","b","v","g","d","e","e","zh","z","i","i","k","l","m","n","o","p","r","s","t","u","f","h","c","ch","sh","sh","e","yu","ya","a","b","v","g","d","e","e","zh","z","i","i","k","l","m","n","o","p","r","s","t","u","f","h","c","ch","sh","sh","","i","","e","yu","ya","_"];
  
  var result = "";
  var char;
  for (var i = 0; i < arr_rus.length; i++) {
    str = (str.split(arr_rus[i])).join(arr_tran[i]);
  }
  return str;
};
ms.TranslateTO = function(str, el) {
  str = ms.Translate(str, el);
  $(el).set('value', str); 
};
Elements.implement({
	checkElement: function(checked) {
		var count_checked = 0;
		if ( checked ) {
			this.each(function(item){item.set('checked', 'checked'); count_checked ++;});
		} else {
			this.each(function(item){item.set('checked', '');});
		}
		return count_checked;
	}
});
Element.implement({
	enabledElement: function(condition) {
		if (condition) {
			this.set('disabled', '');
		} else {
			this.set('disabled', 'disabled');
			this.set('value', '');
		}
	},
	showElement: function(show) {
		if ( show ) {
			this.setStyles({'display': 'block', 'visibility': 'visible'});
		} else {
			this.setStyles({'display': 'none', 'visibility': 'hidden'});
		}
	}
});
ms.Error = new Class({
	Implements: [Options],
	options: {
		nameBlockError: 'block_error'
	},
	initialize: function(options) {
		this.setOptions(options);
		this.error = new Hash();
		this.update();
	},
	add: function(id, text) {
		this.error.set(id, text);
	},
	del: function(id) {
		this.error.erase(id);
	},
	update: function() {
		if ( $(this.options.nameBlockError) == null ) return;
		var block = $(this.options.nameBlockError);
		var n = 0;
		block.getElements('span').each(function(v) {
			this.add(n, v.get('html'));
			n++;
		}.bind(this));
    block.getElements('span').dispose();
		block.getElements('p').dispose();
		if (this.error.getLength() > 0) {
			this.error.each(function(v) {
				new Element('p').set('html', v).inject(block);
			});
			block.setStyle('display', 'block');
		}
		else {
			block.setStyle('display','none');		
		}
	}
});
ms.Editor = new Class({
	Implements: [Options],
	options: {
		id: '',
		type: '',
		height: '500px',
		options_editor: {
			type_code: 'htmlmixed',
			contents_css: ''
		}
	},
	initialize: function(options) {
		this.setOptions(options);
		
		switch(this.options.type) {
        case 'ckeditor':
        	new Asset.javascript('/editors/ckeditor/ckeditor.js?t=B1GG4Z6');
        	this.loadCKEDITOR();
          break;
        case 'code_mirror':
          this.path = "/editors/code_mirror/";
        	var div = new Element('div', {'class': 'CodeMirror-border'});
        	div.inject($(this.options.id), 'after');
        	div.adopt($(this.options.id));
          
          new Asset.css(this.path + 'lib/codemirror.css');
        	new Asset.javascript(this.path + 'lib/codemirror.js', {
            onLoad: function(){
              this.loadCodeMirror();
            }.bind(this)
          });
          break;
		}
	},
	getValue: function() {
		var value = '';
		switch(this.options.type) {
        case 'ckeditor':
        	value = this.editor.instances[this.options.id].getData();
            break;
        case 'code_mirror':
        	value = this.editor.getValue();
		}
		return value;
	},
	loadCKEDITOR: function() {
		if ( typeof(CKEDITOR) != "object" ) {
			setTimeout(function(){this.loadCKEDITOR();}.bind(this), 10);
		} else {
			this.editor = CKEDITOR;
			this.editor.replace(this.options.id, 
					{ "height": this.options.height,
					  "contentsCss": this.options.options_editor.contents_css,
            "scayt_autoStartup": false
					});
		}
	},
	loadCodeMirror: function() {
    switch(this.options.options_editor.type_code) {
	    case 'htmlmixed':
	    default:
	      var mode = "text/html";
        var files_js = ["xml/xml.js", "javascript/javascript.js", "css/css.js", "htmlmixed/htmlmixed.js"];
	      break;
	    case 'css':
	      var mode = "text/css";
        var files_js = ["css/css.js"];
	      break;
	    case 'js':
        var mode = "text/javascript";
	      var files_js = ["javascript/javascript.js"];
	      break;
		}
    new Asset.css(this.path + 'theme/default.css');
    var length = files_js.length;
    var i = 0;
    files_js.each(function(js) {
      new Asset.javascript(this.path + 'mode/' + js, {
            onLoad: function() {
              i++;
              if ( i == length ) {this.setCodeMirror(mode)};
            }.bind(this)});
    }.bind(this));
	},
  setCodeMirror: function(mode) {
    this.editor = CodeMirror.fromTextArea($(this.options.id), {
      mode: mode, 
      tabMode: "indent",
      lineNumbers: true
    });
  }
});
ms.Form = new Class ({
	Implements: [Options],
	options: {
		validator: {},
		action: '',
		apply: '&m=apply',
		method: 'post',
		button_apply: 'button_apply',
		editors: []
	},
	initialize: function(form, options) {
		this.setOptions(options);
		if ( typeof(form) == "object" ) {
			this.form = form;
		} else {
			this.form = $(form);
		}
		this.form.set({method: this.options.method, name: form, action: this.options.action});
		if ( $(this.options.button_apply) ) {
			$(this.options.button_apply).addEvent('click', function(){
				this.apply();
			}.bind(this));
		}
		if ( this.options.validator ) {
			this.validator = new ms.Validator({form: this.form});
			Object.map(this.options.validator, function(val, key) {
				this.validator.addElement(key, val);
			}.bind(this));
		}
	},
	submit: function(action, question) {
		var questions = [];
		questions['delete'] = 'Вы действительно хотите удалить эти объекты?';
		if ( question && !confirm(questions[question]) ) {
			return;
		}
		if ( action ) {
			this.form.action = action;
		} else {
			this.form.action = this.options.action;
		}
    if ( this.editors ) {
      this.editors.each(function(editor) {
      this.form.getElement('#'+editor.options.id).set('value', editor.getValue());
    }.bind(this));
    }
    if ( this.validator.validator.validate() ) {
		  this.form.submit();
    }
	},
	setAction: function(action) {
		this.options.action = action;
	},
	setEditors: function(editors) {
		this.editors = editors;
	},
	apply: function(apply) {
    if ( !apply ) {
			apply = this.options.apply;
		}
    if ( this.editors ) {
		  this.editors.each(function(editor) {
			  this.form.getElement('#'+editor.options.id).set('value', editor.getValue());
		  }.bind(this));
    }
    if ( this.validator.validator.validate() ) {
      this.form.action = this.options.action + apply;
      var myResult = new Element('div');
      new Form.Request(this.form, myResult, {
        resetForm: false,
        onSuccess: function(response) {
          var result = JSON.decode(response.get('text'));
          if ( result.report == 'true' ) {
            if ( typeof(result.url) == 'string' && result.url != '' ) {
              document.location.href = result.url;
            } else {
              alert('Сохранено успешно!');
            }
          } else {
            alert(result.report);
          }
        },
        onFailure: function() {
          alert('Ошибка при сохранении!');
        }
      }).send();
    }
    /*
		var req = new Request.HTML({
		url: this.options.action + apply, 
		method: 'post',
		onComplete: function(responseTree, responseElements, response) { 
      var result = JSON.decode(response);
			if ( result.report == 'true' ) {
				if ( typeof(result.url) == 'string' && result.url != '' ) {
          document.location.href = result.url;
				} else {
					alert('Сохранено успешно!');
				}
			} else {
				alert(result.report);
			}
		}, onFailure: function() {
			alert('Ошибка при сохранении!');
		}
		}).post(this.form);
    */
	}
});
ms.Validator = new Class({
	Implements: [Options],
	options: {
		styleElementPass: {border: '1px solid #00ff06'},
		styleElementFail: {border: '1px solid #ff0000'},
		form: ''
	},
	initialize: function(options) {
		this.setOptions(options);
		this.Error = ms.errors;
		this.validator = new Form.Validator(this.options.form, {
			stopOnFailure: true,
			evaluateFieldsOnBlur: false,
			onFormValidate: function(ok) {
				
			},
			onElementFail: function(el, validator) {
				el.setStyles(this.options.styleElementFail);
				this.Error.add(el.get('id'), this.validator.getValidator(validator[0]).getError(el));
				this.Error.update();
			}.bind(this),
			onElementPass: function(el) {
				el.setStyles(this.options.styleElementPass);
				this.Error.del(el.get('id'));
				this.Error.update();
			}.bind(this)
		});
		
		this.add({
			class_name: 'is_empty',
			errorMsg: function(element){
				return $(element).get('title')+': не может быть пустым!';
			},
			test: function(element){
				return ($(element).get('value') != '');
			}
		});
		this.add({
			class_name: 'alpha_num_digits',
		    errorMsg: function(element){
				return $(element).get('title')+': строка содержит недопустимые символы. Используйте латинские буквы, цифры, символы - и _';
		    },
		    test: function(element){
          if(!element.get('value')) return true;
				  return (/^[_\-a-zA-Z0-9]+$/).test(element.get('value'));
		    }
		});
    this.add({
      class_name: 'num',
        errorMsg: function(element){
        return $(element).get('title')+': строка содержит недопустимые символы. Используйте только цифры';
        },
        test: function(element){
          if(!element.get('value')) return true;
          return (/^[0-9]+$/).test(element.get('value'));
        }
    });
    this.add({
      class_name: 'email',
        errorMsg: function(element){
        return $(element).get('title')+': некоректно введен E-Mail';
        },
        test: function(element){
        var template = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z])+$/;
        return template.test(element.get('value'));
        }
    });
		this.add({
			class_name: 'min_length',
		    errorMsg: function(element, props){
		        if ($type(props.min_length))
		            return $(element).get('title')+': минимальное количество символов ' + props.min_length + ' (Вы ввели ' + element.value.length + ' символа).';
		        else return '';
		    },
		    test: function(element, props){
          if(!element.get('value')) return true;
		        return (element.value.length >= $pick(props.min_length, 0));
		    }
		});
		
	},
	addElement: function(element, options) {
		options.valid.each(function(val, key) {
			this.options.form.getElement('#'+element).addClass(val);
		}.bind(this));
		if ( options.add ) {
			if ( options.add.file ) {
				this.addAJAX(options.add);
			} else {
				this.add(options.add);
			}
		}
	},
	add: function(options) {
		this.validator.add(options.class_name,{
			errorMsg: function(element, props){
				if ( options.error_msg ) {
					return options.error_msg;
				} else {
					return options.errorMsg(element, props);
				}
			},
			test: function(element, props){
				return options.test(element, props);
			}
		});
	},
	addAJAX: function(options) {
    this.add({
		  class_name: options.class_name,
	    errorMsg: function(element) {
			  var error_msg = 'такое значение уже существует!';
			  if ( options.error_msg ) {
				  error_msg = options.error_msg;
			  }
	      return $(element).get('title') + ': ' + error_msg;
	    },
	    test: function(element) {
	    	var value = $(element).get('value');
	    	if ( value == options.old_value ) return true;

	      var data = 'value=' + value;
	      if ( options.data ) {
	      	data = data + options.data;
	      }
			  var req = new Request.HTML({
				  url: options.file, 
				  method: 'get',
				  async: false,
				  data: data,
				  onComplete: function(responseTree, responseElements, response) {
            var result = JSON.decode(response);
					  if ( result.report == 'true') {ret = true;}
					  else if ( result.report == 'false' ) {ret = false;}
            else {
              options.error_msg = result.report;
              ret = false;
            }
				  }
			  }).send();
			  return ret;
	    }
		});
	}
});
ms.Position = new Class({
	Implements: [Options],
	options: {
		horizontal: 'center center',
		vertical: 'center center',
    is_scroll: false,
    is_menu_vertical: false,
		parent: null
	},
	initialize: function(element, relative, options) {
		this.setOptions(options);
		this.element = element;
		this.relative = relative;
    this.scroll_top = 0;
		if ( !this.options.parent ) {
			this.options.parent = $(document.body);
		} else {
			this.options.parent = $(this.options.parent);
		}
		
    this.c_relative = {};
    this.c_element = {};
    this.c_parent = {};
		this.c_relative.position = {x: 0, y: 0};
    this.c_relative.position_s = relative.getPosition();
    this.c_relative.size = relative.getSize();
    this.c_element.size = element.getSize();
    this.c_parent.position = this.options.parent.getPosition();
    this.c_parent.size = this.options.parent.getSize();
		this.setPosition();
	},
	setPosition: function(position) {
		if( position ) {
			this.options.horizontal = position.x + ' 0';
			this.options.vertical = position.y + ' 0';
		}
    if ( this.options.is_scroll ) {
      this.scroll_top = this.options.parent.getScroll().y;
      this.c_relative.position.y = this.scroll_top;
      this.c_parent.position.y = this.scroll_top;
    }
		var temp_x = String.split(this.options.horizontal, ' ');
    var temp_y = String.split(this.options.vertical, ' ');
    if ( temp_x.length != 2 || temp_y.length != 2 ) {return false;}
    
		var pos_x = this.getPositionX(temp_x[1], temp_x[0]);
    var pos_y = this.getPositionY(temp_y[1], temp_y[0]);

		if ( (pos_x.right + this.c_relative.position_s.x) > (this.c_parent.position.x + this.c_parent.size.x) ) {
      if ( this.options.is_menu_vertical ) {
        pos_x.left = this.c_relative.position.x - this.c_element.size.x;
			} else {
				pos_x.left = (this.c_relative.position.x + this.c_relative.size.x) - this.c_element.size.x;
			}
    }
    
    if ( (pos_x.left + this.c_relative.position_s.x) < this.c_parent.position.x ) {
      if ( this.options.is_menu_vertical ) {
        pos_x.left = this.c_relative.position.x + this.c_element.size.x;
      } else {
        pos_x.left = this.c_relative.position.x;
      }
    }

    if ( (pos_y.bottom + this.c_relative.position_s.y) > (this.c_parent.position.y + this.c_parent.size.y) ) {
      if ( this.options.is_menu_vertical ) {
        pos_y.top = this.c_relative.position.y + this.c_relative.size.y;
      } else {
        pos_y.top = ((this.c_relative.position.y) + this.c_relative.size.y) - this.c_element.size.y;
      }
    }
    if ( (pos_y.top + this.c_relative.position_s.y) < this.c_parent.position.y ) {
		  pos_y.top = this.c_relative.position.y;
    }
    this.element.setStyles({'left': pos_x.left, 'top': pos_y.top});
	},
  getPositionX: function (el, re) {
    var left;
    var right;
    if ( !isNaN(parseInt(re, 10)) ) {
      left = parseInt(re, 10);
    } else {
      switch(re) {
        case 'right':
          left = this.c_relative.position.x + this.c_relative.size.x;
          break;
        case 'center':
          left = this.c_relative.position.x + Math.round(this.c_relative.size.x / 2);
          break;
        case 'left':
        default:
          left = this.c_relative.position.x;
          break;
      }              
    }
    if ( !isNaN(parseInt(el, 10)) ) {
      left += parseInt(el, 10);
      right = left + this.c_element.size.x;
    } else {
      switch(el) {
        case 'right':
          right = left + this.c_element.size.x;
          break;
        case 'left':
          right = left;
          left -= this.c_element.size.x;
          break;
        case 'center':
        default:
          left -= Math.round(this.c_element.size.x / 2);
          right = left + this.c_element.size.x;
          break;
      }              
    }
    return {left: left, right: right};
  },
  getPositionY: function (el, re) {
    var top;
    var bottom;
    if ( !isNaN(parseInt(re, 10)) ) {
      top = parseInt(re, 10);
    } else {
      switch(re) {
        case 'bottom':
          top = this.c_relative.position.y + this.c_relative.size.y;
          break;
        case 'center':
          top = this.c_relative.position.y + Math.round(this.c_relative.size.y / 2);
          break;
        case 'top':
        default:
          top = this.c_relative.position.y;
          break;
      }
    }
    if ( !isNaN(parseInt(el,10)) ) {
      top += parseInt(el, 10);   
      bottom = top + this.c_element.size.y;
    } else {
      switch(el) {
        case 'bottom':
          bottom = top + this.c_element.size.y;
          break;
        case 'top':
          bottom = top;
          top -= this.c_element.size.y;
          break;
        case 'center':
        default:
          top -= Math.round(this.c_element.size.y / 2);
          bottom = top + this.c_element.size.y;
          break;
      }                    
    }
    return {top: top, bottom: bottom};
  }
});
ms.Toolbar = new Class({
	Implements: [Options],
	options: {
		id: '',
		css_class: 'toolbar'
	},
	initialize: function(options) {
		this.setOptions(options);
		this.items = [];
    this.complete = [];
		this.n = 0;
		if ( this.options.id ) {
			this.toolbar = $(this.options.id);
		} else {
			this.toolbar = new Element('div');
		}
		this.toolbar.addClass(this.options.css_class);
	},
	add: function(items) {
    items.each(function(item) {
			this.n++;
			this.items[this.n] = item;
			this.toolbar.adopt(item.button);
		}.bind(this));
	},
  addComplete: function(name, items) {
    if ( typeof(this.complete[name]) == 'undefined' ) {
      this.complete[name] = [];
    }
    items.each(function(item) {
      this.n++;
      var id = this.n;
      this.complete[name].append([this.n]);
      this.items[this.n] = item;
      this.items[this.n].a.addEvent('click', function(){this.buttonClick(name, id);}.bind(this));
      this.toolbar.adopt(item.button);
    }.bind(this));
  },
  buttonClick: function(complete, id) {
    this.complete[complete].each(function(item_id) {    
      if ( typeof(this.items[item_id].box) != 'undefined' ) {
        if ( id == item_id ) {
          this.items[item_id].box.setShow(true);
        } else {
          this.items[item_id].box.setShow(false);
        }
      }
      if ( id == item_id ) {
        this.items[item_id].setActive(true);
      } else {
        this.items[item_id].setActive(false);
      }
    }.bind(this));
  }
});
ms.Button = new Class({
	Implements: [Options, Events],
	options: {
		css_class: 'bt_',
    label: '',
    enabled: true,
    active: false,
    show: true,
    title: '',
    image: '',
    href: '',
    action_button: ''
	},
	initialize: function(options) {
		this.setOptions(options);
		this.button = new Element('div', {'class': this.options.css_class+'container'});
		var href = 'javascript:void(0)';
		if ( this.options.href ) {
			href = this.options.href; 
		}
		this.a = new Element('a', {
			'class': this.options.css_class+'button',
      'href': href, 
      'title': this.options.title
      //'events': {click: this.clicked.bindWithEvent(this)}
		});
    this.a.addEvent('click', function(e){
      this.clicked.call(this, e);
    }.bind(this));
		this.span = new Element('span', {'class': this.options.css_class+'button'});
    
    this.button.adopt(this.a);
    this.a.adopt(this.span);
    if ( this.options.label ) {
      this.label = new Element('font', {html: this.options.label});
      this.span.adopt(this.label);
    }
    if ( this.options.image ) {
      this.img = new Element('img', {
        'src': this.options.image,
        'alt': this.options.label,
        'title': this.options.label
      });
      this.span.grab(this.img, 'top');
    }
    if ( this.options.action_button ) {
      this.action_button = new Element('a', {
        'href': this.options.action_button,
        'class': 'action_button'
      });
      this.span.grab(this.action_button, 'top');
    }
    this.setActive(this.options.active);
    this.setShow(this.options.show);
    this.setEnabled(this.options.enabled);
	},
	clicked: function(evt) {
		if (this.options.enabled) {
        	this.fireEvent('click', {obj: this, event: evt});
        }
    },
    setActive: function(active) {
    	if ( typeof(active) == 'undefined' && this.options.active == false) {
			this.options.active = true;
		} else if ( typeof(active) == 'undefined' && this.options.active == true) {
			this.options.active = false;
		} else {
			this.options.active = active;
		}
    	if (!this.options.active) {
            this.button.removeClass('button_active');
        } else {
        	this.button.addClass('button_active');
        }
    },
    setEnabled: function(enabled) {
    	this.options.enabled = enabled;
    	if (this.options.enabled) {
            this.button.removeClass('button_disabled');
        } else {
        	this.button.addClass('button_disabled');
        }
    },
    setShow: function(show) {
    	this.options.show = show;
    	this.button.showElement(this.options.show);
    }
});
ms.Button.Box = new Class({
  Extends: ms.Button,
  Implements: [Options, Events],
  options: {
  },
  initialize: function(box, options) {
    this.parent(options);
    this.box = box;
  }
});
ms.Box = new Class({
	Implements: [Options],
	options: {
		css_class: 'box_',
		id: '',
		label: '&nbsp;',
		image: '',
		title: true,
		show: true,
		show_content: true,
    button_close: false,
    button_displace: false,
    width: 'auto',
    height: 'auto'
	},
	initialize: function(options) {
		this.setOptions(options);
		this.content = new Element('div', {'class': this.options.css_class+'content', html: ''});
		if ( this.options.id ) {
			this.box = $(this.options.id);
			this.setContent(this.box.get('html'));
			$(this.options.id).set('html', '');
		} else {
			this.box = new Element('div');
		}
		this.box.addClass(this.options.css_class+'container');
    
		if ( this.options.title ) {
			this.title = new Element('div', {'class': this.options.css_class+'title'});
			this.menu = new Element('div', {'class': this.options.css_class+'title_menu'});
			this.label = new Element('label', {'html' : this.options.label});
			if ( this.options.image ) {
				var image = new Element('img', {'src': this.options.image, 'class': this.options.css_class+"title_image"});
				this.title.adopt(image);
			}
      this.title.adopt(this.label);
			this.title.adopt(this.menu);
			this.box.adopt(this.title);
      this.setMenu();
		}
		this.box.adopt(this.content);
		
		this.setWidth(this.options.width);
		this.setHeight(this.options.height);

		this.setShow(this.options.show);
		this.setShowContent(this.options.show_content);
	},
	setMenu: function() {
		if ( this.options.button_displace ) {
			this.b_show = new ms.Button({title: 'Показать', css_class: 'bb_', onClick: function(){this.setShowContent(true);}.bind(this), image: 'files/admin/icon/application_put.png'});
			this.b_hide = new ms.Button({title: 'Скрыть',  css_class: 'bb_', onClick: function(){this.setShowContent(false);}.bind(this), image: 'files/admin/icon/application_get.png'});
			this.menu.adopt(this.b_show.button);
			this.menu.adopt(this.b_hide.button);
		}
		if ( this.options.button_close ) {
			this.b_close = new ms.Button({title: 'Закрыть',  css_class: 'bb_', onClick: function(){this.setShow(false);}.bind(this), image: 'files/admin/icon/exit.png'});
      this.menu.adopt(this.b_close.button);
		}
	},
	setWidth: function(width) {
		this.box.setStyle('width', width);
	},
	setHeight: function(height) {
		this.content.setStyle('height', height);
	},
	setContent: function(content) {
		this.content.set('html', content);
	},
	setContentAJAX: function(file, form) {
		var result;
    if ( $(form) ) {
      var req =  new Request.HTML({
        url: file, 
        async: false,
        onComplete: function(tree, elements, html, js){
          result = html;
        }
      }).post($(form));
    } else {
		  var req =  new Request.HTML({
			  url: file, 
			  method: 'get',
			  async: false,
			  onComplete: function(tree, elements, html, js){
				  result = html;
			  }
		  }).send();
    }
		this.setContent(result);
	},
	setShow: function(show) {
		if ( typeof(show) == 'undefined' && this.options.show == false) {
			this.options.show = true;
		} else if ( typeof(show) == 'undefined' && this.options.show == true) {
			this.options.show = false;
		} else {
			this.options.show = show;
		}
		this.box.showElement(this.options.show);
	},
	setShowContent: function(show) {
		this.options.show_container = show;
		this.content.showElement(show);
		if ( this.options.button_displace && this.options.title ) {
			if ( this.options.show_container ) {
				this.b_show.setShow(false);
				this.b_hide.setShow(true);
			} else {
				this.b_show.setShow(true);
				this.b_hide.setShow(false);
			}
		}
	}
});
ms.Box.Window = new Class({
	Extends: ms.Box,
	Implements: [Options],
	options: {
		parent: null,
		move: true,
		blanket: true,
    is_scroll: true,
    horizontal: 'center center',
    vertical: 'center center'
	},
	initialize: function(options) {
    this.parent(Object.merge({show: false, css_class: 'box_window_'}, options));
		if (this.options.parent == null) {
			this.options.parent = $(document.body);
		} else {
			this.options.parent = $(this.options.parent);
		}
		var span = new Element('span', {'class': 'box_window_overlay_span'});
		var b = new Array('box_window_overlay_BR', 'box_window_overlay_BL', 'box_window_overlay_TL', 'box_window_overlay_TR');
		b.each(function(class_name) {
			var t = new Element('div', {'class': class_name});
			t.adopt(span.clone());
			this.box.grab(t, 'top');
		}.bind(this));
		
		if ( this.options.blanket ) {
			this.blanket = new Element('div',{
        'class': 'window_blanket',
        'styles': {'display': 'none'}
      });
      this.blanket.resize = (function() {
        var ss = $(document.body).getScrollSize();
        this.setStyles({
          width: ss.x,
          height: ss.y
        });
      }).bind(this.blanket);
      this.options.parent.adopt(this.blanket);
      window.addEvent('resize', this.blanket.resize);
		}
    this.options.parent.adopt(this.box);
	},
	setShow : function(show) {
		this.options.show = show;
    this.box.showElement(show);
    if ( show ) {
      var pos = new ms.Position(this.box, this.options.parent, {
        'horizontal': this.options.horizontal,
        'vertical': this.options.vertical,
        'is_scroll' : this.options.is_scroll
      });
      if (this.options.move && typeof Drag != 'undefined') {
      this.title.addClass('window_title_move');
      new Drag(this.box, {
        handle: this.title,
        onComplete: (function() {
          pos.setPosition(this.box.getPosition());
        }).bind(this)
      });            
    }
    }
		
    if (this.blanket) {
      this.blanket.resize();
      this.blanket.showElement(show);
    }
  }
});
ms.Box.Search = new Class({
  Extends: ms.Box,
  Implements: [Options],
  options: {
    parent: null,
    mode: null,
    url: null,
    width: '300',
    horizontal: 'rigth rigth',
    vertical: 'bottom bottom'
  },
  initialize: function(options) {
    this.parent(Object.merge({show: false, title: false, css_class: 'box_search_', move: false, blanket: false}, options));

    this.options.parent = $(this.options.parent);
    this.box.inject(this.options.parent, 'before');
    
    this.options.parent.addEvents({
      'keyup': function() {
        var value = this.options.parent.get('value');
        if ( value.length > 2 ) {
          this.getAJAX(value);
          var position = this.options.parent.getPosition();
          var size = this.options.parent.getSize();
          this.box.setStyles({'left': position.x + 5, 'top': position.y + size.y - 2});
        } else {
          this.setShow(false);
        }
      }.bind(this)
    });
  },
  getAJAX: function(value) {
    var req =  new Request({
      url: this.options.url, 
      method: 'get',
      async: false,
      data: 'mode='+this.options.mode+'&value='+value,
      onComplete: function(html){
        if ( html == '' ) {
          this.setShow(false);
        } else {
          this.setContent(html);
          this.setShow(true);
        }
      }.bind(this)
    }).send();
  },
  setValue: function(value) {
    this.options.parent.set('value', value);
    this.setShow(false);
  },
  setShow : function(show) {
    this.options.show = show;
    this.box.showElement(show);
  }
});
ms.Menu = new Class({
	Implements: [Options],
	options: {
		css_class: 'menu_top_',
		id: '',
		position: 'horizontal', //vertical
    open_child: false,
		button_css_class: {parent: '', child: ''}
	},
	initialize: function(options) {
		this.setOptions(options);
    var element = $(this.options.id);
		this.position = {};
		if ( this.options.position == 'horizontal' ) {
			this.position.parent = {horizontal: 'left right', vertical: 'bottom bottom'};
			this.position.child = {horizontal: 'right right', vertical: 'top bottom', is_menu_vertical: true};
		} else {
      this.position.parent = {horizontal: 'right right', vertical: 'top bottom', is_menu_vertical: true};
			this.position.child = {horizontal: 'right right', vertical: 'top bottom', is_menu_vertical: true};
		}
		
		element.addClass(this.options.css_class + 'container');
		var links = element.getElements('a');
		links.each(function(item) {
      item.store('parent_ul', item.getParent().getParent());
			item.store('parent_li', item.getParent());
			if ( $(item.retrieve('parent_ul')).id === this.options.id ) {
				item.store('root_ul', 'true');
			} else {
        item.store('root_ul', 'false');
			}
			item.store('action_button', '');
			if ( $(item.getNext('ul')) ) {
				item.store('child_menu', item.getNext('ul'));
				item.store('action_button', 'javascript:void(0)');
				item.retrieve('child_menu').addClass('child');		
				if ( !this.options.open_child ) {
          item.retrieve('parent_li').addEvents({
						  'mouseenter' : function(){
						  item.retrieve('child_menu').showElement(true);
					  }.bind(this),
						  'mouseleave' : function(){
						  item.retrieve('child_menu').showElement(false);
					  }.bind(this)
				  });
        }
			}
		}.bind(this));
		links.each(function(item, index) {
			if ( item.retrieve('root_ul') == 'false' && this.options.button_css_class.child ) {
        this.setButtonMenu(item, this.options.button_css_class.child);
			}
			if ( item.retrieve('root_ul') == 'true' && this.options.button_css_class.parent ) {
				this.setButtonMenu(item, this.options.button_css_class.parent);
			}
			if ( item.retrieve('child_menu') ) {
				if ( item.retrieve('root_ul') == 'false' ) { 
					var pos = new ms.Position(item.retrieve('child_menu'), item.retrieve('parent_li'), this.position.child);
				} else {
					var pos = new ms.Position(item.retrieve('child_menu'), item.retrieve('parent_li'), this.position.parent);
				}
			}
		}.bind(this));
    links.each(function(item, index) {
      if ( item.retrieve('child_menu') && !this.options.open_child ) {
        item.retrieve('child_menu').showElement(false);
      }
    }.bind(this));
	},
  setButtonMenu: function(item, button_css) {
    var element = item.retrieve('parent_li').getElement('a');
    var img = '';
    
    if ( element.get('class') == "select" ) {
      active = true;
    } else {
      active = false;
    }
    if ( element.getElement('img') ) {
      img = element.getElement('img').get('src');
    }
    var b = new ms.Button({
      css_class: button_css,
      label: element.get('text'),
      href: element.get('href'),
      image: img,
      action_button: item.retrieve('action_button'),
      active: active
    });
    b.button.inject(element, 'after');
    element.dispose();
  }
});
ms.Grid = new Class({
	Implements: [Options],
	options: {
		css_class: 'grid',
		id: '',
		form: true,
		checkbox: true,
    count_id: {checkbox: 'count_checkbox', checked: 'count_checked'}
	},
	initialize: function(options) {
		this.setOptions(options);
		this.buttons = [];
		this.box = $(this.options.id);
    this.box.addClass(this.options.css_class);
    if ( !this.box.getElement('table') ) {
      return;
    }
		this.grid = this.box.getElement('table');
    this.grid.addClass(this.options.css_class);
		this.count_checkbox = this.grid.getElements('tr').length - 1;
		this.count_checked = 0;
    if ( this.options.form ) {
      var form = new Element('form', {
        'id': 'form_'+this.options.id,
			  'name': 'form_'+this.options.id,
			  'method': 'post',
			  'action': ''
      });
		  form.adopt(this.grid);
		  form.inject(this.box, 'top');
		  this.form = new ms.Form(form);
    }
		this.setPanel();
    this.setCountPanel();
	},
  setCountPanel: function()
  {
    if ( $(this.options.count_id.checkbox) ) {
      $(this.options.count_id.checkbox).set('html', this.count_checkbox);
    }
    if ( $(this.options.count_id.checked) ) {
      $(this.options.count_id.checked).set('html', this.count_checked);
    }
  },
  setPanel: function() {
    this.grid.getElements('tr').each(function(item) {
      if ( this.options.checkbox ) {
        this.setCheckbox(item);
      }
      
      if ( item.getElement('.editor') ) {
        var editor = item.getElement('.editor');
        item.addEvents({
          'mouseenter': function() {
            editor.setStyle('visibility', 'visible');
          },
          'mouseleave': function() {
            editor.setStyle('visibility', 'hidden');
          }
        });
      }
    }.bind(this));
  },
	setCheckbox: function(item) {
		var td = new Element('td', {'class': 'center'});
		var span = new Element('span', {});
		var checkbox = new Element('input', {
			 'type': 'checkbox',
			 'class': 'checkbox',
			 'value': '',
			 'name': ''
		});
		if ( item.get('code') ) {
      var code = item.get('code');
			checkbox.set({'name': 'check[]', 'id': 'check_' + code, 'value': code });
			checkbox.addEvent('click', function(){this.markCheckbox(checkbox);}.bind(this));
		} else {
			td.set('width', '30');
			checkbox.set('name', 'mark_all');
			checkbox.addEvent('click', function(){this.markAllCheckbox(checkbox);}.bind(this));
		}
		span.adopt(checkbox);
		td.adopt(span);
		td.inject(item, 'top');
	},
	addButtons: function(buttons) {
		this.buttons = buttons;
	},
	buttonEnabled: function() {
		if ( this.count_checked == 0 ) {
			enabled = false;
		} else {
			enabled = true;
		}
		this.buttons.each(function(button){
			button.setEnabled(enabled);
		});
    this.setCountPanel();
	},
	markAllCheckbox: function(checked)
	{ 
		this.count_checked = $(this.form.form).getElements('input[name^=check]').checkElement(checked.get('checked'));
		this.buttonEnabled();
	},
	markCheckbox: function(checked)
	{ 
		var form = $(this.form.form);
		var checkbox = form.getElements('input[name^=check]');
		var count_checked = 0;
		
		checkbox.each(function(item){
			if ( item.get('checked') == true ) {
				count_checked ++;
			}
		});
		this.count_checked = count_checked;
		if ( this.count_checkbox == this.count_checked ) {
			form.getElements('input[name=mark_all]').checkElement(true);
		} else {
			form.getElements('input[name=mark_all]').checkElement(false);
		}
		this.buttonEnabled();
	}
});

