
function redirect(url){
	window.location = url;
}

function popupWindow(url, w, h){
	var width = w || 640, height = h || 480;
	var top = parseInt((screen.width - width) / 2), left = parseInt((screen.height - height) / 2);
	var popupWin = window.open(url, "myPopupWindow", "location,width=" + width + ",height=" + height + ",top=" + top + ",left=" + left);
	popupWin.focus();
	return false;
}

function charCounter(obj, max){
	var textarea = $(obj);
	var limit = max || 3000;
	var count = textarea.value.length;
	var current = limit - count;
	if(count >= limit){
		this.value = textarea.value.substr(0, limit);
		current = limit - textarea.value.length;
	}
	$('char_counter').update(current);
};

//---------------------------------------------------------------- ONLOAD EVENTS

document.observe('dom:loaded',  function() {
	$$('img.menu-hover').each( function(element){
		var src = element.src;
		var srcHover = element.src.slice(0, -4) + '_a' + '.png';
		var img = new Element('img', {'src' : srcHover});
		element.observe('mouseover', function() {
			this.src = srcHover;
		});
		element.observe('mouseout', function() {
			this.src = src;
		});
		new Element('img', {src: srcHover});
	})
});

Event.observe(document, 'dom:loaded', function(e){
	$$('input[rel="clear"]').each(function(el, i){
		if(el.type.match(/text/i) && !$F(el).blank()){
			var defValue = el.value;
			el.observe('focus', function(e, defValue){
				if(this.value == defValue){
					this.value = "";
					this.style.color = '#000';
				}
			}.bindAsEventListener(el, defValue));
			el.observe('blur', function(e, defValue){
				if(this.value == ""){
					this.value = defValue;
					this.style.color = '#ccc';
				}
			}.bindAsEventListener(el, defValue));
		}
	});

	$$('img[rel="hover"]').each(function(el, i){
		if (el.src.blank() == false) {   
			var defsrc = el.src;   
			var hovsrc = el.src.substring(0, el.src.length - 4) + '_a' + el.src.substring(el.src.length - 4);
			el.observe('mouseover', function(e, src){
				this.src = src;
			}.bindAsEventListener(el, hovsrc));
			el.observe('mouseout', function(e, src){
				this.src = src;
			}.bindAsEventListener(el, defsrc));
			new Element('img', {src: hovsrc});
		}   
	});

	$$('img[rel="bg"]').each(function(el, i){
		var defbg = el.up('td').style.backgroundImage;
		var hovbg = 'url(/images/menu_bg_a.gif)';
		el.observe('mouseover', function(e, bg){
			this.up('td').setStyle({backgroundImage: bg});
		}.bindAsEventListener(el, hovbg));
		el.observe('mouseout', function(e, bg){
			this.up('td').setStyle({backgroundImage: bg});
		}.bindAsEventListener(el, defbg));
	});
	
	$$('img[rel="fade"]').each(function(el, i){
		el.setOpacity(0.6);
		(function(object, start, finish, ptr){
			object.observe('mouseover', function(e){
				if(ptr !== null) ptr.cancel();
				ptr = new Effect.Appear(object, {duration: 0.3, from: start, to: finish, afterFinish: function(){
					ptr = null;
				}});
			});
			object.observe('mouseout', function(e){
				if(ptr !== null) ptr.cancel();
				ptr = new Effect.Fade(object, {duration: 0.2, from: finish, to: start, afterFinish: function(){
					ptr = null;
				}});
			});
		})(el, 0.6, 1.0, null);
	});	
});

//--------------------------------------------------------- FORM VALIDATOR CLASS

