window.addEvent('domready',function() {
    /* settings */
    if($('TickerVertical')!==null)
    {
        var list = $('TickerVertical');
        var items = list.getElements('li');
        var showDuration = 10000;
        var scrollDuration = 500;
        var index = 0;
        var size = $('TickerVertical').getSize();
        var height =157;
        /* action func */
        var move = function() {
            list.set('tween',{
                duration: scrollDuration,
                onComplete: function() {
                    if(index == items.length/2 - 2) {
                        index = 0 - 1;
                        list.scrollTo(0,0);
                    }
                }
            }).tween('margin-top',0 - (++index * height));
        };
   
        window.addEvent('load',function() {		
            move.periodical(showDuration);
        });
    }
});
 

window.addEvent('domready',function(){
    initialize_user();
});


function price_calc()
{
    if ($('prod_descr'))
        var jsonRequest = new Request.JSON({
            url: 'modules/catalog_manager/ajax/actions.php?action=price_data', 
            onSuccess: function(price){
            
                $('price').innerHTML = price.price;
                (price.comment=='')?($('comment_block').setStyle('display','none')):($('comment_block').setStyle('display','block'));
                $('comment').innerHTML = price.comment; 
                $('total').innerHTML = price.total; 
                $('count_price').innerHTML = price.count_price;
                $('exist').innerHTML = price.exist;
                /*   if (price.exist=='Товар временно отвутствует')
                {
                    $('count_block').setStyle('display','none');
                    $('total_block').setStyle('display','none');
                    $('buy').setStyle('display','none');
                }
                else
                {
                    $('count_block').setStyle('display','block');
                    $('total_block').setStyle('display','block');
                    $('buy').setStyle('display','block');
                }*/
                $('articul').innerHTML = price.articul;
                $('prod_label').innerHTML = price.prod_label;
            }
        }).get({
            'price_id': $('prod_descr').getAttribute('data-id'), 
            'count': $('count_input').value
        });
}



function initialize_user()
{   
    slider();
    //  initialize_onscreen();
    if ($('send_button'))
    {
        $('send_button').addEvent('click', function(e) {
            window.location = site_url+'virtual_fitting';
        });
    }
    
    function color_selector()
    {
        if ($('color_slider')!==null)
        {
            var item = $$('#color_slider .color_item');
            //    $('color_slider').setStyle('display',(item.length==1)?'none':'block');
            $('colors_selector').setStyle('display',item.length>1?'block':'none');
            $('colors_selector').setStyle('cursor',item.length>1?'pointer':'default');
            
           
            
            if(item.length>1)
            {
                $('colors').setAttribute('data-color', item[0].getAttribute('data-color'));
                $('colors_selector').removeEvents('click');
                $('colors_selector').addEvent('click', function(e) {
                
                    var new_height =  ((col.getSize().y)!==height)?height:($$('.color_item').length*(height+10));
                    col.tween('height',new_height);
                });
            }
            $$('.color_item').removeEvents('click');
            $$('.color_item').addEvent('click', function(e) {
                
                color_select_item(this);
                
            });
            
            var i = 0;

            if($('color_slider')!==null)
            {
                if($$('#color_slider .color_item').length>0)
                {
                    
                    with($('color_slider'))

                    {
                        var line = $('prod_panel_c');
                        var img = $$('#color_slider .color_item');
                        var last_ = $('last_c');
                        var next_ = $('next_c');
                        (i==0)?fadeOut(last_):fadeIn(last_);
                        (i>=img.length-5)?fadeOut(next_):fadeIn(next_);
                        line.setStyle('width',((img[0].getSize().x+15)*(img.length))+'px');
                        $$('.group_unit_line_c').setStyle('width',((img[0].getSize().x+15)*(img.length))+'px');
                        function list(nid)
                        {
                            i = nid;
                            {
                                if(i==0){
                                    last_.removeClass('last-act');
                                    next_.removeClass('next-no');
                                }else{
                                    if(i==img.length-1){
                                        next_.addClass('next-no');
                                    }else{
                                        next_.removeClass('next-no');
                                    }
                                    last_.addClass('last-act');
                                }
                                if (i<img.length)
                                    line.morph({
                                        'margin-left':"-"+(img[0].getSize().x+15)*i+'px'
                                    });
                            }
                        }

                        next_.addEvent('mousedown',function(e){
                            if(i>=img.length-5){
                                e.stop();
                
                            }else{
                                i++
                                list(i);
                                if(i>=img.length-5)
                                {
                                    fadeOut(next_);
                                    next_.setStyle('background-position','-19px center');
                                }
                                else
                                {
                                    fadeIn(next_);
                                }
                                fadeIn(last_);
                            }
                        });
                        next_.addEvent('mouseover',function(e){
                            if(i>=img.length-5){
                                e.stop();
                            }else{
                                next_.setStyle('background-position','-58px center');
                            }
                        });
                        next_.addEvent('mouseout',function(e){
                            if(i>=img.length-5){
                                e.stop();
                            }else{
                                next_.setStyle('background-position','-19px center');
                            }
                        });
            
                        last_.addEvent('mousedown',function(e){
                            if(i==0){
                                e.stop();
                            }else{
                                i--
                                list(i);
                                if(i==0)
                                {
                                    fadeOut(last_);
                                    last_.setStyle('background-position','0px center');
                                }
                                else
                                {
                                    fadeIn(last_);
                                }
                                fadeIn(next_);
                            }
                        });
            
                        last_.addEvent('mouseover',function(e){
                            if(i!==0){
                                $('last_').setStyle('background-position','-38px center');
                            }
                        });
                        last_.addEvent('mouseout',function(e){
                            if(i!==0){
                                last_.setStyle('background-position','0px center');
                            }
                        });

                        }
                    select_group();
                    if($('adm_line')==null)
                        $('adm_line').setStyle('margin-top','-4px');
                }
                else 
                {
                    $('color_slider').setStyle('display','none');
                    if($('adm_line')!==null)
                        $('adm_line').setStyle('margin-top','-14px');
                }
                
            }
        }    
    }
    function color_select_item(elem)
    {
        if (elem)
        {
            Cookie.write("current_mod", elem.id);
            var items = $$('.color_item');
            items.setStyle("background",'');
            elem.setStyle("background",'#fff');
            $$('.border_table').setStyle("border-top","1px #838383 solid");
            $$('.border_table').setStyle("border-bottom","none");
            $('border_table_'+elem.getAttribute('data-id')).setStyle("border-bottom","1px #838383 solid");
            $('border_table_'+elem.getAttribute('data-id')).setStyle("border-top","1px #fff solid");
            $('prod_descr').setAttribute("data-id",elem.getAttribute('data-id'));
            var new_height =  ((col.getSize().y)!==height)?height:($$('.color_item').length*(height+10));
            $('colors').setAttribute('data-color', elem.getAttribute('data-color'));
            price_calc();
            if ($('add_img_link'))
            {
                $('add_img_link').setAttribute('data-obj_value', $('prod_descr').getAttribute('data-id'));
            }
            show_pictures(elem);
            prod_links_list($('code').value)
        
        }
    }
    
    function size_selector()
    {
        if ($('sizes')){
            var selector = $('sizes');
            var container = $('container');
            var size = $$('.size');
            var height = 16;
            var max_height = selector.getSize().y*size.length;
            var new_margin;
            var i = 0;
            $('container').setStyle('margin-top',0);
            selector.setStyle('background-position',size.length>1?'top':'bottom');
            size.setStyle('cursor',size.length>1?'pointer':'default');
            size.length>0?size[i].setAttribute('id','size'):false;
            selector.removeEvents('click');
            selector.addEvent('click', function(e) {
                size[i].setAttribute('id','');
                if (i<size.length-1)
                {
                    i++;
                    new_margin = -height*i;
                } 
                else
                {
                    i = new_margin = 0;
                }
                $('container').setStyle('margin-top',new_margin);
                size[i].setAttribute('id','size');
                if( $('add_img_link'))
                    $('add_img_link').setAttribute('data-obj_value', size[i].getAttribute('data-id'));
                if (size.length>1)
                    show_pictures($('size'));
                price_calc();
            });
        }
    }
    
    function count_selector()
    {
        var count_input = $('count_input');
        
        var count_block = $('count_block');
        var up = $('up');
        var down = $('down');
        
        up.addEvent('click', function(e) {
            $('count_input').value = parseInt($('count_input').value)+1;
            price_calc();
        });
        
        down.addEvent('click', function(e) {
            if (parseInt($('count_input').value)>0)
                $('count_input').value = parseInt($('count_input').value)-1;
            price_calc();
        });
        count_block.addEvent('mouseenter', function(e) {
            $('count_arrow').setStyle('display','block');
        });
        count_block.addEvent('mouseleave', function(e) {
            $('count_arrow').setStyle('display','none');
        });

        count_input.addEvent('keyup', function(e) {
            price_calc();
        });
    }
    function add_good()
    {
        var count = $('count_input')?$('count_input').value:'';
        var price =  $('prod_descr')?$('prod_descr').getAttribute('data-id'):'';  
        var jsonRequest = new Request.JSON({
            url: 'modules/catalog_manager/ajax/actions.php?action=add_good', 
            onSuccess: function(basket){
                $('basket_count').innerHTML = basket.count;
                $('count_price').innerHTML = basket.count_price;
                $('total').innerHTML = basket.total; 
                new Fx.Scroll(window, {
                    wait: false,
                    duration: 400,
                    transition: Fx.Transitions.Quad.easeInOut,
                    onComplete: function(){
                        $('basket').fireEvent('mouseover');
                    }
                }).toElement('basket');
            }
        }).get({
            count:count, 
            price_id:price
        });
    }
    
    function buy()
    {
        var buy = $('buy');
        buy.removeEvent('click');
        buy.addEvent('click', function(e) {
            add_good();
            $('count_input').value=1;
            $('count_price').highlight("#ffffff","#dadada");
            
        });
    }
    
    if ($('colors_block')!==null)
    {
        var col = $('colors_block');
        var height = col.getSize().y;
        color_selector();
        //   size_selector();
        count_selector();
        buy(); 
        var tmp = $$('.color_item');
        var current_mod = Cookie.read('current_mod');
        if($(current_mod))
            color_select_item($(current_mod));  
        else
            color_select_item(tmp[0]);
    }
    $$('#link_controls .sort_pl').removeEvent('click');
    $$('#link_controls .sort_pl').addEvent('click', function(event){
        var key_field = this.getAttribute('data-key_field');
        var key_value = this.getAttribute('data-key_value');
        var field = this.getAttribute('data-field');
        var table = this.getAttribute('data-table');
        var obj_field = this.getAttribute('data-obj_field');
        var obj_value = this.getAttribute('data-obj_value');
        var file_field = this.getAttribute('data-file_field');
        var sort_field = this.getAttribute('data-sort_field');
        var up = this.getAttribute('data-up');
        var onComplete = this.getAttribute('data-onComplete');      
        var pars = $H({
            key_field:key_field,
            key_value:key_value,
            field:field,
            table:table,
            obj_field:obj_field,
            obj_value:obj_value,
            file_field:file_field,
            sort_field:sort_field,
            up:up
        }).toQueryString();
        var myRequest = new Request.HTML({
            url: 'modules/catalog_manager/ajax/actions.php?action=sort_pl',
            method: 'get',
            evalScripts: true,
            onComplete: function(){
                //  prod_links_list($('code').value);
                setTimeout(""+onComplete+"",10);
            }
        }).send(pars);
    });
    
    gallery_events(ml);
   
    
}
function tree(name)
{
    $(name).setStyle('display',(($(name).getStyle('display')=='block')?'none':'block'));
    $('a'+name).innerHTML = ($('a'+name).innerHTML=='+ ')?'-&nbsp;&nbsp;':'+ ';
}


