var current_width = 0;
var n=0;
var IE='\v'=='v';

function searchAutoWidth(){
    if (window.getCoordinates().width >= 980 && window.getCoordinates().width <= 1150)
    {
        var new_s_width = $('wrapper').getCoordinates().width - 825;
        $("search-input").setStyle('width',new_s_width);
    }
}

function setAutoRemove(id, val) {
    if (!$(id)) return false;
    if ($(id).hasClass('no_auto_remove')) return false;
    $(id).addEvent('focus', function() {
        if (this.get('value') == val) {
            this.set('value', '');
            this.addClass('color_black');
        }
    });
    $(id).addEvent('blur', function() {
        if (this.get('value').trim() == '') {
            this.set('value', val);
            this.removeClass('color_black');
            this.removeClass('input_succes');
        }
    });
    if($(id).get('value')) {
        if ($(id).get('value').trim() == ''){
            $(id).set('value',val);
            $(id).removeClass('color_black');
        }
    }

    return $(id);
}
function slider_resize() {
    var current_width_me = 0, slider_w = 0;

    if ($('slider-info-box')){

        current_width_me = window.getCoordinates().width;
        //console.log(current_width_me);

        if (current_width_me >= 1020 && current_width_me <= 1330) {
            slider_w = current_width_me - 1010;
            $('slider-info-box').setStyle('display','block');
            $('slider-info-box').setStyle('width',slider_w);
            if (slider_w < 150){
                $('current-slider-item-text').fade(0);
            } else {
                $('current-slider-item-text').fade(1);
            }
        } else if (current_width_me < 1020) {
            $('slider-info-box').setStyle('display','none');
        } else {
            $('slider-info-box').setStyle('display','block');
            $('slider-info-box').setStyle('width', 300);        }
    }
}

function moveBlocks(k) {
    var box;

    for(var i=1;i<11;i++){
        box=('box-'+i).toString();
        if(document.getElementById(box)) {
            $(box).store('morph', new Fx.Morph(box, {duration: 'long', transition: Fx.Transitions.linear.easeOut}));
        }
    }
    $('wrapper').set('tween',{
        duration: 1000,
        transition: Fx.Transitions.linear.easeOut});
    $('middle_box').set('tween',{
        duration: 1000,
        transition: Fx.Transitions.linear.easeOut});
    $('search-input').set('tween',{
        duration: 1000,
        transition: Fx.Transitions.linear.easeOut});
//    if(document.getElementById('slider-info-box')) {
//        $('slider-info-box').set('morph', {
//            duration: 1000,
//            transition: Fx.Transitions.linear.easeOut
//        });
//    }

    if(k==2){
        $('wrapper').tween('width', 1330);
        $$('.hidden_products').removeClass('none');
        $('middle_box').tween('height',1360);
        $('search-input').tween('width',300);
        if(document.getElementById('calendar-box-relative')) {
            $('calendar-box-relative').tween('width',756);
        }
        if(document.getElementById('main-content-slider')) {
            $('main-content-slider').addClass('wide');
        }
        if(document.getElementById('slider-info-box')) {
            $('slider-info-box').morph({
                'height':[74,345],
                'left':[0,630]
            }).fade('show');
        }
        if(document.getElementById('box-3')) {
            $('box-3').retrieve('morph').start({
                top:[659,410],
                left:[0,990]
            });
        }
        if(document.getElementById('box-4')) {
            $('box-4').retrieve('morph').start({
                top:[950,659],
                left:[0,660]
            });
        }
        if(document.getElementById('box-5')) {
            $('box-5').retrieve('morph').start({
                top:[659,659],
                left:[330,0]
            });
        }
        if(document.getElementById('box-6')) {
            $('box-6').retrieve('morph').start({
                top:[950,737],
                left:[330,990]
            });
        }
        if(document.getElementById('box-7')) {
            $('box-7').retrieve('morph').start({
                top:[1240,952],
                left:[0,0]
            });
        }
        if(document.getElementById('box-8')) {
            $('box-8').retrieve('morph').start({
                top:[1240,1030],
                left:[330,990]
            });
        }
        if(document.getElementById('box-9')) {
            $('box-9').retrieve('morph').start({
                top:[659,955],
                left:[660,660]
            });
        }
        if(document.getElementById('box-10')) {
            $('box-10').retrieve('morph').start({
                top:[1060,659],
                left:[660,330]
            });
        }
    } else if(k==1){
        $$('.hidden_products').addClass('none');
        $('wrapper').tween('width',980);
        $('middle_box').tween('height',1640);
        $('search-input').tween('width',125);
        if(document.getElementById('calendar-box-relative')) {
            $('calendar-box-relative').tween('width',505);
        }
        if(document.getElementById('main-content-slider')) {
            $('main-content-slider').removeClass('wide');
        }
        if(document.getElementById('slider-info-box')) {
            $('slider-info-box').morph({
                'height':[345,74],
                'left':[630,0]
            });
            $('slider-info-box').fade('hide');
        }
        if(document.getElementById('box-3')) {
            $('box-3').retrieve('morph').start({
                top:[410,659],
                left:[990,0]
            });
        }
        if(document.getElementById('box-4')) {
            $('box-4').retrieve('morph').start({
                top:[659,950],
                left:[660,0]
            });
        }
        if(document.getElementById('box-5')) {
            $('box-5').retrieve('morph').start({
                top:[659,659],
                left:[0,330]
            });
        }
        if(document.getElementById('box-6')) {
            $('box-6').retrieve('morph').start({
                top:[737,950],
                left:[990,330]
            });
        }
        if(document.getElementById('box-7')) {
            $('box-7').retrieve('morph').start({
                top:[952,1240],
                left:[0,0]
            });
        }
        if(document.getElementById('box-8')) {
            $('box-8').retrieve('morph').start({
                top:[1030,1240],
                left:[990,330]
            });
        }
        if(document.getElementById('box-9')) {
            $('box-9').retrieve('morph').start({
                top:[955,659],
                left:[660,660]
            });
        }
        if(document.getElementById('box-10')) {
            $('box-10').retrieve('morph').start({
                top:[659,1060],
                left:[330,660]
            });
        }
    }

}

