
//--------------------------------------------------------- MAIL FORM CHECKER

function checker(form)
{
	if(form.hidden.value == '0')
		form.hidden.value = '1';
	
	return true;
}

//--------------------------------------------------------- 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 || 1000;
	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();
				(function a(){ alert('Ваш товар добавлен в корзину.'); }).delay(1);				
			}.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 priceFrameClass(){
	this.init = function(){
		$('price-block-shadow').observe('click', function(q){
	    	$('body').removeClassName('pv-active');
	    });
		$('price-block-close').observe('click', function(q){
	    	$('body').removeClassName('pv-active');
	    });

		$$('.price-view-btn').each(function(el){
		   el.observe('click', this.load.bindAsEventListener(this, el.readAttribute('rel')));
		}.bind(this));
	};

	this.load = function(e, item_id){
		new Ajax.Request('/?module=catalogue&media=ajax', {
			method: 'POST',
			parameters: {item: item_id},
			onCreate: function(){
				if(table = $('price-table')) table.remove();
				$('body').addClassName('pv-active');
			}.bind(this),
			onSuccess: function(transport){
				if(transport.responseText.length > 0){
					$('price-view').insert({bottom: transport.responseText});
				}
			}.bind(this),
			onComplete: function(){
		       this.render();
			}.bind(this),
			onException: function(a, b){
				alert('priceFrameClass Load error: #' + b.message);
			}
		});
	};

	this.render = function(){
		if(element = $('price-view')){
			var leftP = Math.round((document.viewport.getWidth() - element.getWidth()) / 2);
			var topP = Math.round((document.viewport.getHeight() - element.getHeight()) / 2);
			element.setStyle({
				'top' : topP + 'px',
				'left' : leftP + 'px'
			});
		}
	};

	this.init();
}

//------------------------------------------------------------------- ZOOM IMAGE

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

//------------------------------------------------------------------------ OTHER

function clear_select_list(list){
	for(var i = list.options.length - 1; i >= 0; i--){
		list.remove(i);
	}
}

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

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

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