function slider()
{
    var i = 0;
    if($('div_catalog_links')!==null)
    {
        with($('div_catalog_links'))
        {
            var line = $('prod_panel');
            var img = $$('.uline');
            var last_ = $('last_');
            var next_ = $('next_');
            var dl = $$(".delete_link");
            (i==0)?fadeOut(last_):fadeIn(last_);
            (i>=img.length-2)?fadeOut(next_):fadeIn(next_);
            line.setStyle('width',((img[0].getSize().x+30)*(img.length))+'px');
            $$('.group_unit_line').setStyle('width',((img[0].getSize().x+30)*(img.length))+'px');
            
            function list(nid)
            {
                i = nid;
                {
                    if(i==0){
                        last_.removeClass('last-act');
                        next_.removeClass('next-no');
                    }else{
                        if(i==img.length-1){
                            next_.addClass('next-no');
                        }else{
                            next_.removeClass('next-no');
                        }
                        last_.addClass('last-act');
                    }
                    if (i<img.length)
                        line.morph({
                            'margin-left':"-"+(img[0].getSize().x+30)*i+'px'
                        });
                }
            }

            next_.addEvent('mousedown',function(e){
                if(i>=img.length-2){
                    e.stop();
                
                }else{
                    i++
                    list(i);
                    if(i>=img.length-2)
                    {
                        fadeOut(next_);
                        $('next_').setStyle('background-position','-19px center');
                    }
                    else
                    {
                        fadeIn(next_);
                    }
                    fadeIn(last_);
                }
            });
            $('next_').addEvent('mouseover',function(e){
                if(i>=img.length-2){
                    e.stop();
                }else{
                    $('next_').setStyle('background-position','-58px center');
                }
            });
            $('next_').addEvent('mouseout',function(e){
                if(i>=img.length-2){
                    e.stop();
                }else{
                    $('next_').setStyle('background-position','-19px center');
                }
            });
            
            last_.addEvent('mousedown',function(e){
                if(i==0){
                    e.stop();
                }else{
                    i--
                    list(i);
                    if(i==0)
                    {
                        fadeOut(last_);
                        $('last_').setStyle('background-position','0px center');
                    }
                    else
                    {
                        fadeIn(last_);
                    }
                    fadeIn(next_);
                }
            });
            
            $('last_').addEvent('mouseover',function(e){
                if(i!==0){
                    $('last_').setStyle('background-position','-38px center');
                }
            });
            $('last_').addEvent('mouseout',function(e){
                if(i!==0){
                    $('last_').setStyle('background-position','0px center');
                }
            });
            if ($('link_controls'))
            {
                $$('.delete_link').addEvent('click', function(event){
                    if (confirm('Удалить эту связку?'))
                    {
                        set_up(this,event);
                        prod_links_list(this.getAttribute("data-code"));
                    }
                    else return false;
                });
            }
            }
        select_group();
    }
}

function prod_links_list(code)
{
    var pars = $H({
        code:code
    }).toQueryString();

    var myRequest = new Request.HTML({
        url: 'modules/catalog_manager/ajax/actions.php?prod_links_list',
        method: 'get',
        update: 'place_for_links',
        evalScripts: true,
        onComplete: function(){
            $$('#link_controls .sort_pl').removeEvent('click');
            $$('#link_controls .sort_pl').addEvent('click', function(event){
                var key_field = this.getAttribute('data-key_field');
                var key_value = this.getAttribute('data-key_value');
                var field = this.getAttribute('data-field');
                var table = this.getAttribute('data-table');
                var obj_field = this.getAttribute('data-obj_field');
                var obj_value = this.getAttribute('data-obj_value');
                var file_field = this.getAttribute('data-file_field');
                var sort_field = this.getAttribute('data-sort_field');
                var up = this.getAttribute('data-up');
                var onComplete = this.getAttribute('data-onComplete');      
                var pars = $H({
                    key_field:key_field,
                    key_value:key_value,
                    field:field,
                    table:table,
                    obj_field:obj_field,
                    obj_value:obj_value,
                    file_field:file_field,
                    sort_field:sort_field,
                    up:up
                }).toQueryString();
                var myRequest = new Request.HTML({
                    url: 'modules/catalog_manager/ajax/actions.php?action=sort_pl',
                    method: 'get',
                    evalScripts: true,
                    onComplete: function(){
                        //  prod_links_list($('code').value);
                        setTimeout(""+onComplete+"",10);
                    }
                }).send(pars);
            });
            slider();
        //   initialize_user();
        }
    }).send(pars);
}

/*
var color_id;
function price_select(id)
{
    function chg(first,second){
        if (first!==second)
        {
            var d1=first;
            var d2=second;
            var d11=d1.cloneNode(true);
            var d22=d2.cloneNode(true);
            d2.parentNode.insertBefore(d11,d2);
            d1.parentNode.insertBefore(d22,d1);
            d1.parentNode.removeChild(d1);
            d2.parentNode.removeChild(d2);
        }
    }
    color_id = id;
    
    if ($('price_'+color_id).getStyle('position')!=='absolute')
    //     with ($('price_'+prod_id).parentNode)
    {
        $('price_'+color_id).setStyles({
            position:'absolute',
            overflow:'visible',
            border:'1px #ccc solid'
        });
        var costs =  $$('.cost'); 
        for (var i=0;i<costs.length;i++)
        { 
            costs[i].addEvent('mouseover', function(event){
                this.setStyles({
                    background:'#eee',
                    cursor:'pointer'
                });
            });
            costs[i].addEvent('mouseout', function(event){
                this.setStyle('background','inherit');
            });
            costs[i].addEvent('click', function(event,i){
                this.setStyle('background','inherit');   
                var costs =$('price_'+color_id).getElementsByClassName('cost'); 
                this.setAttribute('id','color_name');
                chg($(costs[0]),this);
               
                price_select(color_id);
                var price_id = this.getAttribute('data-id');
                $('price_'+id).setAttribute('data-price_id',price_id);
            });
        }    
    }
    else
    {
        $('price_'+id).setStyles({
            position:'',
            overflow:'hidden',
            border: 'none'
        });
    }
    
}*/ 
var curent_menu = '';
var focus=false;
var tid;
function submenu()
{
    if ($$('.top_menu')!==null)
    {

        $$('.top_menu').addEvent('click', function(e) 
        { 
            // alert("1");
            var myValues = this.getCoordinates();
            var myValues_ = $('topmenu').getCoordinates();
            var y = myValues.top;
            var x = myValues.left;
            var y_ = myValues_.top;
            var x_ = myValues_.left;
            if($('menu_'+this.id)!==null)
            {
                /*          if ($('menu_'+this.id).getStyle('visibility')!=='hidden')
                    fadeOut($('menu_'+this.id));
                else*/
                // {
                $$('.submenu').setStyle('display','none');
                $('menu_'+this.id).setStyle('top', y_);
                $('menu_'+this.id).setStyle('left', x-x_-74);
                
                
                if(Browser.name == 'opera'){                   
                    $('menu_'+this.id).setStyle('display', 'block').setStyle('opacity', '1');
                }
                else
                    fadeIn($('menu_'+this.id)); 
                //  tid = this.id;
                //  setTimeout("$('menu_'+tid).setStyles({'display':'block',opacity:'1'})",'300');

                curent_menu = this.id;
            //   }
            }
        });
        $$('.submenu').addEvent('mouseup',function(e){
            if(Browser.name == 'opera'){                   
                $(this).setStyle('display', 'none').setStyle('opacity', '0');
            }
            else
                fadeOut(this);
            curent_menu = '';
            focus=false;
        });  
        $$('.submenu').addEvent('mouseleave', function(e) 
        {
            if(Browser.name == 'opera'){                   
                $(this).setStyle('display', 'none').setStyle('opacity', '0');
            }
            else
                fadeOut(this);
            curent_menu = '';
            focus=false;
        });
    }
}

function banner_page_img()
{
    var banner_page = $('banner_page');
    var page_id = banner_page.getAttribute("data-page_id");
    var jsonRequest = new Request.JSON({
        url: 'modules/partition_manager/ajax/actions.php', 
        onSuccess: function(banner){
            banner_page.setStyle('background',"url('"+ banner.bg+"') no-repeat center center");

        }
    })
    .get({
        action:'banner_page_img',
        page_id:page_id
    });
}

window.addEvent('domready', function() 
{
    submenu();
});
 
window.addEvent('domready',function(){
    price_recalc();
    send_order();
    basket_popup();
    if ($('suffix'))
    {
        $('suffix').innerHTML= $$(".detalies").length==1?"е":($$(".detalies").length<5?"я":"й");
    }
});


function send_order()
{
    if ($("send_order_button"))
    {
        
        $('send_order_button').addEvent('click', function(e) {
                
            var error=null;
            var name= $('contact_name').value;
            var phone= $('contact_phone').value;
            var email= $('contact_email').value;
            var comment= $('contact_comment').value;
            if (name=='')
                error = "Укажите, пожалуйста, свое имя";
            if (phone=='')
                error = name==''?error+" и контактный телефон":"Укажите, пожалуйста, контактный телефон";
            if (!error)
            {
                
                var price_id = this.getAttribute('data-id');
                var count = this.value;
                var jsonRequest = new Request.JSON({
                    url: 'modules/orders_manager/ajax/actions.php?action=send_order', 
                    onSuccess: function(price){
                   
                    }
                }).get({
                    'name': name, 
                    'phone': phone,
                    'email': email,
                    'comment': comment
                });
                $('basket_page').innerHTML = "<div style='padding:15px'><h1>Ваш заказ успешо отправлен!</h1></div>";
            }
            else alert(error);
        });
       
        
    }
        
}