window.addEvent('domready',function(){

    slider_resize();
    var i=0;
    if(document.getElementById('box8')) {
        var handles8_more = $$('#handles8_more span');
        var nS8 = new noobSlide({
            box: $('box8'),
            items: $$('#box8 a'),
            size: 630,
            autoPlay: true,
            interval: 7000,
            handles: $$('#handles8 span'),
            onWalk: function(currentItem,currentHandle){
                //style for handles
                $$(this.handles,handles8_more).removeClass('active');
                $$(currentHandle,handles8_more[this.currentIndex]).addClass('active');
                var curid = this.items[this.currentIndex].get('id').split('-').pop();
                if ($('slider-hidden-text-'+curid)){
                    $('current-slider-item-text').set('html', $('slider-hidden-text-'+curid).get('html'));
                }
                //text for "previous" and "next" default buttons
            }
        });
        //more "previous" and "next" buttons
        //more handle buttons
        nS8.addHandleButtons(handles8_more);
        //walk to item 3 witouth fx
    }
    if($('search-input').get('value') == 'поиск') {
         setAutoRemove('search-input',$('search-input').get('value'));
    }
    
    if(document.getElementById('countries-select')) {
        $('countries-select').addEvent('change', function(evt) {
            if(document.getElementById('cities-select')) {
                $('default-city').setAttribute('selected', 'selected');
            }
            if(document.getElementById('search-country-select')) {
                var action = this.getParent('form').get('action');
                var selected = $('countries-select').getSelected();
                action = action.replace(/(&country=.+)/gi,'&country='+selected.get('rel'));
                this.getParent('form').set('action', action);
            }
            if(document.getElementById('search-city-select')) {
                var action = this.getParent('form').get('action');
                var selected = $('countries-select').getSelected();
                action = action.replace(/(&city=.+)/gi,'&city='+selected.get('rel'));
                this.getParent('form').set('action', action);
            }
            this.getParent('form').submit();
        });
    }

    if(document.getElementById('cities-select')) {
        $('cities-select').addEvent('change', function(evt) {
            this.getParent('form').submit();
        });
    }

    $$('.product_menu_tab').each(function(item){
        item.addEvent('click', function(evt){
            if(!item.hasClass('menu_item_act')) {
                $$('.product_menu_tab').removeClass('menu_item_act');
                item.addClass('menu_item_act');
                $$('.product_tab_window').addClass('none');
                $(item.id+'-window').removeClass('none');
            }
        });
    });

    /*current_width = window.getCoordinates().width;

     if($('slider-info-box') && current_width >= 1330){
     if(document.getElementById('slider-info-box')) {
     $('slider-info-box').morph({
     'height':[74,345],
     'left':[0,630]
     });
     }
     $('wrapper').setStyle('width', '1310px');
     $$('.hidden_products').removeClass('none');
     $('middle_box').setStyle('height','1360px');
     $('search-input').setStyle('width','300px');
     if(document.getElementById('calendar-box-relative')) {
     $('calendar-box-relative').tween('width',756);
     }
     if($('main-content-slider')) {
     $('main-content-slider').addClass('wide');
     }
     if($('box-1')) {
     $('box-1').setStyles({top:410,left:0});
     $('box-2').setStyles({top:410,left:660});
     $('box-3').setStyles({top:410,left:990});
     $('box-4').setStyles({top:659,left:660});
     $('box-5').setStyles({top:659,left:0});
     $('box-6').setStyles({top:737,left:990});
     $('box-7').setStyles({top:952,left:0});
     $('box-8').setStyles({top:1030,left:990});
     $('box-9').setStyles({top:955,left:660});
     $('box-10').setStyles({top:659,left:330});
     }
     if($('main-content-slider')) {
     $('main-content-slider').addClass('wide');
     }
     } else if ($('slider-info-box')) {
     if($('main-content-slider')) {
     $('main-content-slider').removeClass('wide');
     }

     $('wrapper').setStyle('width', '980px');
     $('middle_box').setStyle('height','1640px');
     $('search-input').setStyle('width','125px');
     if($('box-1')) {
     $('box-1').setStyles({top:410,left:0});
     $('box-2').setStyles({top:410,left:660});
     $('box-3').setStyles({top:659,left:0});
     $('box-4').setStyles({top:950,left:0});
     $('box-5').setStyles({top:659,left:330});
     $('box-6').setStyles({top:950,left:330});
     $('box-7').setStyles({top:1240,left:0});
     $('box-8').setStyles({top:1240,left:330});
     $('box-9').setStyles({top:659,left:660});
     $('box-10').setStyles({top:1060,left:660});
     }
     }

     if(!$("main-content-slider-0")){
     if (window.getCoordinates().width <= 980){
     $("search-input").setStyle('width',160);
     } else if (window.getCoordinates().width >= 1150){
     $("search-input").setStyle('width',300);
     } else {
     $("search-input").setStyle('width',$('wrapper').getCoordinates().width - 825);
     }
     } */

    var roar = new Roar({
        position:'upperCenter'
    });

    $$('.add_to_favourite').each(function(item){
        item.addEvent('click', function(evt){
            if(!item.hasClass('add_to_favourite_inactive')) {
                var id = item.id.split('-').pop();
                new Request.JSON({
                    'url' : lang+'/catalog/add_to_favourite.json',
                    onSuccess: function(res) {
                        if(res == true) {
                            item.addClass('add_to_favourite_inactive');
                            roar.alert('Сообщение', 'Объект успешно добавлен в избранное');
                        }
                    }
                }).post({
                    'id' : id,
                    'type' : $('favourite-object-type').get('html')
                });
            } else if(item.hasClass('not_registered')) {
                roar.alert('Сообщение', 'Для добавления объекта в избранное зарегистрируйтесь или выполните вход');
            } else {
                roar.alert('Сообщение', 'Этот объект уже есть у вас в избранном');
            }
        });
    });

    $$('.answer_to_comment').each(function(item){
        item.addEvent('click', function(evt){
            var id = item.get('id').split('-').pop();
            $('node-id-parent').set('value', id);
            $('answer-form-'+id).grab($('form-wrapper'));
            $$('.answer_to_comment').removeClass('none');
            item.addClass('none');
            id = null;
        });
    });

    $$('.list_item_manuf').each(function(item){
        if(item.get('id')){
            item.addEvent('mouseenter', function(evt){
                if(document.getElementById('manufacturer-image-info-'+item.get('id').split('-').pop())) {
                    $('manufacturer-image-info-'+item.get('id').split('-').pop()).setStyle('display', 'block');
                }
            });
            item.addEvent('mouseleave', function(evt){
                $$('.item_inf').setStyle('display', 'none');
                /*if(document.getElementById('product-image-info-'+item.get('id').split('-').pop())) {
                 $('product-image-info-'+item.get('id').split('-').pop()).dissolve();
                 }*/
            });
        }
    });

    /*if(document.getElementById('user-country-city')) {
     var inputword2 = $('user-country-city');

     var aucomp = new Autocompleter.Request.HTML(inputword2, lang+'/search_city/', {
     'indicatorClass': 'autocompleter-loading', // class added to the input during request
     'minLength': 3, // We need at least 1 character
     'selectMode': 'type-ahead', // Instant completion
     'multiple': false, // Tag support, by default comma separated
     'onComplete': function() {
     if(!aucomp.request.response.elements.length) {
     inputword2.addClass('reg_error');
     } else {
     inputword2.removeClass('reg_error');
     }
     },
     'injectChoice': function(choice) {
     var value = choice.innerHTML;
     // inputValue saves value of the element for later selection
     choice.inputValue = value;
     // overrides the html with the marked query value (wrapped in a <span>)
     choice.set('html', this.markQueryValue(value));
     // add the mouse events to the <li> element
     this.addChoiceEvents(choice);
     choice.addEvent('click', function(evt){
     if(evt) {
     evt.stop();
     }
     $('user-country-hidden').set('value', choice.get('value'));
     $('user-city-hidden').set('value', choice.get('id').split('-').pop());
     });
     }
     });
     $('user-country-city').addEvent('keydown', function(evt){
     if(evt.code == 13) {
     if(aucomp.queryValue) {
     aucomp.selected.fireEvent('click');
     }
     }
     });
     } */

    /*window.addEvent('resize', function(){
     slider_resize();

     if($('slider-info-box')){
     if ((current_width < 1330) && (window.getCoordinates().width >= 1330)) {
     current_width = window.getCoordinates().width;
     $$('.hidden_products').removeClass('none');
     moveBlocks(2);
     } else if ((current_width >= 1330) && (window.getCoordinates().width < 1330)) {
     current_width = window.getCoordinates().width;
     $$('.hidden_products').addClass('none');
     moveBlocks(1);
     }
     }

     searchAutoWidth();
     });*/
    /*if( document.getElementById('background-info-box') ) document.getElementById('background-info-box').setStyle('display','none');

     if( document.getElementById('background-info-button') ){
     document.getElementById('background-info-button').addEvent('click',function(){
     if( document.getElementById('background-info-box').getStyle('display') == 'block' ){
     document.getElementById('background-info-box').setStyle('display','none');
     } else {
     document.getElementById('background-info-box').setStyle('display','block');
     }
     });
     }*/

    if(document.getElementById('main-slider')){
        if($$('.ms_item').length > 1) {
            mainSlider(document.getElementById('main-slider'));
        } else {
            var imgAsset = new Asset.images($('main-slider').getElementsByTagName('img'),{
                onComplete:function(){
                    $('main-slider').getElement('.main_slider_preloader').fade('out');
                    $$('.ms_item').each(function(item){
                        item.setStyle('left',0);
                    })
                }
            });
        }
    }

    if($$('.oip_title').length>0){
        $$('.oip_title').getNext('.oip_container')[0]._height = $$('.oip_title').getNext('.oip_container')[0].offsetHeight;
        $$('.oip_title').getNext('.oip_container')[0]._tween = new Fx.Tween($$('.oip_title').getNext('.oip_container')[0],{duration:300,onComplete:function(){if(this.element.offsetHeight>0) this.element.setStyle('height','auto')}});
        $$('.oip_title').getNext('.oip_container')[0].setStyle('height',0);
        $$('.oip_title').addEvent('click',function(){
            if(this.getNext('.oip_container').offsetHeight == 0){
                this.getNext('.oip_container')._tween.start('height',this.getNext('.oip_container')._height);
            } else {
                this.getNext('.oip_container')._height = this.getNext('.oip_container').offsetHeight;
                this.getNext('.oip_container')._tween = new Fx.Tween(this.getNext('.oip_container'),{duration:300,onComplete:function(){if(this.element.offsetHeight>0) this.element.setStyle('height','auto')}});
                this.getNext('.oip_container')._tween.start('height',this.getNext('.oip_container')._height,0);
            }
        })
    }

    if($('information-more')) {
        $('information-more').addEvent('click', function(evt){
            if($('information-text').hasClass('information_text_full')) {
                $('information-text').removeClass('information_text_full');
                $('information-more').innerHTML = 'Показать полностью';
            } else {
                $('information-text').addClass('information_text_full');
                $('information-more').innerHTML = 'Скрыть';
            }
        });
    }

    if(document.getElementById('submit-comment-form-login')) {
        $('email').addEvent('keydown', function(evt){
            if(evt.code==13){
                evt.stop();
            }
        });
        $('password').addEvent('keydown', function(evt){
            if(evt.code==13){
                evt.stop();
                $('submit-comment-form-login').fireEvent('click');
            }
        });
        $('submit-comment-form-login').addEvent('click', function(evt){
            var eerr, perr = 0;
            if(($('email').value != null) && ($('email').value != '')) {
                if(validEmail($('email').value)){
                    $('email-error').addClass('hidden');
                    $('email').removeClass('reg_error');
                    eerr = 0;
                } else {
                    $('email-error').removeClass('hidden');
                    $('email').addClass('reg_error');
                    eerr = 1;
                }
            } else {
                $('email-error').removeClass('hidden');
                $('email').addClass('reg_error');
                eerr = 1;
            }
            if(($('password').value == null) || ($('password').value == '')) {
                $('password-error').removeClass('hidden');
                $('password').addClass('reg_error');
                perr = 1;
            } else {
                $('password-error').addClass('hidden');
                $('email').removeClass('reg_error');
                perr = 0;
            }
            if(eerr == 0 && perr == 0) {
                new Request.JSON({
                    'url' : 'ru/check_login_info.json',
                    onComplete: function(res) {
                        if(res == true) {
                            $('comment-form-login').submit();
                        } else {
                            $('password-error').removeClass('hidden');
                            $('email').addClass('reg_error');
                            $('password').addClass('reg_error');
                        }
                    }
                }).post({
                    'email': $('email').value,
                    'password': $('password').value
                });
            } else {
            }
        });
    }

    if($('search-country-select')) {

    }

});
window.addEvent('load', function(){
    if(document.getElementById('user-country-city')) {
        var inputwordc = $('user-country-city');

        var aucompc = new Autocompleter.Request.HTML(inputwordc, lang+'/search_city/', {
            'indicatorClass': 'autocompleter-loading', // class added to the input during request
            'minLength': 1, // We need at least 1 character
            //'selectMode': 'type-ahead', // Instant completion
            'multiple': false, // Tag support, by default comma separated
            'onComplete': function() {
                if(!aucompc.request.response.elements.length) {
                    inputwordc.addClass('reg_error');
//                    inputwordc.addClass('input_error');
   //                 inputwordc.removeClass('input_succes');
                }
//              else {
//                    inputwordc.removeClass('input_error');
  //                  inputwordc.addClass('input_succes');
//                }
            },
//            'onBlur': function() {
//                if(aucompc.selected.get('value')) {
//                    $('user-country-hidden').set('value', aucompc.selected.get('value'));
//                    $('user-city-hidden').set('value', aucompc.selected.get('id').split('-').pop());
//                    inputwordc.addClass('input_succes');
//                }
//            },
            'injectChoice': function(choice) {
                var value = choice.innerHTML;
                // inputValue saves value of the element for later selection
                choice.inputValue = value;
                // overrides the html with the marked query value (wrapped in a <span>)
                choice.set('html', this.markQueryValue(value));
                // add the mouse events to the <li> element
                this.addChoiceEvents(choice);
                choice.addEvent('click', function(evt){
                    if(evt) {
                        evt.stop();
                    }
                    $('user-country-hidden').set('value', choice.get('value'));
                    $('user-city-hidden').set('value', choice.get('id').split('-').pop());
                    $('user-country-city').fireEvent('blur',$('user-country-city'),1);
                    inputwordc.addClass('input_succes');
                    inputwordc.removeClass('input_error');
                });
            }
        });
//        $('user-country-city').addEvent('keydown', function(evt){
//            alert(5);
//            if(evt.code == 13) {
//                if(aucompc.selected.get('value')) {
//                    $('user-country-hidden').set('value', aucompc.selected.get('value'));
//                    $('user-city-hidden').set('value', aucompc.selected.get('id').split('-').pop());
//                    $('user-country-city').fireEvent('blur',$('user-country-city'),1);
//                }
//            } else if(evt.code == 8) {
//                $('user-country-hidden').set('value', '');
//                $('user-city-hidden').set('value', '');
//            }
//        });

        $('user-country-city').addEvent('change', function(evt){
            $('user-country-hidden').set('value', '0');
            $('user-city-hidden').set('value', '0');
            inputwordc.removeClass('input_succes');
            inputwordc.addClass('input_error');
        });

    }
});

