
//--------------------------------------------------------- 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: SITE_SETTINGS.lang == 'en' ? 'Empty field' : 'Это поле не заполнено.',
			func: function(el){ return !$F(el).blank(); }
		},
		'email': {
			message: SITE_SETTINGS.lang == 'en' ? 'Incorrect Email' : 'Неверно введен Email.',
			func: function(el){ return $F(el).blank() || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test($F(el)); }
		},
		'url': {
			message: SITE_SETTINGS.lang == 'en' ? 'Incorrect URL' : 'Неверно введен 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: SITE_SETTINGS.lang == 'en' ? 'Incorrect login' : 'Неверно введен login',
			func: function(el){ return $F(el).blank() || /^[^\s\d]{1,}[A-Z-a-zА-Я-а-я0-9_]{2,31}$/.test($F(el)); }
		},
		'password': {
			message: SITE_SETTINGS.lang == 'en' ? 'Incorrect password' : 'Неверно введен password',
			func: function(el){ return $F(el).blank() || /^\S{6,16}$/.test($F(el)); }
		},
		'password_confirm': {
			message: SITE_SETTINGS.lang == 'en' ? 'Passwords are different' : 'Пароли не совпадают.',
			func: function(el){ return $F(el).blank() || $F(el) == $F($(el.form).select('input.password').shift()); }
		},
		'captcha': {
			message: SITE_SETTINGS.lang == 'en' ? 'Incorrect code' : 'Код введен неверно.',
			func: function(el){ return $F(el).blank() || /^[0-9]{6}$/.test($F(el)); }
		}
	};
	
	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();
}


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);
};

//------------------------------------------------------------------------------

function shopBasketClass(url){
	this.url = url || '/?module=shop&media=ajax';

	this.add = function(gid, count){
		new Ajax.Request(this.url, {
			method: 'GET',
			parameters: {action: 'add', gid: gid, count: count},
			onSuccess: function(transport){
				if(transport.responseText.length > 0){
					alert(transport.responseText);
				}
			},
			onComplete: function(){
				this.updateCart();
			}.bind(this),
			onException: function(a, b){
				alert('AddCart error: #' + b.message);
			}
		});
	}

	this.updateCart = function(){
		if($('shopbasket_goods') && $('shopbasket_price')){
			new Ajax.Request(this.url, {
				method: 'GET',
				parameters: {action: 'update'},
				onSuccess: function(transport){
					if(transport.responseText.length && transport.responseText.isJSON() == true){
						var result = transport.responseText.evalJSON();
						$('shopbasket_goods').update(result.total);
						$('shopbasket_price').update(result.price);
					}
					else if(transport.responseText.length){
						alert(transport.responseText);
					}
				},
				onComplete: function(){
					new Effect.Pulsate('basket', {pulses: 2, duration: .8});
				},
				onException: function(a, b){
					alert('UpdateCart error: #' + b.message);
				}
			});
		}
	}
}

//------------------------------------------------------------------------------

function zoomImageClass(){
	this.iddle = true;
	this.div = new Element('div', {id: 'zoomImageDiv'});
	this.close = new Element('img', {src: '/images/close.gif', width: 16, height: 16, title: 'Закрыть'}).addClassName('close');
	this.img = null
	
	this.zoom = function(src){
		if(this.iddle == false) return;
		this.iddle = false;

		this.img = new Element('img');
		this.img.observe('load', this.onload.bindAsEventListener(this));
		this.img.observe('click', this.onclose.bindAsEventListener(this));
		this.img.src = src;
	}
	
	this.onload = function(e){
		var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
		var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft;

		var cTop = scrollTop + (document.viewport.getHeight() - this.img.height) / 2;
		var cLeft = scrollLeft + (document.viewport.getWidth() - this.img.width) / 2;

		this.div.setStyle({'top': cTop + 'px', 'left': cLeft + 'px', width: this.img.width + 'px', height: this.img.height + 'px'});
		this.div.insert({top: this.img}).insert({top: this.close}).hide();

		$$('body')[0].insert({top: this.div});
		
		new Effect.Appear('zoomImageDiv', {
			duration: 0.5
		});
	}
	
	this.onclose = function(e){
		new Effect.Fade('zoomImageDiv', {
			duration: 0.5,
			afterFinish: function(){
				$('zoomImageDiv').descendants().invoke('remove');
				$('zoomImageDiv').remove();
				this.img = null;
				this.iddle = true;
			}.bind(this)
		});
	}

	this.close.observe('click', this.onclose.bindAsEventListener(this));
}

//------------------------------------------------------------------------------

Event.observe(document, 'dom:loaded', function(e){
	$$('.menu-item').each( function(element){
		element.observe('mouseover', function() {
			this.addClassName('hover');
		});
		element.observe('mouseout', function() {
			this.removeClassName('hover');
		});
	});

	$$('img[rel="hover"]').each(function(el, i){
	    if (el.tagName.match(/img/i) && el.src != '') {   
	        defsrc = el.src;   
			hovsrc = el.src.substring(0, el.src.length - 4) + '_a' + el.src.substring(el.src.length - 4);
	        (function(defsrc, hovsrc) {   
	            el.onmouseover = function(){
	                if (this.src == defsrc) this.src = hovsrc;
	            }   
	            el.onmouseout = function(){   
	                if (this.src == hovsrc) this.src = defsrc;
	            }   
	        })(defsrc, hovsrc);   
	    }   
	});

	$$('input[rel="clear"]').each(function(el, i){
		if(el.type == 'text' && el.value != ""){
			el.setStyle({color: '#999'});
			var defValue = el.value;
			(function(defValue){
				el.observe('focus', function(e){
					if(this.value == defValue) this.value = "";
					el.setStyle({color: '#000'});
				});
				el.observe('blur', function(e){
					if(this.value == "") this.setStyle({color: '#999'}).value = defValue;
				});
			})(defValue);
		}
	});
});