function price_recalc()
{
    
    $$('.count_input').addEvent('keyup', function(e) {
        var price_id = this.getAttribute('data-id');
        var count = this.value;
        
        var jsonRequest = new Request.JSON({
            url: 'modules/orders_manager/ajax/actions.php?action=recalc', 
            onSuccess: function(price){
                $('discount_'+price_id).innerHTML = price.discount;
                $('ts').innerHTML = price.ts; 
                $('total_'+price_id).innerHTML = price.total; 
            }
        }).get({
            'price_id': price_id, 
            'count': count
        });
    });
}

function basket_unit_delete(price_id)
{
    if (confirm("Удалить этот товар из корзины?"))
    {
        var pars = $H({
            price_id:price_id,
            action:'basket_unit_delete'
        }).toQueryString();
        var myRequest = new Request.HTML({
            url: 'modules/orders_manager/ajax/actions.php',
            method: 'get',
            update: 'basket_table_container',
            evalScripts: true,
            onComplete: function(){ 
                price_recalc();
                send_order();
                var jsonRequest = new Request.JSON({
                    url: 'modules/catalog_manager/ajax/actions.php?action=basket_count', 
                    onSuccess: function(basket){
                        $('basket_count').innerHTML = basket.count;
                        if (basket.count==0){
                            $('basket_page').innerHTML = "<div style='padding:15px'><h1>Ваша корзина пуста!</h1></div>";
                        }
                    }
                })
                .get({
                    });
            }
        
        }).send(pars);
    }
}



function basket_popup()
{
    if(!$('basket_popup'))
    {
        var trashield = new Element('div', {
            id:'basket_popup'
        });
        trashield.addEvent('mouseleave', function(e) {
            fadeOut(this);
        });
        trashield.inject($('page'),'top'); 
    }
  
    if ($('basket'))
    {
        $('basket').addEvent('mouseover', function(e) {
            var myRequest = new Request.HTML({
                url: 'modules/orders_manager/ajax/actions.php?action=basket_popup',
                method: 'get',
                update: 'basket_popup',
                evalScripts: true,
                onComplete: function(){
                    if ($('basket_popup').innerHTML.indexOf('пуста')==-1)
                    {
				
					
					if( $$('.basket_table')[0])
                        $$('.basket_table')[0].setStyle('display','block')
                    }else{
					$('basket_out_popup').innerHTML = 'Ваша корзина пуста';
					
					//$$('.basket_table')[0].setStyle('display','none')
                    }
                    fadeIn($('basket_popup'));
                }
            }).send();
            
        });
        $('basket_popup').addEvent('click', function(e) {
            window.location= site_url+"order/";
        });
    }
  

}
 

var next=0;
var curent=0;
window.addEvent('domready', function() 
{
    if ($('vitrina_block_slider')!==null)
    {
        $('vitrina_block_slider').addEvent('click', function() 
        {
            list_portfolio();
        });
        setInterval('list_portfolio()',11000);
    }
    select_group();
    
    if ($$('.cost')[0]&&$('smeta_block'))
    {
        $('smeta_block').setStyle('display',$$('.cost')[0].innerHTML==''?'none':'block');
    }
//  button_buy();
});
/* баннер витрины */
function list_portfolio()
{
    var nodeList = $('vitrina_block_slider').getElementsByTagName("div");
    var t=0;
    var slides = new Array();
    for (var i = 0; i < nodeList.length; i++)
    {
        if (nodeList[i].getAttribute('class')=='v_el_slider')
        {
            slides[t] = nodeList[i];
            fadeOut(slides[t]);
            t++;
        }
    }
    
    for (var i = 0; i < slides.length; i++)
    {
        if ((getStyle_(slides[i],'display') == 'block'))
            curent = i;
        if (curent<slides.length-1)
        {
            next = curent+1;
        }
        else next=0;
        if (curent!==i)
        {
            fadeOut(slides[i]);
            slides[i].setStyle('display','none');
        }
    }
    $('vitrina_block_slider').setStyle('background-image',getStyle_(slides[curent],'background-image'));
    $('vitrina_block_slider').setStyle('background-position',getStyle_(slides[curent],'background-position'));
    $('vitrina_block_slider').setStyle('background-repeat',getStyle_(slides[curent],'background-repeat'));
    
    if (slides[next])
    {
        slides[next].setStyle('position','absolute');
        slides[next].setStyle('position','inherit');
        slides[next].setStyle('display','block');
        fadeIn(slides[next]);
        slides[curent].setStyle('position','inherit');
        fadeOut(slides[curent]);
        slides[curent].setStyle('display','none');
    }
} 
var ml='';
window.addEvent('domready',function(){
    gallery_events(ml);
});


function gallery_events(ml)
{
    var i = 0;
    if($('photo_block')!==null)
    {
        var wrapper = $('photo_block');
        var view = $('view');
        var line = $('line');
        var img = $$('.photo');
        var del = $$('.delete_photo');
        var up = $$('.up_photo');
        var sort = $$('.sort');
        var add = $$('.add_photo');
        var separator = $$('.separator');
        var nav = new Element('div', {
            id:'nav',
            html:'<span id="last"></span><span id="next"></span>'
        });

        var width = ((img[0].getSize().x+separator[0].getSize().x)*(img.length)+'px');
        line.setStyles({
            'width':width,
            'margin-left':ml
        });
        nav.inject(wrapper);
        i==0?fadeOut($('last')):fadeIn($('last'));
        i>=img.length-3?fadeOut($('next')):fadeIn($('next'));

        function display(el){
            var src = el.getAttribute('data-image');
            var img = view;
            img.addEvent('load', function(){
                fadeIn(img);
            });

            view.setStyle('background-image', "url('"+src+"')");
            fadeIn(view);
        }

        function thumbStyle(img,e){
            img.each(function(el,i){
                if(el.hasClass('active-thumb')){
                    el.removeClass('active-thumb');
                }
                if(e==i){
                    el.addClass('active-thumb');
                }
            });
        }

        function list(nid){
            i = nid;
            with ($('thumb')){
                if(i==0){
                    $('last').removeClass('last-act');
                    $('next').removeClass('next-no');
                }else{
                    if(i==img.length-1){
                        $('next').addClass('next-no');
                    }else{
                        $('next').removeClass('next-no');
                    }
                    $('last').addClass('last-act');
                }
                if (i<img.length-2){
                    ml="-"+(img[0].getSize().x+separator[0].getSize().x)*i+'px';
                    line.morph({
                        'margin-left':ml
                    });
                }
                }
        }

        function photo_delete(elem,event)
        {
            set_up(elem,event);
            var img = $$('.photo');
            for (var i=0;i<img.length;i++)
            {
                if (elem.parentNode.parentNode.parentNode==img[i])
                {
                    if (i<img.length-2)
                        img[i+1].click();
                    else
                        img[i-1].click();
                    ehide(img[i]);
                }
            }
        }
        // *****************************************************************************
        // *****************************************************************************
        // КНОПКА ВПЕРЕД ***************************************************************
        $('next').addEvent('mousedown',function(e){
            if(i>=img.length-3){
                e.stop();
            }else{
                i++
                list(i);
                i>=img.length-3?fadeOut($('next')):fadeIn($('next'));
                if(i>=img.length-3) $('next').setStyle('background-position','-19px center');
                fadeIn($('last'));
            }
        });
        $('next').addEvent('mouseover',function(e){
            if(i>=img.length-3){
                e.stop();
            }else{
                $('next').setStyle('background-position','-58px center');
            }
        });
        $('next').addEvent('mouseout',function(e){
            if(i>=img.length-3){
                e.stop();
            }else{
                $('next').setStyle('background-position','-19px center');
            }
        });
        // *****************************************************************************
        // КНОПКА НАЗАД ****************************************************************
        $('last').addEvent('mousedown',function(e){
            if(i==0){
                e.stop();
            }else{
                i--
                list(i);
                i==0?fadeOut($('last')):fadeIn($('last'));
                if (i==0) $('last').setStyle('background-position','0px center');
                fadeIn($('next'));
            }
        });
        $('last').addEvent('mouseover',function(e){
            if(i!==0){
                $('last').setStyle('background-position','-38px center');
            }
        });
        $('last').addEvent('mouseout',function(e){
            if(i!==0){
                $('last').setStyle('background-position','0px center');
            }
        });
        // *****************************************************************************
        // *****************************************************************************
        // *****************************************************************************
        img.each(function(el,i){
            if(el.getParent('a')){
                el.getParent('a').addEvent('click',function(e){
                    e.stop();
                });
            }
            el.addEvent('mousedown', function(){
                // list(i);
                display(img[i]);
                $('view').getElementById('photo_link').href=img[i].getElementsByTagName('a')[0].href;
                thumbStyle(img,i);
                nophoto_init();
                $$('.photo a').each(function(el,i){
                    el.setAttribute('rel', 'lightbox-atomium');
                });
                img[i].getElementsByTagName('a')[0].setAttribute('rel', '');
                Slimbox.scanPage();
            });
            el.addEvent('mouseover', function(event){
                if (!($('img_'+this.id)))
                {
                    var preloader = new Element('img', {
                        id:'img_'+this.id,
                        src:img[i].getElementsByTagName('a')[0].href,
                        style:'display: none;'
                    });
                    preloader.inject(document.body);
                }


            });
        });


        del.each(function(el,i){
            el.addEvent('click', function(event){
                // list(i);
                if (confirm('Удалить эту фотографию?'))
                {
                    set_up(this,event);


                    if ($('prod_id'))
                        setTimeout("descr($('prod_id').value)",500);
                    else
                        setTimeout("window.location.reload();",500);

                }
                else return false;
            });
        });

        sort.each(function(el,i){
            el.addEvent('click', function(event){
                var url = this.getAttribute('data-url');
                var key_field = this.getAttribute('data-key_field');
                var key_value = this.getAttribute('data-key_value');
                var field = this.getAttribute('data-field');
                var table = this.getAttribute('data-table');
                var obj_field = this.getAttribute('data-obj_field');
                var obj_value = this.getAttribute('data-obj_value');
                var dir = this.getAttribute('data-dir');
                var file_field = this.getAttribute('data-file_field');
                var sort_field = this.getAttribute('data-sort_field');
                var up = this.getAttribute('data-up');

                var pars = $H({
                    url:url,
                    key_field:key_field,
                    key_value:key_value,
                    field:field,
                    table:table,
                    obj_field:obj_field,
                    obj_value:obj_value,
                    dir:dir,
                    file_field:file_field,
                    sort_field:sort_field,
                    up:up
                }).toQueryString();
                var myRequest = new Request.HTML({
                    url: 'modules/gallery/ajax/actions.php?action=sort',
                    method: 'get',
                    update: $('photo_block').parentNode.id,
                    evalScripts: true,
                    onComplete: function(){
                        gallery_events();
                    }
                }).send(pars);
            });
        });

        // назад ************************************
        var trashield = new Element('div', {
            'class': 'go_last'
        });
        trashield.addEvent('mousedown',function(){
            if (!img[i-1])
                i = img.length;
            display(img[i-1]);
            $('view').getElementById('photo_link').href=img[i-1].getElementsByTagName('a')[0].href;
            thumbStyle(img,i);
            nophoto_init();
            i--;
            if($('show_'+i))
                $('show_'+i).fireEvent('click');
        //  show($('show_'+i));


        });
        trashield.addEvent('mouseover',function(e){
            this.setStyle('background-position','0px -51px');
        });
        trashield.addEvent('mouseout',function(e){
            this.setStyle('background-position','0px 0px');
        });

        trashield.inject($('curent_photo'),'top');
        //*******************************************
        // вперед ************************************
        var trashield = new Element('div', {
            'class': 'go_next'
        });
        trashield.addEvent('mousedown',function(){
            if (!img[i+1])
                i = -1;
            display(img[i+1]);
            $('view').getElementById('photo_link').href=img[i+1].getElementsByTagName('a')[0].href;

            thumbStyle(img,i);
            nophoto_init();
            i++;
            if($('show_'+i))
                $('show_'+i).fireEvent('click');
        //    show($('show_'+i));

        });
        trashield.addEvent('mouseover',function(e){
            this.setStyle('background-position','-41px -51px');
        });
        trashield.addEvent('mouseout',function(e){
            this.setStyle('background-position','-41px 0px');
        });
        trashield.inject($('curent_photo'),'top');
        //*******************************************
        if($('code')&&img.length>1)
        {
            $('curent_photo').addEvent('mouseenter',function(event){
                $$('.go_last').setStyle('display','block');
                $$('.go_next').setStyle('display','block');
            });
            $('curent_photo').addEvent('mouseleave',function(event){
                $$('.go_last').setStyle('display','none');
                $$('.go_next').setStyle('display','none');
            });
        }
    }
    initialize_photo_selector();
    nophoto_init();
    if (img)
    {

        $$('.photo a').each(function(el,i){
            el.setAttribute('rel', 'lightbox-atomium');
        });
        img[i].getElementsByTagName('a')[0].setAttribute('rel', '');
        $('view').getElementById('photo_link').href=img[i].getElementsByTagName('a')[0].href;
        Slimbox.scanPage();
    }
}

