var PromoManager = new Class(
        {
            initialize : function()
            {
                var toggles = $$('#promo dt');
                toggles.each(function(toggler, idx)
                        {
                            toggler.addEvent('click', function(e)
                                    {
                                        if (this.getNext().getStyle('height') != '0px')
                                        {
                                            window.location.href = this.getNext().getElement('a').get('href');
                                        }
                                    });
                        });
                var content = $$('#promo dd');
                this.acc = new Accordion(toggles, content,
                        {
                            display : 0,
                            show : 0,
                            duration : 700,
                            opacity : false,
                            onActive : function(toggler, element)
                            {
                                toggler.addClass('active');
                            },
                            onBackground : function(toggler, element)
                            {
                                toggler.removeClass('active');
                            }
                        });
                $('promo').addEvent('mouseover', function()
                        {
                            $clear(PromoManager.current.timerId)
                        });
                $('promo').addEvent('mouseleave', function()
                        {
                            PromoManager.current.timerId = PromoManager.current.rotate.periodical(5000, PromoManager.current)
                        });
                PromoManager.current = this;
                this.timerId = this.rotate.periodical(10000, this);
            },
            rotate : function()
            {
                var i = (this.acc.previous + 1) % 5;
                this.acc.display(i);
            }
        });
MooTools.lang.set('en-US', 'FormValidator',
        {

            required : 'Обязательное поле',
            minLength : 'Введите минимум {minLength} символов (вы ввели {length}).',
            maxLength : 'Введите не больше {maxLength} символов (вы ввели {length}).',
            integer : 'Введите целое число',
            numeric : 'Введите число',
            digits : 'Можно ввести только цифры и знаки',
            alpha : 'Please use letters only (a-z) with in this field. No spaces or other characters are allowed.',
            alphanum : 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.',
            dateSuchAs : 'Please enter a valid date such as {date}',
            dateInFormatMDY : 'Please enter a valid date such as MM/DD/YYYY (i.e. "12/31/1999")',
            email : 'Введите верный e-mail адрес',
            url : 'Please enter a valid URL such as http://www.google.com.',
            currencyDollar : 'Please enter a valid $ amount. For example $100.00 .',
            oneRequired : 'Заполните хотя бы одно поле',
            errorPrefix : ' ',
            warningPrefix : ' ',

            // FormValidator.Extras

            noSpace : 'There can be no spaces in this input.',
            reqChkByNode : 'Выберите вариант',
            requiredChk : 'Обязательное поле',
            reqChkByName : 'Please select a {label}.',
            match : 'Неверное подтверждение {matchName}',
            notMatch : 'Значение не должно совпадать со значением {matchName}',
            startDate : 'the start date',
            endDate : 'the end date',
            currendDate : 'the current date',
            afterDate : 'The date should be the same or after {label}.',
            beforeDate : 'The date should be the same or before {label}.',
            startMonth : 'Please select a start month',
            sameMonth : 'These two dates must be in the same month - you must change one or the other.'

        });

function hashCode(inText)
{
    inText = inText.toLowerCase().trim();
    var hash = 0;
    for (i = 0; i < inText.length; i++)
    {
        symbol = inText.charAt(i);
        Ucode = symbol.charCodeAt(0);
        hash += Ucode * i;
    }
    return hash;
}

