function setCookie(name, value, seconds, path) {
	if (!seconds) seconds = 0;
	if (!path) path = "/";
	var expires = new Date();
	expires.setTime(expires.getTime()+seconds*1000);
	document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() + "; path="+path;
}


function getCookie(name) {
	var cookies = document.cookie;
	var startpos = cookies.indexOf(name);
	if (startpos != -1) {
		startpos += name.length+1;
		var endpos = cookies.indexOf(";",startpos);
		if (endpos == -1) endpos = cookies.length;
		return unescape(cookies.slice(startpos,endpos));
	}
	else
		return false;
}

function checkForm(f) {
	var obligatory = Ext.query('input.red,textarea.red',f);
	for (i=0;i<obligatory.length;i++) {
		if (obligatory[i].name == 'email') {
        	re = /^\w[\w\-\.]*@\w[\w\-]+\.([\w\-]+\.)*\w{1,4}$/;
			r = obligatory[i].value.match(re);
			if (r == null) {
				Ext.fly(obligatory[i]).addClass('checkError');
				obligatory[i].focus();
    			return false;
			}
		}
		else if(!obligatory[i].value || obligatory[i].value == 0) {
        	Ext.fly(obligatory[i]).addClass('checkError');
			obligatory[i].focus();
			return false;
		}
	}
	if (f.password && f.password2 && f.password.value != "" && f.password2.value != f.password.value) {
  		var Pass = Ext.get(f.password);
  		var Tip = Ext.fly(f).createChild({
			cls	: 'errorTip',
			html: 'Пароль и повтор пароля не совпадают'
		});
		Tip.setStyle({
			width		: '160px',
			'text-align': 'center',
			top			: Pass.getY()+'px',
			left		: Pass.getX()+Pass.getWidth()+5+'px'
		}).pause(4).fadeOut({remove: true});
		return false;
	}
	return true;
}