function nophoto_init()
{
    if ($('photo_link'))
        if ($('photo_link').href.indexOf('no_photo')!==-1)
        {
            $('photo_link').removeAttribute('rel');
            $('photo_link').removeEvent('click');
            $('photo_link').removeAttribute('href');
            Slimbox.scanPage();
        }
}


function show_pictures(elem)
{

    var key_field = elem.getAttribute('data-key_field');
    var key_value = elem.getAttribute('data-key_value');
    var field = elem.getAttribute('data-field');
    var table = elem.getAttribute('data-table');
    var obj_field = elem.getAttribute('data-obj_field');
    var obj_value = elem.getAttribute('data-obj_value');
    var dir = elem.getAttribute('data-dir');
    var file_field = elem.getAttribute('data-file_field');
    var sort_field = elem.getAttribute('data-sort_field');

    var pars = $H({

        key_field:key_field,
        key_value:key_value,
        field:field,
        table:table,
        obj_field:obj_field,
        obj_value:obj_value,
        dir:dir,
        file_field:file_field,
        sort_field:sort_field
    }).toQueryString();
    var container =  $('photo_block')?$('photo_block').parentNode.id:"div_catalog_photo";
    var myRequest = new Request.HTML({
        url: 'modules/gallery/ajax/actions.php?action=show_pictures',
        method: 'get',
        update: container,
        evalScripts: true,
        onComplete: function(){
            gallery_events();
            Slimbox.scanPage();
        }
    }).send(pars);
}


function initialize_photo_selector()
{
    if($('div_catalog_photo'))
    {
        if(!$('add_img_link'))
        {
            $('thumb').setStyle('display','none');


        }
        else  if($('ps_navi'))
        {
            $('ps_navi').setStyle('display','none');
            $$('.cb')[1].innerHTML = "<b onmouseover=\"$('line').highlight('#ffffff','#dadada');\">миниатюры фотографий</b> в каталоге отображаются только у администраторов";
        }
    }

    if ($('nav'))
        $('nav').setStyle('display','none');

    var i=0;
    var item = $$('.photo');
    var navi = $('ps_navi');
    var next = 0;
    function navi_create()
    {
        if(navi)
        {
            navi.innerHTML='';
            if(item.length>1)
                for (var j=0; j<item.length;j++)
                {
                    var cl = 'show_button';
                    if (j==i)
                        cl = 'show_button-active';
                    var trashield = new Element('div', {
                        id:'show_'+j,
                        'class': cl,
                        'data-id': j
                    });
                    trashield.addEvent('click', function(e) {
                        show(this);
                    });
                    trashield.addEvent('mouseover', function(e) {
                        item[i].fireEvent('mouseover');
                    });
                    trashield.inject(navi,'bottom');
                }
        }
    }

    function show(elem)
    {
        $('show_'+i).setAttribute('class','show_button');
        var id=parseInt(elem.getAttribute('data-id'));
        i = id;
        item[i].fireEvent('mousedown');
        item[id].setStyle('display','block');
        elem.setAttribute('class','show_button-active');

        next = i==item.length-1?0:i+1;
        nophoto_init();
    }
    navi_create();

} 
/**
 * http://github.com/valums/file-uploader
 *
 * Multiple file upload component with progress-bar, drag-and-drop.
 * В© 2010 Andrew Valums ( andrew(at)valums.com )
 *
 * Licensed under GNU GPL 2 or later, see license.txt.
 */

//
// Helper functions
//

var qq = qq || {};
var run_oncomplete;
/**
 * Adds all missing properties from second obj to first obj
 */
qq.extend = function(first, second){
    for (var prop in second){
        first[prop] = second[prop];
    }
};

/**
 * Searches for a given element in the array, returns -1 if it is not present.
 * @param {Number} [from] The index at which to begin the search
 */
qq.indexOf = function(arr, elt, from){
    if (arr.indexOf) return arr.indexOf(elt, from);

    from = from || 0;
    var len = arr.length;

    if (from < 0) from += len;

    for (; from < len; from++){
        if (from in arr && arr[from] === elt){
            return from;
        }
    }
    return -1;
};

qq.getUniqueId = (function(){
    var id = 0;
    return function(){
        return id++;
    };
})();

//
// Events

qq.attach = function(element, type, fn){
    if (element.addEventListener){
        element.addEventListener(type, fn, false);
    } else if (element.attachEvent){
        element.attachEvent('on' + type, fn);
    }
};
qq.detach = function(element, type, fn){
    if (element.removeEventListener){
        element.removeEventListener(type, fn, false);
    } else if (element.attachEvent){
        element.detachEvent('on' + type, fn);
    }
};

qq.preventDefault = function(e){
    if (e.preventDefault){
        e.preventDefault();
    } else{
        e.returnValue = false;
    }
};

//
// Node manipulations

/**
 * Insert node a before node b.
 */
qq.insertBefore = function(a, b){
    b.parentNode.insertBefore(a, b);
};
qq.remove = function(element){
    element.parentNode.removeChild(element);
};

qq.contains = function(parent, descendant){
    // compareposition returns false in this case
    if (parent == descendant) return true;

    if (parent.contains){
        return parent.contains(descendant);
    } else {
        return !!(descendant.compareDocumentPosition(parent) & 8);
    }
};

/**
 * Creates and returns element from html string
 * Uses innerHTML to create an element
 */
qq.toElement = (function(){
    var div = document.createElement('div');
    return function(html){
        div.innerHTML = html;
        var element = div.firstChild;
        div.removeChild(element);
        return element;
    };
})();

//
// Node properties and attributes

/**
 * Sets styles for an element.
 * Fixes opacity in IE6-8.
 */
qq.css = function(element, styles){
    if (styles.opacity != null){
        if (typeof element.style.opacity != 'string' && typeof(element.filters) != 'undefined'){
            styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')';
        }
    }
    qq.extend(element.style, styles);
};
qq.hasClass = function(element, name){
    var re = new RegExp('(^| )' + name + '( |$)');
    return re.test(element.className);
};
qq.addClass = function(element, name){
    if (!qq.hasClass(element, name)){
        element.className += ' ' + name;
    }
};
qq.removeClass = function(element, name){
    var re = new RegExp('(^| )' + name + '( |$)');
    element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, "");
};
qq.setText = function(element, text){
    element.innerText = text;
    element.textContent = text;
};

//
// Selecting elements

qq.children = function(element){
    var children = [],
    child = element.firstChild;

    while (child)
    {
        if (child.nodeType == 1){
            children.push(child);
        }
        child = child.nextSibling;
    }

    return children;
};

qq.getByClass = function(element, className){
    if (element.querySelectorAll){
        return element.querySelectorAll('.' + className);
    }

    var result = [];
    var candidates = element.getElementsByTagName("*");
    var len = candidates.length;

    for (var i = 0; i < len; i++){
        if (qq.hasClass(candidates[i], className)){
            result.push(candidates[i]);
        }
    }
    return result;
};

/**
 * obj2url() takes a json-object as argument and generates
 * a querystring. pretty much like jQuery.param()
 *
 * how to use:
 *
 *    `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`
 *
 * will result in:
 *
 *    `http://any.url/upload?otherParam=value&a=b&c=d`
 *
 * @param  Object JSON-Object
 * @param  String current querystring-part
 * @return String encoded querystring
 */