FormValidator.addAllThese(
        [

                ['validateAjax',
                        {
                            errorMsg : 'Ошибка',
                            test : function(element, props)
                            {
                                var fv = element.getParent('form').retrieve('validator');
                                if (!fv)
                                    return true;
                                if (FormValidator.getValidator('IsEmpty').test(element))
                                    return true;
                                var result = true;
                                loader = new Element('img').addClass('loader').set('src', '/s/images/icons/loader.gif');
                                $(props.msgPos).adopt(loader);
                                var jsonRequest = new Request.JSON(
                                        {
                                            async : false,
                                            url : props.validateAjax,
                                            onSuccess : function(json, text)
                                            {
                                                json = JSON.decode(text);
                                                result = json.result;
                                                loader.destroy();
                                            }.bind(this)
                                        }).get(
                                        {
                                            data : element.value
                                        });
                                if (result == true)
                                    return result;
                                this.errorMsg = result;
                                return false;
                            }
                        }],
                ['validateAbonentLastname',
                {
                    errorMsg : 'Фамилия абонента введена неверно. Если вы уверены в правильности ввода фамилии - <a href="/abonents/account/change-lastname.xl">заполните форму</a>',
                    test : function(element, props)
                    {
                        var fv = element.getParent('form').retrieve('validator');
                        if (!fv)
                            return true;
                        if (FormValidator.getValidator('IsEmpty').test(element))
                            return true;
                        var result = true;
                        if (props.validateAbonentLastname == hashCode(element.value))
                            return true;
                        this.errorMsg = 'Фамилия абонента введена неверно. Если вы уверены в правильности ввода фамилии - <a href="/abonents/account/change-lastname.xl?id='
                                + props.contractId + '">заполните форму</a>'
                        return false;
                    }
                }],
                ['validate-not-match',
                        {
                            errorMsg : function(element, props)
                            {
                                return FormValidator.getMsg('notMatch').substitute(
                                        {
                                            matchName : props.matchName || document.id(props.matchInput).get('name')
                                        });
                            },
                            test : function(element, props)
                            {
                                var eleVal = element.get('value');
                                if (FormValidator.getValidator('IsEmpty').test(element))
                                    return true;
                                var matchVal = document.id(props.matchInput) && document.id(props.matchInput).get('value');
                                return eleVal == matchVal ? false : true;
                            }
                        }],

                ['minOrNull',
                        {
                            errorMsg : function(element, props)
                            {
                                if ($type(props.minOrNull))
                                    return FormValidator.getMsg('minLength').substitute(
                                            {
                                                minLength : props.minOrNull,
                                                length : element.get('value').length
                                            });
                                else
                                    return '';
                            },
                            test : function(element, props)
                            {
                                if (FormValidator.getValidator('IsEmpty').test(element))
                                    return true;
                                if ($type(props.minOrNull))
                                    return (element.get('value').length >= $pick(props.minOrNull, 0));
                                else
                                    return true;
                            }
                        }],
                ['validate-russian',
                        {
                            errorMsg : 'Используйте только буквы русского алфавита',
                            test : function(element)
                            {
                                return FormValidator.getValidator('IsEmpty').test(element) || (/^[а-яА-Я \\-Ёё]+$/).test(element.get('value'));
                            }
                        }],
       ['validate-enforce-ifnotempty', {
		test: function(element, props){
			var fv = element.getParent('form').retrieve('validator');
			if (!fv) return true;
			if (!FormValidator.getValidator('IsEmpty').test(element)){
				if( props.toEnforce)
				{
					$(props.toEnforce).addClass( "required");					
				}
			}
			else
			{
			    $(props.toEnforce).removeClass( "required");
			    $($(props.toEnforce).get('validatorProps').msgPos).set( "text", '');
			}
			return true;
		}
	}]]);

function reloadCaptcha()
{
    $('captcha').src = '/captcha.jpg?id=' + Math.random();
}

window.addEvent('domready', function()
{
    var els = $$('form.custom');
    els.each(function(el, i)
            {
                var validator = new FormValidator.Inline(el,
                        {
                            evaluateFieldsOnBlur : false,
                            scrollToErrorsOnSubmit : true,
                            scrollFxOptions :
                            {
                                transition : 'quad:out',
                                offset :
                                {
                                    y : -300
                                }
                            }
                        })
                validator.addEvent('elementFail', function(f)
                        {
                            f.getParent().getParent().addClass("validate-error");
                            f.getParent().getParent().removeClass("validate-ok");
                        });
                validator.addEvent('elementPass', function(f)
                        {
                            f.getParent().getParent().removeClass("validate-error");
                            if (f.value)
                                f.getParent().getParent().addClass("validate-ok");
                        });
            });
        // var els = $$('input[alt]');
        // els.each( function( el, i)
        // {
        // new OverText(el, {positionOptions: {poll:true,position:
        // 'upperLeft',edge: 'upperLeft', offset: {x: 6,y: 7}}});
        // });
    });

function toggleContract(id)
{
    $(id).toggleClass('opened');
}

if (window.location.href.indexOf('preview=1') != -1)
{
    window.addEvent('domready', function()
            {
                $$('a').each(function(el, idx)
                        {
                            el.set('target', '_top');
                        });
            });
}

function checkPageLoaded(pageId)
{
    var jsonRequest = new Request.JSON(
            {
                async : true,
                url : '/check-loader.xl?id=' + pageId,
                onSuccess : function(json, text)
                {
                    if (json.result != 2)
                    {
                        document.location.reload(true);
                        $clear(loaderTimerId);
                    }
                }
            }).get();
}