Ext.onReady(function(){
	if (document.getElementById('login_form')) {
		// Авторизация
		var logFrm = Ext.query('div#login_form form')[0]; // DOM
		var lv = logFrm.login.value;
		var pv = logFrm.password.value;
		Ext.get(logFrm.login).on({
			focus: function(){
				if (this.value == lv) this.value = "";
			},
			blur:  function(){
				if (this.value == "") this.value = lv;
			}
		});
		Ext.get(logFrm.password).on({
			focus: function(){
				if (this.value == pv) this.value = "";
			},
			blur:  function(){
				if (this.value == "") this.value = pv;
			}
		});
		Ext.get(Ext.query('div#login_form a.submit')[0]).on('click',function(){
			if (logFrm.login.value !="" && logFrm.login.value!=lv && logFrm.password.value !="" && logFrm.password.value!=pv) logFrm.submit();
			else {
				var Tip = this.parent().createChild({
					cls	: 'errorTip',
					html: 'Логин или пароль не указаны'
				});
				Tip.setStyle({
					width		: '160px',
					'text-align': 'center',
					top			: this.getY()-Tip.getHeight()-5+'px',
					left		: this.getX()+this.getWidth()/2+'px'
				}).pause(4).fadeOut({remove: true});
			}
		},null,{preventDefault:true});
	}
  	if (document.getElementById('remindForm')) {
  		// Восстановление пароля
  		var remFrm = document.getElementById('remindForm');
	    Ext.select('input.red',remFrm).on('keydown',function(){
	    	Ext.fly(this).removeClass('checkError');
	    });
    	Ext.get(Ext.query('form#remindForm div.submit > a')[0]).on('click',function(){
	    	if (checkForm(remFrm)) remFrm.submit();
		},null,{preventDefault:true});
  	}
  	else if (document.getElementById('addForm')) {
  		// Добавление объявы
	  	var addFrm = Ext.query('div#reg_form form')[0]; // DOM
	  	// IE bug: Резюме</option>Вакансии</option>
	  	//var tpl = new Ext.Template('<option value="{id}">{name}</option>');
	    //tpl.compile();
	    var spans = Ext.query('span.cRed',addFrm);
	    var imax = parseInt(spans[0].innerHTML);
	    var tmax = parseInt(spans[1].innerHTML);
	    var sels = Ext.query('select',addFrm);
	    Ext.get(sels[0]).on('change',function(){
      		sels[1].innerHTML = sels[2].innerHTML = [];
      		for(var i = 0; i < Sel[this.dom.value]['subs'].length; i++){
			    sels[1].add(new Option(Sel[this.dom.value]['subs'][i]['name'],Sel[this.dom.value]['subs'][i]['id']),null);
			}
			for(var i = 0; i < Sel[this.dom.value]['types'].length; i++){
			   sels[2].add(new Option(Sel[this.dom.value]['types'][i]['name'],Sel[this.dom.value]['types'][i]['id']),null);
			}
	    });
	    Ext.select('input.red, textarea.red',false,addFrm).addListener('keydown mousedown',function(){
	    	Ext.fly(this).removeClass('checkError');
	    });
	    Ext.select('input.red, textarea.red',false,addFrm).addListener('keyup mouseup',function(){
	    	if (this.tagName.toLowerCase() == 'input') {
            	if (this.value.length>imax) {
            		this.value = this.value.slice(0,imax);
            	}
                spans[0].innerHTML = imax-this.value.length;
	    	}
	    	if (this.tagName.toLowerCase() == 'textarea') {
            	if (this.value.length>tmax) {
            		this.value = this.value.slice(0,tmax);
            	}
                spans[1].innerHTML = tmax-this.value.length;
	    	}
	    });
	    Ext.get(Ext.query('div#reg_form div.submit a.reset')[0]).on('click',function(){
	    	addFrm.reset();
	    	spans[0].innerHTML = imax;
	    	spans[1].innerHTML = tmax;
		},null,{preventDefault:true});
		Ext.get(Ext.query('div#reg_form div.submit a.save')[0]).on('click',function(){
	    	var input = Ext.query('input.red',addFrm)[0];
	    	if (input.value.length>imax) {
        		input.value = input.value.slice(0,imax);
        	}
            spans[0].innerHTML = imax-input.value.length;
            var textarea = Ext.query('textarea.red',addFrm)[0];
	    	if (textarea.value.length>tmax) {
        		textarea.value = textarea.value.slice(0,imax);
        	}
            spans[1].innerHTML = tmax-textarea.value.length;
	    	if (checkForm(addFrm)) addFrm.submit();
		},null,{preventDefault:true});
	}
	else if (document.getElementById('reg_form')) {
  		// Регистрация
	  	var regFrm = Ext.query('div#reg_form form')[0]; // DOM
	    Ext.select('input.red',regFrm).on('keydown',function(){
	    	Ext.fly(this).removeClass('checkError');
	    });
		Ext.get(Ext.query('div#reg_form div.submit > a')[0]).on('click',function(){
	    	if (checkForm(regFrm)) regFrm.submit();
		},null,{preventDefault:true});
	}
	else if (document.getElementById('myForm')) {
		// Список объяв пользователя
    	Ext.get('delete_all').on('click',function(){
    		Ext.select('input[type=checkbox][id!=delete_all]',null,'myForm').each(function(el){
    			this.dom.checked?el.dom.setAttribute('checked',true):el.dom.removeAttribute('checked');
    		},this);
    	});
    	Ext.get(Ext.query('div#delete_all_control > a')[0]).on('click',function(){
        	if (Ext.query("input[type=checkbox][id!=delete_all]:checked",null,'myForm').length) {
				if(confirm("Удалить выбранные?")) document.getElementById('myForm').submit();
			}
    	},null,{preventDefault:true});
	}
});

Ext.override(Ext.CompositeElementLite, {
	addListener : function(eventName, handler, scope, opt){
	    var i,eventArray = eventName.split(' '),len = eventArray.length;
		for(i=0;i<len;i++){
		    Ext.each(this.elements, function(e) {
		    	Ext.EventManager.on(e, eventArray[i], handler, scope || e, opt);
		    });
		}
	    return this;
	}
});
Ext.CompositeElementLite.prototype.on = Ext.CompositeElementLite.prototype.addListener;