qq.obj2url = function(obj, temp, prefixDone){
    var uristrings = [],
    prefix = '&',
    add = function(nextObj, i){
        var nextTemp = temp
        ? (/\[\]$/.test(temp)) // prevent double-encoding
        ? temp
        : temp+'['+i+']'
        : i;
        if ((nextTemp != 'undefined') && (i != 'undefined')) {
            uristrings.push(
                (typeof nextObj === 'object')
                ? qq.obj2url(nextObj, nextTemp, true)
                : (Object.prototype.toString.call(nextObj) === '[object Function]')
                ? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj())
                : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj)
                );
        }
    };

    if (!prefixDone && temp) {
        prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?';
        uristrings.push(temp);
        uristrings.push(qq.obj2url(obj));
    } else if ((Object.prototype.toString.call(obj) === '[object Array]') && (typeof obj != 'undefined') ) {
        // we wont use a for-in-loop on an array (performance)
        for (var i = 0, len = obj.length; i < len; ++i){
            add(obj[i], i);
        }
    } else if ((typeof obj != 'undefined') && (obj !== null) && (typeof obj === "object")){
        // for anything else but a scalar, we will use for-in-loop
        for (var i in obj){
            add(obj[i], i);
        }
    } else {
        uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj));
    }

    return uristrings.join(prefix)
    .replace(/^&/, '')
    .replace(/%20/g, '+');
};

//
//
// Uploader Classes
//
//

var qq = qq || {};

/**
 * Creates upload button, validates upload, but doesn't create file list or dd.
 */
qq.FileUploaderBasic = function(o){
    this._options = {
        // set to true to see the server response
        debug: false,
        action: '/server/upload',
        params: {},
        button: null,
        multiple: true,
        maxConnections: 3,
        // validation
        allowedExtensions: [],
        sizeLimit: 0,
        minSizeLimit: 0,
        // events
        // return false to cancel submit
        onSubmit: function(id, fileName){},
        onProgress: function(id, fileName, loaded, total){},
        onComplete: function(id, fileName, responseJSON, onComplite){},
        onCancel: function(id, fileName){},
        // messages
        messages: {
            typeError: "{file} имеет недопустимое расширение. Только файлы, имеющие расширение {extensions} могут быть загружены.",
            sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
            minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
            emptyError: "{file} is empty, please select files again without it.",
            onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
        },
        showMessage: function(message){
            alert(message);
        }
    };
    qq.extend(this._options, o);

    // number of files being uploaded
    this._filesInProgress = 0;
    this._handler = this._createUploadHandler();

    if (this._options.button){
        this._button = this._createUploadButton(this._options.button);
    }

    this._preventLeaveInProgress();
};

qq.FileUploaderBasic.prototype = {
    setParams: function(params){
        this._options.params = params;
    },
    getInProgress: function(){
        return this._filesInProgress;
    },
    _createUploadButton: function(element){
        var self = this;

        return new qq.UploadButton({
            element: element,
            multiple: this._options.multiple && qq.UploadHandlerXhr.isSupported(),
            onChange: function(input){
                self._onInputChange(input);
            }
        });
    },
    _createUploadHandler: function(){
        var self = this,
        handlerClass;

        if(qq.UploadHandlerXhr.isSupported()){
            handlerClass = 'UploadHandlerXhr';
        } else {
            handlerClass = 'UploadHandlerForm';
        }

        var handler = new qq[handlerClass]({
            debug: this._options.debug,
            action: this._options.action,
            maxConnections: this._options.maxConnections,
            onProgress: function(id, fileName, loaded, total){
                self._onProgress(id, fileName, loaded, total);
                self._options.onProgress(id, fileName, loaded, total);
            },
            onComplete: function(id, fileName, result){
                self._onComplete(id, fileName, result);
                self._options.onComplete(id, fileName, result);
            },
            onCancel: function(id, fileName){
                self._onCancel(id, fileName);
                self._options.onCancel(id, fileName);
            }
        });

        return handler;
    },
    _preventLeaveInProgress: function(){
        var self = this;

        qq.attach(window, 'beforeunload', function(e){
            if (!self._filesInProgress){
                return;
            }

            var e = e || window.event;
            // for ie, ff
            e.returnValue = self._options.messages.onLeave;
            // for webkit
            return self._options.messages.onLeave;
        });
    },
    _onSubmit: function(id, fileName){
        this._filesInProgress++;
    },
    _onProgress: function(id, fileName, loaded, total){
    },
    _onComplete: function(id, fileName, result){
        this._filesInProgress--;
        if (result.error){
            this._options.showMessage(result.error);
        }
    },
    _onCancel: function(id, fileName){
        this._filesInProgress--;
    },
    _onInputChange: function(input){
        if (this._handler instanceof qq.UploadHandlerXhr){
            this._uploadFileList(input.files);
        } else {
            if (this._validateFile(input)){
                this._uploadFile(input);
            }
        }
        this._button.reset();
    },
    _uploadFileList: function(files){
        for (var i=0; i<files.length; i++){
            if ( !this._validateFile(files[i])){
                return;
            }
        }

        for (var i=0; i<files.length; i++){
            this._uploadFile(files[i]);
        }
    },
    _uploadFile: function(fileContainer){
        var id = this._handler.add(fileContainer);
        var fileName = this._handler.getName(id);

        if (this._options.onSubmit(id, fileName) !== false){
            this._onSubmit(id, fileName);
            this._handler.upload(id, this._options.params);
        }
    },
    _validateFile: function(file){
        var name, size;

        if (file.value){
            // it is a file input
            // get input value and remove path to normalize
            name = file.value.replace(/.*(\/|\\)/, "");
        } else {
            // fix missing properties in Safari
            name = file.fileName != null ? file.fileName : file.name;
            size = file.fileSize != null ? file.fileSize : file.size;
        }

        if (! this._isAllowedExtension(name)){
            this._error('typeError', name);
            return false;

        } else if (size === 0){
            this._error('emptyError', name);
            return false;

        } else if (size && this._options.sizeLimit && size > this._options.sizeLimit){
            this._error('sizeError', name);
            return false;

        } else if (size && size < this._options.minSizeLimit){
            this._error('minSizeError', name);
            return false;
        }

        return true;
    },
    _error: function(code, fileName){
        var message = this._options.messages[code];
        function r(name, replacement){
            message = message.replace(name, replacement);
        }

        r('{file}', this._formatFileName(fileName));
        r('{extensions}', this._options.allowedExtensions.join(', '));
        r('{sizeLimit}', this._formatSize(this._options.sizeLimit));
        r('{minSizeLimit}', this._formatSize(this._options.minSizeLimit));

        this._options.showMessage(message);
    },
    _formatFileName: function(name){
        if (name.length > 33){
            name = name.slice(0, 19) + '...' + name.slice(-13);
        }
        return name;
    },
    _isAllowedExtension: function(fileName){
        var ext = (-1 !== fileName.indexOf('.')) ? fileName.replace(/.*[.]/, '').toLowerCase() : '';
        var allowed = this._options.allowedExtensions;

        if (!allowed.length){
            return true;
        }

        for (var i=0; i<allowed.length; i++){
            if (allowed[i].toLowerCase() == ext){
                return true;
            }
        }

        return false;
    },
    _formatSize: function(bytes){
        var i = -1;
        do {
            bytes = bytes / 1024;
            i++;
        } while (bytes > 99);

        return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];
    }
};


/**
 * Class that creates upload widget with drag-and-drop and file list
 * @inherits qq.FileUploaderBasic
 */
qq.FileUploader = function(o){
    // call parent constructor
    qq.FileUploaderBasic.apply(this, arguments);

    // additional options
    qq.extend(this._options, {
        element: null,
        // if set, will be used instead of qq-upload-list in template
        listElement: null,

        template: '<div class="qq-uploader">' +
        '<div class="qq-upload-drop-area"><span>Перенесите файлы в эту область для </span></div>' +
        '<div class="qq-upload-button">Выбрать файлы для загрузки</div>' +
        '<ul class="qq-upload-list"></ul>' +
        '</div>',

        // template for one item in file list
        fileTemplate: '<li>' +
        '<span class="qq-upload-file"></span>' +
        '<span class="qq-upload-spinner"></span>' +
        '<span class="qq-upload-size"></span>' +
        '<a class="qq-upload-cancel" href="#">Отменить</a>' +
        '<span class="qq-upload-failed-text">Произошла ошибка</span>' +
        '</li>',

        classes: {
            // used to get elements from templates
            button: 'qq-upload-button',
            drop: 'qq-upload-drop-area',
            dropActive: 'qq-upload-drop-area-active',
            list: 'qq-upload-list',

            file: 'qq-upload-file',
            spinner: 'qq-upload-spinner',
            size: 'qq-upload-size',
            cancel: 'qq-upload-cancel',

            // added to list item when upload completes
            // used in css to hide progress spinner
            success: 'qq-upload-success',
            fail: 'qq-upload-fail'
        }
    });
    // overwrite options with user supplied
    qq.extend(this._options, o);

    this._element = this._options.element;
    this._element.innerHTML = this._options.template;
    this._listElement = this._options.listElement || this._find(this._element, 'list');

    this._classes = this._options.classes;

    this._button = this._createUploadButton(this._find(this._element, 'button'));

    this._bindCancelEvent();
    this._setupDragDrop();
};

// inherit from Basic Uploader
qq.extend(qq.FileUploader.prototype, qq.FileUploaderBasic.prototype);