function mainSlider(slider){
    var mainDuration = 400;
    var mainDurationLong = 5000;
    var mainSliderWidth = slider.offsetWidth;
    var activeItem = 0;
    var sliderItem = slider.getElements('.ms_item');
    sliderItem.each(function(item){
        item._tween = new Fx.Tween(item,{duration:mainDuration})
    });
    var sliderControls = slider.getElements('.ms_controls');

    var imgAsset = new Asset.images(slider.getElementsByTagName('img'),{
        onComplete:function(){
            slider.getElement('.main_slider_preloader').fade('out');
            sliderItem.each(function(item,index){
                if(index==activeItem) item.setStyle('left',0);
            })
        }
    });

    controlsFunction = function(evt){
        if(sliderControls.indexOf(evt.target) != activeItem){
            sliderEvent(sliderControls.indexOf(evt.target));
        }
    }

    function sliderEvent(next){
        sliderItem[next].setStyle('left',mainSliderWidth);

        sliderItem[activeItem]._tween.start('left',-mainSliderWidth);
        sliderItem[next]._tween.start('left',0);

        sliderControls[activeItem].removeClass('act_ms_controls');
        sliderControls[next].addClass('act_ms_controls');

        activeItem = next;
    }

    var mainSliderTimer = setInterval(function(){
        mainSliderInterval()
    },mainDurationLong);

    function mainSliderInterval(){
        if(activeItem+2>sliderItem.length) {
            sliderEvent(0);
        } else {
            sliderEvent(activeItem+1);
        }
    }

    slider.addEvents({
        mouseenter:function(){
            clearInterval(mainSliderTimer);
        },
        mouseleave:function(){
            mainSliderTimer = setInterval(function(){
                mainSliderInterval()
            },mainDurationLong);
        }
    })

    sliderControls.each(function(item){
        item.addEvent('click',controlsFunction);
    })

}
function validEmail(string){
    return /^((([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+(\.([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+)*)@((((([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.))*([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.)[\w]{2,4}|(((([0-9]){1,3}\.){3}([0-9]){1,3}))|(\[((([0-9]){1,3}\.){3}([0-9]){1,3})\])))$/.test(string);
}