function formValidatorClass(form_id){
    this.form = $(form_id);
    this.isValid = true;

    this.icons = {
        loading: '/images/validator/loading.gif',
        error: '/images/validator/error.gif',
        success: '/images/validator/success.gif'
    };
    
    this.validators = {
        'required': {
            message: 'Это поле не заполнено',
            func: function(el){ return !$F(el).blank(); }
        },
        'email': {
            message: 'Неверно введен email',
            func: function(el){ return $F(el).blank() || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test($F(el)); }
        },
        'url': {
            message: 'Неверно введен url',
            func: function(el){ return $F(el).blank() || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test($F(el)); }
        },
        'login': {
            message: 'Неверный логин',
            func: function(el){ return $F(el).blank() || /^[^\s\d]{1,}[A-Z-a-zА-Яа-я0-9_]{2,31}$/.test($F(el)); }
        },
        'password': {
            message: 'Неверный пароль',
            func: function(el){ return $F(el).blank() || /^\S{3,16}$/.test($F(el)); }
        },
        'password_confirm': {
            message: 'Пароли не совпадают',
            func: function(el){ return $F(el).blank() || $F(el) == $F($(el.form).select('input.password').shift()); }
        },
        'captcha': {
            message: 'Код введен неверно',
            func: function(el){ return $F(el).blank() || /^[0-9]{6}$/.test($F(el)); }
        },
        'minsum': {
            message: 'Сумма должна быть не меньше 5 грн.',
            func: function(el){ return $F(el) >= 5; }
        },
		'phone': {
            message: 'Телефон введен неправильно.',
            func: function(el){ if(/^\+[(38)7].+/.test($F(el))) { return /^\+38\d{10}/.test($F(el)) || /^\+7\d{10}/.test($F(el)) } else { return true }; }
		}
    };
    
    this.submit = function(e){
        e.stop();
        this.validateAll();
        if(this.isValid == true){
            this.form.select('input[type="submit"]').invoke('disable');
            this.form.submit();
        }
    };

    this.reset = function(e){
        this.isValid = true;
        this.form.select('div.icon').invoke('update');
        this.form.select('div.message').invoke('update').invoke('hide');
        this.form.select('input[type="submit"]').invoke('enable');
    };

    this.initElement = function(el){
        if(el.hasClassName($H(this.validators).keys().join('|'))){
            Event.observe(el, 'blur', function(e){
                this.validateOne(e.element());
            }.bindAsEventListener(this));
        }
    };

    this.validateOne = function(el){
        var valid = true;

        $(el).classNames().each(function(className){
            if(valid == true){
                if(typeof (validator = $H(this.validators).get(className)) == 'object'){
                    if(validator.func.bind(this)(el) == false){
                        valid = false;
                        this.setCheckStatus('false', el, validator.message);
                    }
                    else {
                        this.setCheckStatus('true', el);
                    }
                }
            }
        }.bind(this));
        
        this.isValid &= valid;
    };

    this.validateAll = function(){
        this.isValid = true;
        Form.getElements(this.form).each(function(el){
            if(el.hasClassName($H(this.validators).keys().join('|'))){
                this.validateOne(el);
            }
        }.bind(this));
    };

    this.setCheckStatus = function(status, el, message){
        var icon_block = $(el).up('div.fieldset').select('div.icon').shift();
        var mess_block = $(el).up('div.fieldset').select('div.message').shift();

        switch(status){
            case 'true':
                mess_block.update().hide();
                icon_block.update()
                //icon_block.update().insert({top: new Element('img', {src: this.icons.success, width: 16, height: 16})});
                break;
            case 'false':
                mess_block.hide().update(validator.message);
                icon_block.update().insert({top: new Element('img', {src: this.icons.error, width: 16, height: 16})});
                if(typeof Effect == 'object'){
                    new Effect.Parallel([
                            new Effect.BlindDown(mess_block, { sync: true }), new Effect.Appear(mess_block, { sync: true }) 
                        ], { 
                        duration: 0.5
                    });
                }
                else{
                    mess_block.show();
                }
                break;
            case 'wait':
                mess_block.update().hide();
                icon_block.update().insert({top: new Element('img', {src: this.icons.loading, width: 16, height: 16})});
                break;
        }
    };

    Form.getElements(this.form).each(this.initElement.bind(this));
    Event.observe(this.form, 'submit', this.submit.bindAsEventListener(this));
    Event.observe(this.form, 'reset', this.reset.bindAsEventListener(this));

    this.reset();
}
var tabs = function(){
	document.observe("dom:loaded", function(){
		var tabs = $$('#tabs li a');
		var panel = $$('.panel');
		tabs.each(function(e){
			e.observe('click', function(event){
				var tabId = this.href.split('#')[1];
				$$('#tabs .selected').each(function(el){
					el.removeClassName('selected');
				});			
				this.addClassName('selected');
				panel.each(function(el){
					el.hide();				 
				});
				$(tabId).setStyle({'display': 'block'});
				event.stop();
			})
		})
	});
}