qq.extend(qq.FileUploader.prototype, {
    /**
     * Gets one of the elements listed in this._options.classes
     **/
    _find: function(parent, type){
        var element = qq.getByClass(parent, this._options.classes[type])[0];
        if (!element){
            throw new Error('element not found ' + type);
        }

        return element;
    },
    _setupDragDrop: function(){
        var self = this,
        dropArea = this._find(this._element, 'drop');

        var dz = new qq.UploadDropZone({
            element: dropArea,
            onEnter: function(e){
                qq.addClass(dropArea, self._classes.dropActive);
                e.stopPropagation();
            },
            onLeave: function(e){
                e.stopPropagation();
            },
            onLeaveNotDescendants: function(e){
                qq.removeClass(dropArea, self._classes.dropActive);
            },
            onDrop: function(e){
                dropArea.style.display = 'none';
                qq.removeClass(dropArea, self._classes.dropActive);
                self._uploadFileList(e.dataTransfer.files);
            }
        });

        dropArea.style.display = 'none';

        qq.attach(document, 'dragenter', function(e){
            if (!dz._isValidFileDrag(e)) return;

            dropArea.style.display = 'block';
        });
        qq.attach(document, 'dragleave', function(e){
            if (!dz._isValidFileDrag(e)) return;

            var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
            // only fire when leaving document out
            if ( ! relatedTarget || relatedTarget.nodeName == "HTML"){
                dropArea.style.display = 'none';
            }
        });
    },
    _onSubmit: function(id, fileName){
        qq.FileUploaderBasic.prototype._onSubmit.apply(this, arguments);
        this._addToList(id, fileName);
    },
    _onProgress: function(id, fileName, loaded, total){
        qq.FileUploaderBasic.prototype._onProgress.apply(this, arguments);

        var item = this._getItemByFileId(id);
        var size = this._find(item, 'size');
        size.style.display = 'inline';

        var text;
        if (loaded != total){
            text = Math.round(loaded / total * 100) + '% from ' + this._formatSize(total);
        } else {
            text = this._formatSize(total);
        }

        qq.setText(size, text);
    },
    _onComplete: function(id, fileName, result, onComplete){
        qq.FileUploaderBasic.prototype._onComplete.apply(this, arguments);

        // mark completed
        var item = this._getItemByFileId(id);
        qq.remove(this._find(item, 'cancel'));
        qq.remove(this._find(item, 'spinner'));

        if (result.success){
            qq.addClass(item, this._classes.success);
            setTimeout(""+run_oncomplete+"",10);

        // else
        //  if ($('down_photo')) $('down_photo').click();
        /* if ($('group_photo')&&$('group_id'))
                group_photo_img($('group_id').value);*/
        //  if ($('db_files')) dynamic_banner_form();
        //   if ($('banner_page')) banner_page_img();
        } else {
            qq.addClass(item, this._classes.fail);
        }

    //  onComplite();



    },
    _addToList: function(id, fileName){
        var item = qq.toElement(this._options.fileTemplate);
        item.qqFileId = id;

        var fileElement = this._find(item, 'file');
        qq.setText(fileElement, this._formatFileName(fileName));
        this._find(item, 'size').style.display = 'none';

        this._listElement.appendChild(item);
    },
    _getItemByFileId: function(id){
        var item = this._listElement.firstChild;

        // there can't be txt nodes in dynamically created list
        // and we can  use nextSibling
        while (item){
            if (item.qqFileId == id) return item;
            item = item.nextSibling;
        }
    },
    /**
     * delegate click event for cancel link
     **/
    _bindCancelEvent: function(){
        var self = this,
        list = this._listElement;

        qq.attach(list, 'click', function(e){
            e = e || window.event;
            var target = e.target || e.srcElement;

            if (qq.hasClass(target, self._classes.cancel)){
                qq.preventDefault(e);

                var item = target.parentNode;
                self._handler.cancel(item.qqFileId);
                qq.remove(item);
            }
        });
    }
});

qq.UploadDropZone = function(o){
    this._options = {
        element: null,
        onEnter: function(e){},
        onLeave: function(e){},
        // is not fired when leaving element by hovering descendants
        onLeaveNotDescendants: function(e){},
        onDrop: function(e){}
    };
    qq.extend(this._options, o);

    this._element = this._options.element;

    this._disableDropOutside();
    this._attachEvents();
};

qq.UploadDropZone.prototype = {
    _disableDropOutside: function(e){
        // run only once for all instances
        if (!qq.UploadDropZone.dropOutsideDisabled ){

            qq.attach(document, 'dragover', function(e){
                if (e.dataTransfer){
                    e.dataTransfer.dropEffect = 'none';
                    e.preventDefault();
                }
            });

            qq.UploadDropZone.dropOutsideDisabled = true;
        }
    },
    _attachEvents: function(){
        var self = this;

        qq.attach(self._element, 'dragover', function(e){
            if (!self._isValidFileDrag(e)) return;

            var effect = e.dataTransfer.effectAllowed;
            if (effect == 'move' || effect == 'linkMove'){
                e.dataTransfer.dropEffect = 'move'; // for FF (only move allowed)
            } else {
                e.dataTransfer.dropEffect = 'copy'; // for Chrome
            }

            e.stopPropagation();
            e.preventDefault();
        });

        qq.attach(self._element, 'dragenter', function(e){
            if (!self._isValidFileDrag(e)) return;

            self._options.onEnter(e);
        });

        qq.attach(self._element, 'dragleave', function(e){
            if (!self._isValidFileDrag(e)) return;

            self._options.onLeave(e);

            var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
            // do not fire when moving a mouse over a descendant
            if (qq.contains(this, relatedTarget)) return;

            self._options.onLeaveNotDescendants(e);
        });

        qq.attach(self._element, 'drop', function(e){
            if (!self._isValidFileDrag(e)) return;

            e.preventDefault();
            self._options.onDrop(e);
        });
    },
    _isValidFileDrag: function(e){
        var dt = e.dataTransfer,
        // do not check dt.types.contains in webkit, because it crashes safari 4
        isWebkit = navigator.userAgent.indexOf("AppleWebKit") > -1;

        // dt.effectAllowed is none in Safari 5
        // dt.types.contains check is for firefox
        return dt && dt.effectAllowed != 'none' &&
        (dt.files || (!isWebkit && dt.types.contains && dt.types.contains('Files')));

    }
};

qq.UploadButton = function(o){
    this._options = {
        element: null,
        // if set to true adds multiple attribute to file input
        multiple: false,
        // name attribute of file input
        name: 'file',
        onChange: function(input){},
        hoverClass: 'qq-upload-button-hover',
        focusClass: 'qq-upload-button-focus'
    };

    qq.extend(this._options, o);

    this._element = this._options.element;

    // make button suitable container for input
    qq.css(this._element, {
        position: 'relative',
        overflow: 'hidden',
        width:'210px',
        // Make sure browse button is in the right side
        // in Internet Explorer
        direction: 'ltr'
    });

    this._input = this._createInput();
};

qq.UploadButton.prototype = {
    /* returns file input element */
    getInput: function(){
        return this._input;
    },
    /* cleans/recreates the file input */
    reset: function(){
        if (this._input.parentNode){
            qq.remove(this._input);
        }

        qq.removeClass(this._element, this._options.focusClass);
        this._input = this._createInput();
    },
    _createInput: function(){
        var input = document.createElement("input");

        if (this._options.multiple){
            input.setAttribute("multiple", "multiple");
        }

        input.setAttribute("type", "file");
        input.setAttribute("name", this._options.name);

        qq.css(input, {
            position: 'absolute',
            // in Opera only 'browse' button
            // is clickable and it is located at
            // the right side of the input
            right: 0,
            top: 0,
            fontFamily: 'Arial',
            // 4 persons reported this, the max values that worked for them were 243, 236, 236, 118
            fontSize: '118px',
            margin: 0,
            padding: 0,
            cursor: 'pointer',
            opacity: 0
        });

        this._element.appendChild(input);

        var self = this;
        qq.attach(input, 'change', function(){
            self._options.onChange(input);
        });

        qq.attach(input, 'mouseover', function(){
            qq.addClass(self._element, self._options.hoverClass);
        });
        qq.attach(input, 'mouseout', function(){
            qq.removeClass(self._element, self._options.hoverClass);
        });
        qq.attach(input, 'focus', function(){
            qq.addClass(self._element, self._options.focusClass);
        });
        qq.attach(input, 'blur', function(){
            qq.removeClass(self._element, self._options.focusClass);
        });

        // IE and Opera, unfortunately have 2 tab stops on file input
        // which is unacceptable in our case, disable keyboard access
        if (window.attachEvent){
            // it is IE or Opera
            input.setAttribute('tabIndex', "-1");
        }

        return input;
    }
};

/**
 * Class for uploading files, uploading itself is handled by child classes
 */
qq.UploadHandlerAbstract = function(o){
    this._options = {
        debug: false,
        action: '/upload.php',
        // maximum number of concurrent uploads
        maxConnections: 999,
        onProgress: function(id, fileName, loaded, total){},
        onComplete: function(id, fileName, response){},
        onCancel: function(id, fileName){}
    };
    qq.extend(this._options, o);

    this._queue = [];
    // params for files in queue
    this._params = [];
};
qq.UploadHandlerAbstract.prototype = {
    log: function(str){
        if (this._options.debug && window.console) console.log('[uploader] ' + str);
    },
    /**
     * Adds file or file input to the queue
     * @returns id
     **/
    add: function(file){},
    /**
     * Sends the file identified by id and additional query params to the server
     */
    upload: function(id, params){
        var len = this._queue.push(id);

        var copy = {};
        qq.extend(copy, params);
        this._params[id] = copy;

        // if too many active uploads, wait...
        if (len <= this._options.maxConnections){
            this._upload(id, this._params[id]);
        }
    },
    /**
     * Cancels file upload by id
     */
    cancel: function(id){
        this._cancel(id);
        this._dequeue(id);
    },
    /**
     * Cancells all uploads
     */
    cancelAll: function(){
        for (var i=0; i<this._queue.length; i++){
            this._cancel(this._queue[i]);
        }
        this._queue = [];
    },
    /**
     * Returns name of the file identified by id
     */
    getName: function(id){},
    /**
     * Returns size of the file identified by id
     */
    getSize: function(id){},
    /**
     * Returns id of files being uploaded or
     * waiting for their turn
     */
    getQueue: function(){
        return this._queue;
    },
    /**
     * Actual upload method
     */
    _upload: function(id){},
    /**
     * Actual cancel method
     */
    _cancel: function(id){},
    /**
     * Removes element from queue, starts upload of next
     */
    _dequeue: function(id){
        var i = qq.indexOf(this._queue, id);
        this._queue.splice(i, 1);

        var max = this._options.maxConnections;

        if (this._queue.length >= max && i < max){
            var nextId = this._queue[max-1];
            this._upload(nextId, this._params[nextId]);
        }
    }
};

/**
 * Class for uploading files using form and iframe
 * @inherits qq.UploadHandlerAbstract
 */
qq.UploadHandlerForm = function(o){
    qq.UploadHandlerAbstract.apply(this, arguments);

    this._inputs = {};
};
// @inherits qq.UploadHandlerAbstract
qq.extend(qq.UploadHandlerForm.prototype, qq.UploadHandlerAbstract.prototype);

