(function($) {
    //scroll_content = function(){
      //content_height = $('#content').height();
      //wrapper_height = $('#content-wrapper').height();
      show_cont_nav_buttons = function() {
          o = $('#content-text');
          cnt_height = $('#content-wrapper').height(); 
          t = parseFloat(o.css('top'));
          if(t == 0) {
              $('#vertical-content-scrool .cnt-top:visible').fadeOut();
              
          } else {
              $('#vertical-content-scrool .cnt-top:hidden').fadeIn();
              
              $('#content-text').removeClass('no-scrool');
              $('#content-text').addClass('scrool');
              $('#vertical-content-scrool').fadeIn();
          }
          h = o.height() - cnt_height - 4;
          //alert(o.height() + '==' + cnt_height);
          //alert(t + '==' + h);
          //alert(t < -h);
          if(t < -h) {
              $('#vertical-content-scrool .cnt-bottom:visible').fadeOut();
              
          } else {
              $('#vertical-content-scrool').fadeIn();
              $('#vertical-content-scrool .cnt-bottom:hidden').fadeIn();
              
              $('#content-text').removeClass('no-scrool');
              $('#content-text').addClass('scrool');
              $('#content-text').width('515px');
          }
          //alert($('#content-text').attr('class'));
      }
      
      show_cont_nav_buttons2 = function() {
          o2 = $('#content-text2');
          cnt_height = $('#content-wrapper').height();
          t = parseFloat(o2.css('top'));
          
          if(t == 0) {
              
              $('#vertical-content-scrool .cnt-top2:visible').fadeOut();
          } else {
              
              $('#vertical-content-scrool .cnt-top2:hidden').fadeIn();
              $('#content-text2').removeClass('no-scrool');
              $('#content-text2').addClass('scrool');
              $('#vertical-content-scrool').fadeIn();
          }
          h = o2.height() - cnt_height - 4;
          //alert(o.height() + '==' + cnt_height);
          //alert(t + '==' + h);
          //alert(t < -h);
          if(t < -h) {
              
              $('#vertical-content-scrool .cnt-bottom2:visible').fadeOut();
          } else {
              $('#vertical-content-scrool').fadeIn();
              
              $('#vertical-content-scrool .cnt-bottom2:hidden').fadeIn();
              $('#content-text2').removeClass('no-scrool');
              $('#content-text2').addClass('scrool');
              $('#content-text2').width('515px');
          }
          //alert($('#content-text').attr('class'));
      }
        
      shift = 750;
      $('.cnt-top').live('click', function() {
         cnt_height = $('#content-wrapper').height();
         
         t = parseFloat($('#content-text').css('top'));
         
         t = (t + shift) > 0 ? 0 : t + shift;
         $('#content-text').stop().animate({
             top: t
         }, show_cont_nav_buttons);
      });
      $('.cnt-bottom').live('click',function() {
         cnt_height = $('#content-wrapper').height();
         t = parseInt($('#content-text').css('top').replace('px', ''));
         
         h = $('#content-text').height() - cnt_height + 50;
         //alert(cnt_height + '--' + t + '--' + h);
         //if(h > 0) {
         //alert(t - shift + '==' + h)
             t = (t - shift) - 45 < -h ? -h : t - shift - 45;
             //alert(t)
             $('#content-text').stop().animate({
                 top: t
             }, show_cont_nav_buttons);
         //}
      })                                  
    //}
    
    $('.cnt-top2').live('click', function() {
         cnt_height = $('#content-wrapper').height();
         
         t = parseFloat($('#content-text2').css('top'));
         
         t = (t + shift) > 0 ? 0 : t + shift;
         $('#content-text2').stop().animate({
             top: t
         }, show_cont_nav_buttons2);
      });
      $('.cnt-bottom2').live('click',function() {
         cnt_height = $('#content-wrapper').height();
         t = parseInt($('#content-text2').css('top').replace('px', ''));
         
         h = $('#content-text2').height() - cnt_height + 70;
         //alert(cnt_height + '--' + t + '--' + h);
         //if(h > 0) {
         //alert(t - shift + '==' + h)
             t = (t - shift) - 45 < -h ? -h : t - shift - 45;
             //alert(t)
             $('#content-text2').stop().animate({
                 top: t
             }, show_cont_nav_buttons2);
         //}
      })
    
  
    $(document).ready(function() {
        show_cont_nav_buttons();
        show_cont_nav_buttons2();
        $('#vertical-content-scrool .cnt-top').fadeOut();
        $('#vertical-content-scrool .cnt-top2').fadeOut();
        $('#search-form').submit( function() {
            action = $(this).attr('action') + '?text=' + $('#search-form input:text').val();
            $.get( action, 'noMainIndex', function(html) {
                if(html) {
                    $('#content').html(html);
                    handle_content_events();
                }
                return false;
            });
            return false;
        });
   //     sIFR.replaceElement(named({sSelector:"#products-menu li a", sFlashSrc:"/images/design/top-menu-font.swf", sColor:"#636363", sLinkColor:"#000000", sBgColor:"#FFFFFF", sHoverColor:"#CCCCCC", sFlashVars:"textalign=center"}));

        render_plates = function(c) {
            html = '';
            c = c > 30 ? 30 : c;
            mp = (c > 13) ? 10 / ((c - 1) / 13) : 10;
            for(i = 0; i < c; i++) {
                html += '<img src="/images/design/plate.gif" style="margin-left: ' + i * mp + 'px" />';
            }
            return html;
        }

        var debouncers = [];
        add_to_order2 = function(weight, url, inc) {
            $(weight).each(function() {
                e = $(this);
                e.find('.weight .cnt').each(function() {
                    cnt = parseInt($(this).text());
                    price = parseFloat(e.find('.price').text());
                    price_one = price / cnt;
                    inc ? cnt++ : cnt--;
                    if(cnt <= 0) {
                        pr = e.parents('.producers');
                        e.parents('.produce').remove();
                        if(pr.find('.produce').length <= 0) {
                            pr.parent().removeClass('expanded');
                            pr.slideUp();
                        }

                    } else {
                        $(this).text(cnt);
                        e.find('.plates').html(render_plates(cnt));
                        e.find('.price').html(Math.round(cnt * price_one * 100) / 100 + ' ï¿½.');

                    }
                    if (typeof(debouncers[url]) == "undefined") {
                        debouncers[url] = $.debounce(notify_server, 500);
                    }
                    debouncers[url](url, cnt);
                })
            });
            show_order_button();
            show_nav_buttons();
        }

        show_order_button = function() {
            s = 0;
            $('#order .produce').each(function() {
                ps = 0;
                $(this).find('.price').each(function() {
                    ps += parseFloat($(this).html());
                })
                s += ps;
            });
            if(s) {
               s = s.toFixed(2);
               resultSumm = s.toString();
               /*if( parseInt(s) === s ) {
                 resultSumm = resultSumm + ',- ï¿½.';
               } else {
                 s = s.toFixed(2);
                 resultSumm = s.toString();
                 resultSumm = resultSumm.replace('.', ',')  + ' ï¿½.';
               }*/
               resultSumm = resultSumm.replace('.', ',')  + ' ð.';
               $('#do-order-bt span').html( resultSumm );
               $('#do-order-bt a:hidden').fadeIn();
               $('#do-order-bt font').fadeIn();
            } else {
                $('#do-order-bt a:visible').fadeOut();
                $('#do-order-bt font').fadeOut();
            }
        }

        notify_server = function (url, cnt) {
            $.get(url, 'ajax=1&count=' + cnt);
        }

        add_to_order = function (url) {
            $.getJSON(url, 'ajax=1', function(data) {
               if(!data.eof) {
                 $('#order .group_' + data.group).addClass('expanded').find('.producers').slideDown();
                 if(data.count > 0) {
                     p = $('#order .group_' + data.group + ' .producer_' + data.producer + ' .produces');
                     e = p.find('.produce_' + data.produce + ' .weight_' + data.weight);
                     if(e.length) {
                         e.find('.weight .cnt').html(data.count);
                         e.find('.price').html(data.price);
                         e.find('.plates').html(render_plates(data.count));
                     } else {
                         html =
                             '<li class="produce produce_' + data.produce + '"><div>' + data.produce_name + ' ' + (data.weight != 1 ? data.weight + ' ã.' : '') + '</div>' +
                                '<div class="weight_' + data.weight + ' weight-wrapper">' +
                                    '<span class="weight"><span class="cnt">' + data.count + '</span> øò.</span>' +
                                    '<span class="price">' + data.price + '</span>' +
                                    '<div class="buttons">' +
                                        '<a class="remove-produce" href="' + data.remove_url + '"></a>' +
                                        '<div class="plates">' +
                                            render_plates(data.count) +
                                        '</div>' +
                                        '<a class="add-produce" href="' + data.add_url + '"></a>' +
                                    '</div>' +
                                 '</div>' +
                            '</li>';
                        p.append(html);
                     }
                 } else {
                    p.find('.produce_' + data.produce).remove();
                    if(!p.find('.produce').length) {
                        $('#order .group_' + data.group).removeClass('expanded');
                    }
                 }

               }
               show_order_button();
               show_nav_buttons();
            });
            return false;
        }

        handle_content_events = function () {
          
            $('#content .produces-list-wrapper .produces-list').each(function() {
               itemLen = 171;
               blockLen = itemLen * 3;
               lines = 3;
               itemsCount = $(this).children().length;
               rows = Math.round((itemsCount / lines));
               if(itemsCount % lines == 1) {
                   rows ++;
               }
               rows = rows < 3 ? 3 : rows;
               w = rows * itemLen;
               lb =  -w + blockLen;
               rb = 0;
               $(this).width(rows * itemLen);
               var that = this;
               var getLeftOffset = function (l) {
                   l = l - (l % itemLen);
                   return (l + blockLen) > 0 ? 0 : (l + blockLen);
               }
               var getRightOffset = function (l) {
                   l = l - (l % itemLen);
                   return (l - blockLen) < lb ? lb : (l - blockLen);
               }
               
               if(w > blockLen) {
                   $('#content .produces-list-wrapper .move_right').fadeIn();
               }
               $(this).parent().find('.move_right').click(function() {
                   
                   $('.produces-list .weight-bt').parent().find('.prices').fadeOut();
                   $('.produces-list .info:visible').fadeOut();
                   nl = getRightOffset(parseInt($(that).css('left')));
                   if(nl >= lb) {
                       $(that).stop().animate({
                        left: nl
                       });
                       $('#content .produces-list-wrapper .move_left').fadeIn();
                       if(getRightOffset(nl) == nl) {
                            $('#content .produces-list-wrapper .move_right').fadeOut();
                       }
                   }
               });
               $(this).parent().find('.move_left').click(function() {
                   $('.produces-list .weight-bt').parent().find('.prices').fadeOut();
                   $('.produces-list .info:visible').fadeOut();
                   nl = getLeftOffset(parseInt($(that).css('left')));
                   if(nl <= 0) {
                       $(that).stop().animate({
                        left: nl
                       });
                       $('#content .produces-list-wrapper .move_right').fadeIn();
                       if(getLeftOffset(nl) == nl) {
                            $('#content .produces-list-wrapper .move_left').fadeOut();
                       }
                   }
               });
            });
        }


        $('#products-menu a').click(function() {
            $('#order .groups > li > a[href^="' + this.href.replace('//', '').replace(location.protocol, '').replace(location.host, '').replace(/\/$/, '') + '"]').click();
            return false
        });

        $('#order .groups > li > a').live('click', function() {
            $('#order .groups li:not(.expanded) .producers:visible').slideUp('fast',  show_nav_buttons);
            if($(this).parent().find('ul li').length > 1) {
                $(this).parent().find('.producers').slideDown('fast', show_nav_buttons);
            }
            $.get(this.href, 'ajax=1', function(html) {
               $('#content').html(html);
               handle_content_events();
            });

            return false;
        });

         $('#order .producers > li > a,#content .producer,.alink').live('click', function() {
            $.get(this.href, 'ajax=1', function(html) {
               $('#content').html(html);
                handle_content_events();
            });
            return false;
        });

         $('#top-menu a').live('click', function() {
            if(this.href.replace(location.protocol+'//'+location.host, '') != '/') {
                $.get(this.href, 'noMainIndex', function(html) {
                   $('#content').html(html);
                   show_cont_nav_buttons();
                   $('#vertical-content-scrool .cnt-top').fadeOut();
                });
                return false;
            }

        });

        $('#order .add-produce,#order .remove-produce').live('click', function() {
            p = $(this).parents('.weight-wrapper');
            add_to_order2(p, this.href, $(this).hasClass('add-produce'));
            return false;
        });

        $('#order .weight-wrapper').each(function() {
            c = $(this).find('.cnt').html();
            $(this).find('.plates').html(render_plates(c));
        });



        $('.produces-list .produce-link').css('cursor', 'pointer').live('click', function(event) {
            $('.weight-bt').parent().find('.prices').fadeOut();
            $('.produces-list .info:visible').fadeOut();
            l = parseFloat($('#content .produces-list-wrapper .produces-list').css('left'));

            $(this).parent().find('.info').find('.content img').load(function(){
        	});
            //alert($(this).parent().find('.info').height())
            $(this).parent().find('.info').css('top', 300 - $(this).parent().find('.info').height() / 2);
            i = $(this).parent().find('.info').css('left', -l).fadeIn();//css('top', event.y).css('left', event.x)
            

        });

        $('.produces-list .weight-bt').click(function() {
            $('.produces-list .info:visible').fadeOut();
            prices = $(this).parent().find('.price-link');
            if(prices.length > 1) {
                o = $(this).parent().find('.prices:hidden');
                $('.weight-bt').parent().find('.prices').fadeOut();
                o.fadeIn();
            } else {
                add_to_order(prices.attr('href'));
            }
            return false;
        });

        $('.produces-list .info .close').live('click', function() {
            $(this).parents('.info').fadeOut();
        });

        $('#content .produces-list-wrapper .produces-list .price-link').live('click', function() {
            in_order_link = $('#order .add-produce[href^="' + this.href.replace('//', '').replace(location.protocol, '').replace(location.host, '') + '"]');
            if(in_order_link.length) {
                in_order_link.click();
            } else {
                add_to_order(this.href);
            }
            return false;
        });


        show_nav = function () {
            o = $('#order');
            cnt_height = $('#order-second-wrapper').height();
            h = o.height();
            if(h > cnt_height) {

            }
        }

        show_nav_buttons = function() {
            o = $('#order');
            cnt_height = $('#order-second-wrapper').height();
            t = parseFloat(o.css('top'));
            if(t == 0) {
                $('#order-nav .top:visible').fadeOut();
            } else {
                $('#order-nav .top:hidden').fadeIn();
            }
            h = o.height() - cnt_height + 20;
            if(t < -h) {
                $('#order-nav .bottom:visible').fadeOut();
            } else {
                $('#order-nav .bottom:hidden').fadeIn();
            }
        }
        
        $('#order-nav').each(function() {
            o = $('#order');
            shift = 400;
            $(this).find('.top').click(function() {
               cnt_height = $('#order-second-wrapper').height();
               t = parseFloat(o.css('top'));
               t = (t + shift) > 0 ? 0 : t + shift;
               o.stop().animate({
                   top: t
               }, show_nav_buttons);
            });
            $(this).find('.bottom').click(function() {
               cnt_height = $('#order-second-wrapper').height();
               t = parseInt(o.css('top').replace('px', ''));
               h = o.height() - cnt_height + 50;
               //if(h > 0) {
                   t = (t - shift) < -h ? -h : t - shift;
                   o.stop().animate({
                       top: t
                   }, show_nav_buttons);
               //}
            })
        });

        $('#auth-form').submit(function() {
            return false;
        });

        $('.ax-form').live('submit', function() {
            var that = this;
            $.ajax(
                {
                 url: $(this).attr('action'), type: 'POST'
                ,data: $(this).serialize()
                ,dataType: 'json'
                ,success: function(r) {
                    if(r.errors) {
                        $(that).find('.error span').html('');
                        for(e = 0; e < r.errors.length; e++) {
                            f = r.errors[e].split('.');
                            $(that).find('[name="' + f[0] + '"]').parents('dl').children('.error').each(function() {
                                $(this).children('span').html($(this).children('.error-list').children('.' + f[1]).text());
                            });
                        }
                    } else {
                        if(r.is_reg && r.name) {
                            $('#user-block .name').html(r.name);
                            $('#auth-form-block').hide();
                            $("#user-block").fadeIn();
                        }
                        if(r.location) {
                            $.get(r.location, '', function(html) {
                                $('#content').html(html);
                            });
                        }
                    }
                }
            });
            return false;
        });

        $('#auth-form .submit').click(function() { $(this).parents('form').submit(); });
        $('#auth-form').submit(function() {
			$(this).find('dl').hide();
			$(this).append('<div id="lFormPreloader" style="padding-top: 20px; padding-left: 60px;"><img src="/images/design/22.gif"></div>');
            $.ajax({
                dataType: 'json',
                type: 'POST',
                url: '/profile/auth',
                data: $(this).serialize(),
                success: function(data) {
                    if(data.success) {
                        $('#auth-form [name=password]').val('');
                        $('#user-block .name').html(data.name);
                        $('#lFormPreloader').remove();
						$('#auth-form dl').show();
						$('#auth-form-block').hide();
						
                        $("#user-block").fadeIn();
                        $.getJSON('/produces/order/checkProfile/', 'ajax=1', function(d) {
                            $('#order').fadeOut();
                            $('#order-nav').fadeOut();
                            $('#do-order-bt font, #do-order-bt a').fadeOut();
                            $('#order-info').html(d.message).fadeIn();
                        });
						
                    } else {
                        
						alert('Íåâåðíîå èìÿ ïîëüçîâàòåëÿ èëè ïàðîëü');
						$('#lFormPreloader').remove();
						$('#auth-form dl').show();
                    }
                }
            })
        });

        $('.logout').live('click', function() {
            $.get(this.href);
            $.get('/?noMainIndex', '', function(html) { $('#content').html(html); });
            $('#order .produces').children().remove();
            $('#order .producers').fadeOut();
            show_order_button();
            $('#user-block').fadeOut('fast', function() {
                $('#auth-form-block').fadeIn();
            });
            return false;
        });
        
        $('.order-form').live('submit', function() {
            var that = this;
            $.ajax(
                {
                 url: $(this).attr('action'), type: 'POST'
                ,data: $(this).serialize()
                ,dataType: 'json'
                ,success: function(d) {
                    if(d.message) {
                        $('#order,#order-nav').fadeOut('fast', function() {
                            $('#order-info').html(d.message).fadeIn();
                            window.setTimeout(function() {
                                $('#order-info').fadeOut('fast', function() {
                                    $(this).html('');
                                    $('#order,#order-nav').fadeIn('fast');
                                });
                            }, 5000);
                        });
                    }
                    if(d.success) {
                        $('#order .produces').children().remove();
                        $('#order .producers').fadeOut();
                        show_order_button();
                    }
                }
            });
            return false;
        });
        
        $('#order-form-hide').live('click', function(){
          $('#order-info').fadeOut('fast');
          $('#order,#order-nav').fadeIn('fast');
          $('#do-order-bt font, #do-order-bt a').fadeIn();
        })

        $('#do-order-bt a').live('click', function() {
            $.getJSON('/produces/order/checkProfile/', 'ajax=1', function(d) {
                $('#order').fadeOut();
                $('#order-nav').fadeOut();
                $('#do-order-bt font, #do-order-bt a').fadeOut();
                $('#order-info').html(d.message).fadeIn();
            });
            /*$.getJSON('/produces/order/process/', 'ajax=1', function(d) {
                if(d.message) {
                    $('#order,#order-nav').fadeOut('fast', function() {
                        $('#order-info').html(d.message).fadeIn();
                        window.setTimeout(function() {
                            $('#order-info').fadeOut('fast', function() {
                                $(this).html('');
                                $('#order,#order-nav').fadeIn('fast');
                            });
                        }, 5000);
                    });
                }
                if(d.success) {
                    $('#order .produces').children().remove();
                    $('#order .producers').fadeOut();
                    show_order_button();
                }
            });*/
        });

        $('#last-orders-wrapper a').live('click', function() {
            $.get(this.href, 'noMainIndex', function(html) {
               $('#content').html(html);
            });
            return false;
        });

        $('.load-order-link').live('click', function() {
            $.get(this.href, 'noMainIndex', function(html) {
                if(html) {
                    $('#order').html(html);
                    show_order_button();
                }
            });
            return false;
        });
        
        $('.order-link-single').live('click', function() {
          
            $.get(this.href, 'noMainIndex', function(html) {
                if(html) {
                    $('#content').html(html);
                }
            });
            return false;
        });

        $('#password-restore-link').click(function() {
            $('#auth-form-block').fadeOut('fast', function() {
                $('#password-restore-block').fadeIn();
            });
        });

        $('#password-restore-form .submit').click(function() {
            mail = $('#password-restore-form [name=email]').val();
            $.getJSON('/classes/users/js.php5?action=forgot_password', { email: mail}, function(d) {
                if(d.notFound) {
                    $('#password-restore-block .form').fadeOut('fast', function() {
                        $('#password-restore-block .notfound').fadeIn();
                    });
                } else if (d.success) {
                    $('#password-restore-block .form').fadeOut('fast', function() {
                        $('#password-restore-block .success').fadeIn();
                    });
                }
            });
        });
        $('#password-restore-block .cancel').click(function() {
            $('#password-restore-block').fadeOut('fast', function() {
                $('#auth-form-block').fadeIn();
                $('#password-restore-block .form').show();
                $('#password-restore-block .notfound, #password-restore-block .success').hide();
            });
        });



        handle_content_events();
        show_order_button();
        show_nav_buttons();
    });
    
    

    
            
})(jQuery);