qq.extend(qq.UploadHandlerForm.prototype, {
    add: function(fileInput){
        fileInput.setAttribute('name', 'qqfile');
        var id = 'qq-upload-handler-iframe' + qq.getUniqueId();

        this._inputs[id] = fileInput;

        // remove file input from DOM
        if (fileInput.parentNode){
            qq.remove(fileInput);
        }

        return id;
    },
    getName: function(id){
        // get input value and remove path to normalize
        return this._inputs[id].value.replace(/.*(\/|\\)/, "");
    },
    _cancel: function(id){
        this._options.onCancel(id, this.getName(id));

        delete this._inputs[id];

        var iframe = document.getElementById(id);
        if (iframe){
            // to cancel request set src to something else
            // we use src="javascript:false;" because it doesn't
            // trigger ie6 prompt on https
            iframe.setAttribute('src', 'javascript:false;');

            qq.remove(iframe);
        }
    },
    _upload: function(id, params){
        var input = this._inputs[id];

        if (!input){
            throw new Error('file with passed id was not added, or already uploaded or cancelled');
        }

        var fileName = this.getName(id);

        var iframe = this._createIframe(id);
        var form = this._createForm(iframe, params);
        form.appendChild(input);

        var self = this;
        this._attachLoadEvent(iframe, function(){
            self.log('iframe loaded');

            var response = self._getIframeContentJSON(iframe);

            self._options.onComplete(id, fileName, response);
            self._dequeue(id);

            delete self._inputs[id];
            // timeout added to fix busy state in FF3.6
            setTimeout(function(){
                qq.remove(iframe);
            }, 1);
        });

        form.submit();
        qq.remove(form);

        return id;
    },
    _attachLoadEvent: function(iframe, callback){
        qq.attach(iframe, 'load', function(){
            // when we remove iframe from dom
            // the request stops, but in IE load
            // event fires
            if (!iframe.parentNode){
                return;
            }

            // fixing Opera 10.53
            if (iframe.contentDocument &&
                iframe.contentDocument.body &&
                iframe.contentDocument.body.innerHTML == "false"){
                // In Opera event is fired second time
                // when body.innerHTML changed from false
                // to server response approx. after 1 sec
                // when we upload file with iframe
                return;
            }

            callback();
        });
    },
    /**
     * Returns json object received by iframe from server.
     */
    _getIframeContentJSON: function(iframe){
        // iframe.contentWindow.document - for IE<7
        var doc = iframe.contentDocument ? iframe.contentDocument: iframe.contentWindow.document,
        response;

        this.log("converting iframe's innerHTML to JSON");
        this.log("innerHTML = " + doc.body.innerHTML);

        try {
            response = eval("(" + doc.body.innerHTML + ")");
        } catch(err){
            response = {};
        }

        return response;
    },
    /**
     * Creates iframe with unique name
     */
    _createIframe: function(id){
        // We can't use following code as the name attribute
        // won't be properly registered in IE6, and new window
        // on form submit will open
        // var iframe = document.createElement('iframe');
        // iframe.setAttribute('name', id);

        var iframe = qq.toElement('<iframe src="javascript:false;" name="' + id + '" />');
        // src="javascript:false;" removes ie6 prompt on https

        iframe.setAttribute('id', id);

        iframe.style.display = 'none';
        document.body.appendChild(iframe);

        return iframe;
    },
    /**
     * Creates form, that will be submitted to iframe
     */
    _createForm: function(iframe, params){
        // We can't use the following code in IE6
        // var form = document.createElement('form');
        // form.setAttribute('method', 'post');
        // form.setAttribute('enctype', 'multipart/form-data');
        // Because in this case file won't be attached to request
        var form = qq.toElement('<form method="post" enctype="multipart/form-data"></form>');

        var queryString = qq.obj2url(params, this._options.action);

        form.setAttribute('action', queryString);
        form.setAttribute('target', iframe.name);
        form.style.display = 'none';
        document.body.appendChild(form);

        return form;
    }
});

/**
 * Class for uploading files using xhr
 * @inherits qq.UploadHandlerAbstract
 */
qq.UploadHandlerXhr = function(o){
    qq.UploadHandlerAbstract.apply(this, arguments);

    this._files = [];
    this._xhrs = [];

    // current loaded size in bytes for each file
    this._loaded = [];
};

// static method
qq.UploadHandlerXhr.isSupported = function(){
    var input = document.createElement('input');
    input.type = 'file';

    return (
        'multiple' in input &&
        typeof File != "undefined" &&
        typeof (new XMLHttpRequest()).upload != "undefined" );
};

// @inherits qq.UploadHandlerAbstract
qq.extend(qq.UploadHandlerXhr.prototype, qq.UploadHandlerAbstract.prototype)

qq.extend(qq.UploadHandlerXhr.prototype, {
    /**
     * Adds file to the queue
     * Returns id to use with upload, cancel
     **/
    add: function(file){
        if (!(file instanceof File)){
            throw new Error('Passed obj in not a File (in qq.UploadHandlerXhr)');
        }

        return this._files.push(file) - 1;
    },
    getName: function(id){
        var file = this._files[id];
        // fix missing name in Safari 4
        return file.fileName != null ? file.fileName : file.name;
    },
    getSize: function(id){
        var file = this._files[id];
        return file.fileSize != null ? file.fileSize : file.size;
    },
    /**
     * Returns uploaded bytes for file identified by id
     */
    getLoaded: function(id){
        return this._loaded[id] || 0;
    },
    /**
     * Sends the file identified by id and additional query params to the server
     * @param {Object} params name-value string pairs
     */
    _upload: function(id, params){
        var file = this._files[id],
        name = this.getName(id),
        size = this.getSize(id);

        this._loaded[id] = 0;

        var xhr = this._xhrs[id] = new XMLHttpRequest();
        var self = this;

        xhr.upload.onprogress = function(e){
            if (e.lengthComputable){
                self._loaded[id] = e.loaded;
                self._options.onProgress(id, name, e.loaded, e.total);
            }
        };

        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4){
                self._onComplete(id, xhr);
            }
        };

        // build query string
        params = params || {};
        params['qqfile'] = name;
        var queryString = qq.obj2url(params, this._options.action);

        xhr.open("POST", queryString, true);
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
        xhr.setRequestHeader("Content-Type", "application/octet-stream");
        xhr.send(file);
    },
    _onComplete: function(id, xhr){
        // the request was aborted/cancelled
        if (!this._files[id]) return;

        var name = this.getName(id);
        var size = this.getSize(id);

        this._options.onProgress(id, name, size, size);

        if (xhr.status == 200){
            this.log("xhr - server response received");
            this.log("responseText = " + xhr.responseText);

            var response;

            try {
                response = eval("(" + xhr.responseText + ")");
            } catch(err){
                response = {};
            }

            this._options.onComplete(id, name, response);

        } else {
            this._options.onComplete(id, name, {});
        }

        this._files[id] = null;
        this._xhrs[id] = null;
        this._dequeue(id);
    },
    _cancel: function(id){
        this._options.onCancel(id, this.getName(id));

        this._files[id] = null;

        if (this._xhrs[id]){
            this._xhrs[id].abort();
            this._xhrs[id] = null;
        }
    }
});

function createUploader(){
    var uploader = new qq.FileUploader({
        element: document.getElementById('demo'),
        listElement: document.getElementById('separate-list'),
        action: 'modules/fileuploader/ajax/actions.php',
        onComplite: function(){
            alert('qq');
        }
    });
}

function upload_form(elem)
{
    var table = elem.getAttribute('data-table');
    var obj_field = elem.getAttribute('data-obj_field');
    var obj_value = elem.getAttribute('data-obj_value');
    var dir = elem.getAttribute('data-dir');
    var file_field = elem.getAttribute('data-file_field');
    var key_field = elem.getAttribute('data-key_field');
    var key_value = elem.getAttribute('data-key_value');
    var comment = elem.getAttribute('data-comment');
    run_oncomplete = elem.getAttribute('data-run_oncomplete');
    fu_form("Загрузка файлов",'upload_files','upload_block', comment, 500);
    $('upload_files').innerHTML = "<div id='ub' style='padding:10px;height:100px;'></div>";
    var pars = $H({
        table:table,
        obj_field:obj_field,
        obj_value:obj_value,
        dir:dir,
        file_field:file_field,
        key_field:key_field,
        key_value:key_value,
        comment:comment
    }).toQueryString();
    var myRequest = new Request.HTML({
        url: 'modules/fileuploader/ajax/actions.php?action=upload_form',
        method: 'get',
        update: 'ub',
        evalScripts: true,
        onComplete: function(){
            //        gallery_events();
            createUploader();
        //      show_main_groups();

        }
    }).send(pars);
}

function fu_file_delete(category, onComplete)
{
    var jsonRequest = new Request.JSON({
        url: 'modules/fileuploader/ajax/actions.php?action=fu_file_delete',
        onComplete: function(){
            setTimeout(""+onComplete+"",10);
        }
    }).get({
        category:category
    });
}

function fu_file(category)
{
    if ($('logo'))
        var jsonRequest = new Request.JSON({
            url: 'modules/siteconfig/ajax/siteconfig.php?action=logo_update',
            onComplete: function(logo){
                $('logo').setStyle("background","url('content/logo/"+logo.bg_image+"') no-repeat");
            }
        }).get();
}

function fu_sort(category, up, onComplete)
{

    var jsonRequest = new Request.JSON({
        url: 'modules/fileuploader/ajax/actions.php?action=fu_sort',
        onComplete: function(){
            setTimeout(""+onComplete+"",100);
        }
    }).get({
        category:category,
        up:up
    });
}

function fu_form(title,div_id,panel_id, comment_text, w){
    var ua = navigator.userAgent.toLowerCase();
    var isOpera = (ua.indexOf('opera')  > -1);
    var isIE = (!isOpera && ua.indexOf('msie') > -1);


    function getBodyScrollTop()
    {
        return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
    }

    function getBodyScrollLeft()
    {
        return self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft);
    }


    function getDocumentHeight() {
        return Math.max(document.compatMode != 'CSS1Compat' ? document.body.scrollHeight : document.documentElement.scrollHeight, getViewportHeight());
    }

    function getViewportHeight() {
        return ((document.compatMode || isIE) && !isOpera) ? (document.compatMode == 'CSS1Compat') ? document.documentElement.clientHeight : document.body.clientHeight : (document.parentWindow || document.defaultView).innerHeight;
    }

    function fadeIn(elem)
    {
        if (elem)   {
            if (Browser.name == 'ie'&&elem!==null&&elem!==undefined)   $(elem.id).setStyle('display', 'block');
            else

            {
                elem.setStyles({
                    opacity:0,
                    display:'block'
                });
                elem.tween('opacity', '1');
            }
        }
    }

    function fadeOut(elem)
    {
        if (elem)  {
            if (Browser.name == 'ie'&&elem!==null&&elem!==undefined)  $(elem.id).setStyle('display','block');   else   elem.tween('opacity', '0');
        }
    }

    function sizeabley(el, height)
    {
        el.set('morph', {
            duration: '100'

        //,transition: 'bounce:in'
        });
        el.morph({
            height: height
        });
        el.get('morph');
    }

    function sizeablexy(el, width, height)
    {
        el.set('morph', {
            duration: "100"
            ,
            transition: Fx.Transitions.Circ.easeInOut
        });
        el.morph({
            height: height,
            width:width
        });
        el.get('morph');
    }

    if (div_id==undefined)    div_id = 'block_other';
    if (panel_id==undefined)  panel_id = 'block_other_panel';
    if (w==undefined)  w = 30;
    if ($(panel_id)) $(panel_id).destroy();
    if ($(div_id))      $(div_id).setAttribute("id", div_id+"_");

    var shade = new Element('div', {
        id:panel_id,
        'class': "window"
    });
    shade.setStyles({
        display:'block',
        height:getDocumentHeight()+"px",
        width:'100%',
        position:'absolute',
        left:"0px",
        top:"0px",
        'z-index':'1000'
    });
    shade.inject(document.body);



    var shade = new Element('div',{
        id:panel_id+"_shade"
    });
    shade.setStyles({
        display:'block',
        height:getDocumentHeight() +"px",
        width:'100%',
        background:'#000',
        position:'absolute',
        margin:"0 auto",
        left:"0px",
        top:"0px",
        'z-index':'1',
        opacity: 0.6
    });
    shade.inject($(panel_id));

    //sizeablexy(shade, document.body.getSize().x, getDocumentHeight());

    var trashield = new Element('div', {
        id:panel_id+"_form",
        'class':panel_id+"_form"
    });
    trashield.setStyles({
        position:'absolute',
        zIndex:'50',
        //    'min-height':'150px',
        visibility:'visible',
        width:w<100?w+'%':w+"px",
        border: "2px solid #EEEEEE",
        "border-radius": "4px",
        top:getBodyScrollTop()+100+($$('.handle').length*40)+"px",
        left: document.body.getSize().x/2-((w<100)?w*document.body.getSize().x/100/2:w/2)+"px"
    });

    trashield.inject($(panel_id));


    var x = (w<100)?window.getSize().x*w/100:w;

    $(panel_id+"_form").innerHTML = "<div id='"+panel_id+"_wrap' style='opacity:1;margin:0 auto;width:"+w+"px;overflow:hidden;'>"+
    "<table id='"+panel_id+"_table' style='background:#eee;height:100%;width:100%;'><tr><td id='"+panel_id+"_top' style=\"height:30px; background: #eee;filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#eeeeee', endColorstr='#aaa');background: -webkit-gradient(linear, left top, left bottom, from(#eee), to(#aaa));background: -moz-linear-gradient(top,  #eee,  #aaa);\"></td></tr>"+
    "<tr><td style='vertical-align:top'><div style='overflow:auto;' id='"+panel_id+"_container' class='window_container'></div></td></tr></table></div>";


    var handle = new Element('div', {
        id:panel_id+"handle",
        'class':"handle",
        style:'overflow:hidden; '
    });
    handle.inject($(panel_id+"_top"));

    var artform_title = new Element('span', {
        id:'artform_title',
        'class':"artform_title",
        style:'float: left; padding: 4px 0 0 5px;'
    });
    artform_title.innerHTML = "<h3 style='color:#333;padding:0px; text-shadow:1px 1px 1px #fff; '>"+title+"</h3>";
    artform_title.inject($(panel_id+"handle"));
    var comment = new Element('div', {
        id:'form_comment'
    });
    comment.setStyles({
        display:'block',
        background: '#ccc',
        color: '#333',
        'margin':'10px 0 0   0',
        padding:'0 0 0 5px',
        'text-shadow':'1px 1px 1px #fff'
    });
    comment.innerHTML=comment_text;
    comment.inject($(panel_id+"_top"));
    var artform_close = new Element('img', {
        id:'artform_close',
        src:'images/icons/close.png',
        style:'float: right;padding:5px 5px 0 0; position:relative; z-index:10;'

    });
    artform_close.addEvent('mouseup', function(e) {

        /*    fadeOut($(panel_id));
        setTimeout(function(){*/
        $(panel_id).destroy();
        /*    },1000);*/

        if ($(div_id+"_")) {
            $(div_id+"_").setAttribute("id", div_id);
        }
    });
    artform_close.inject($(panel_id+"handle"));



    var catalog_out = new Element('div', {
        id:div_id
    });
    catalog_out.setStyles({
        display:'block',
        visibility:'visible',
        overflow:'auto',
        margin:'0px 0px -10px 0px',
        position:'relative'
    });
    catalog_out.inject($(panel_id+"_container"));


    if(panel_id!=='word_processor_window')
    {
        $(panel_id+'_form').setStyle('opacity', 0);
        setTimeout(function(){
            $(panel_id+'_form').fade(1);
        }, 100);
    }


    var ij = setInterval(function(){
        if ($(div_id))
        {
            var y= $(div_id).getSize().y;
            $(panel_id+'_form').setStyle('height',y+$(panel_id+'_top').getSize().y+"px");
            $(panel_id+'_container').setStyle('height',y+18+"px");
            $(panel_id+'_wrap').setStyle('height',$(panel_id+'_table').getSize().y-18+"px");

            var top=getBodyScrollTop()+100+($$('.handle').length*40);
            if (getViewportHeight()>(y+$(panel_id+'_top').getSize().y)&&$$('.window')[$$('.window').length-1].id==panel_id){
                top=getViewportHeight()/2-(y+$(panel_id+'_top').getSize().y)/2;
                top = getBodyScrollTop()+top;
                $(panel_id+'_form').setStyle('top', top+"px")
            }
        }
        else clearInterval(ij);
    },30);
   

    document.addEvent('scroll', function(){
        clearInterval(ij);
    })
}


function myalert(message)
{
    fu_form('Уведомление','alert_form','alert_window','', 350);
    $('alert_form').innerHTML="<div style='padding:15px;text-align:center;'>"+message+"</div>";
} 
window.addEvent('domready',function(){
    if($('feedback_send'))
        $('feedback_send').addEvent('click', function() {
            feedback_send();
        });
});

function feedback_send()
{
    var pars = $H({
        name:$('name').value,
        email:$('email').value,
        message:$('message').value
    }).toQueryString();
    var myRequest = new Request.HTML({
        url: 'modules/feedback/ajax/actions.php?action=feedback_send',
        method: 'get',
        update: 'send_form',
        evalScripts: true,
        onComplete: function(){ }
    }).send(pars);
}
 
window.addEvent('domready',function(){
    $$('.dbanner').each(function(el){
        initialize_banner(el.id);
    })

});
var db_period= new Array();
var fff=function(){};
function initialize_banner(db_id)
{
    var i = new Array();
    var next= new Array();
    var last= new Array();
    i[db_id]=0;
    var item = $$('#'+db_id+' .db_item');
    var navi = $(db_id+'_navi');
    //   if (!navi) alert ('не найден элемент #'+db_id+'_navi');
    var container = $(db_id+'_container');
    next[db_id] = 0;
    last[db_id] = 0;
    var a = $(db_id).getAttribute("data-navi_arrows");
    var d = $(db_id).getAttribute("data-navi_dots");
    db_period[db_id] = true;
    function navi_create()
    {

        navi.innerHTML='';
        if(item.length>1)
        {
            for (var j=0; j<item.length;j++)
            {
                var cl = 'show_button';
                if (j==i[db_id])
                    cl = 'show_button-active';
                var trashield = new Element('div', {
                    id:db_id+'_show_'+j,
                    'class': cl,
                    'data-id': j
                });
                trashield.addEvent('click', function(e) {
                    show(this);
                });
                if (navi)
                    trashield.inject(navi,'top');
            }


            // назад ************************************
            trashield = new Element('div', {
                id:'last_'+db_id,
                'class': 'db_last',
                'data-id': last[db_id],
                'style':'height:'+item[0].getSize().y+'px'
            });
            trashield.addEvent('mousedown',function(){
                show($(db_id+'_show_'+next[db_id]));
            });
            if (container)
                trashield.inject(container,'top');
            //*******************************************
            // вперед ************************************
            trashield = new Element('div', {
                id:'next_'+db_id,
                'class': 'db_next',
                'data-id': next[db_id],
                'style':'height:'+(item[0].getSize().y)+'px; margin-left:'+(item[0].getSize().x-19)+'px;'
            });

            trashield.addEvent('mousedown',function(){
                show($(db_id+'_show_'+last[db_id]));
            });
            if (container)
                trashield.inject(container,'top');
            //*******************************************

            if (a=='true')
            {
                container.addEvent('mouseover',function(event){
                    $('last_'+db_id).setStyle('display','block');
                    $('next_'+db_id).setStyle('display','block');
                });
                container.addEvent('mouseout',function(event){
                    $('last_'+db_id).setStyle('display','none');
                    $('next_'+db_id).setStyle('display','none');
                });
            }
            if (d=='false')
            {
                navi.setStyle('display','none');
            }
        }

    }

    function show(elem)
    {
        if ($(db_id+'_show_'+i[db_id]))
            $(db_id+'_show_'+i[db_id]).setAttribute('class','show_button');
        if ($$('#'+db_id+' .db_item'))
        {  
            //      $$('#'+db_id+' .db_item').setStyle('display','none');
       /*     $$('#'+db_id+' .db_item').dissolve({
                mode: 'horizontal'
            });*/
             $$('#'+db_id+' .db_item').fade('out');
        }
        var id=parseInt(elem.getAttribute('data-id'));
        //   item[id].setStyle('display','block');
      //  item[id].setStyle('margin-right', (-item[id].getSize().x)+'px')
        item[id].reveal({
            mode: 'horizontal'
        });
         item[id].fade('in');
        
        elem.setAttribute('class','show_button-active');
        //   fadeIn(elem);
        i[db_id] = id;
        next[db_id] = i[db_id]==item.length-1?0:i[db_id]+1;
        last[db_id] = i[db_id]==item.length+1?0:i[db_id]-1;
        if (last[db_id]==-1)
            last[db_id] = item.length-1;
        var period = (parseInt(item[id].getAttribute("data-period"))*1000);

        clearTimeout(db_period[db_id]);
        db_period[db_id] = setTimeout(function(){
            $('next_'+db_id).fireEvent('mousedown');
        }, period);
    }

    navi_create();
    if ($('next_'+db_id))
        $('next_'+db_id).fireEvent('mousedown');

} 

