$(function() {
    function share_wrap() {
      var
        share_timer  = [],
        $share_links = [];

      function _get_index($a) {
        return parseInt($a.attr('rel').replace('index-', ''));
      }

      function start_close_timer($a) {
        var index = _get_index($a);
        share_timer[index] = setTimeout(function() {
          $('div.share-inline', $($a).parent()).hide('fast');
        }, 500);
      }

      function stop_close_timer($a) {
        var index = _get_index($a);
        if (share_timer[index]) {
          clearTimeout(share_timer[index]);
          share_timer[index] = false;
        }
      }

      var i = 0;
      $('a.share-toggle').each(function() {
        $share_links[i] = $(this);
        $share_links[i].attr('rel', 'index-' + i);
        $share_links[i].hover(function() {
          stop_close_timer($(this));
          $('div.share-inline', $(this).parent()).show('fast');
        }, function() {
          start_close_timer($(this));
        });
        share_timer[i] = false;
        i++;
      });

      $('div.share-inline').unbind().hover(function() {
        stop_close_timer($('a.share-toggle', $(this).parent()));
        $('div.share-inline', $(this).parent()).show('fast');
      }, function() {
        start_close_timer($('a.share-toggle', $(this).parent()));
      });
    
    }
    share_wrap();

    if ($('span.rate-stars').size() > 0) {
      /* save current rating */
      var
        current = [],
        i = 0;
      $('span.rate-stars a img').each(function() {
        current[i++] = $(this).attr('src');
      });

      /* bind listener */
      $('span.rate-stars a')
        .hover(function() {
          $(this).prevAll('a').each(function() {
            $('img', $(this)).attr('src', '/images/star-active.gif');
          });
          $('img', $(this)).attr('src', '/images/star-active.gif');
          $(this).nextAll('a').each(function() {
            $('img', $(this)).attr('src', '/images/star-deactive.gif');
          });
        }, function() {
          $(this)
            .parent('span.rate-stars')
            .children('a')
            .each(function(i) {
              $('img', $(this)).attr('src', current[i]);
            });
        })
        .click(function() {
          var
            $a = $(this),
            id = $a.parent('span.rate-stars').attr('rel').replace('id-', '');
          $.cookie('r_' + id, true, {
            expires: 7
          });

          $.ajax({
            url: $a.attr('href'),
            type: "GET",
            success: function(data, textStatus) {
              $a.parent('span.rate-stars').html(data);
            }
          });

          return false;
        });
    }

    if ($('#restaurant-photos').size() == 1) {
      var
        block = $('#restaurant-photos'),
        $main_photo = $('#main-photo'),
        $load_image = $('#load-image');
      if (block.find('.one-photo').size() > 5) {
        block.jCarouselLite({
          btnNext: '.scroll-pics-vert .arrow-next',
          btnPrev: '.scroll-pics-vert .arrow-prev',
          speed: 300,
          visible: 5,
          scroll: 1
        });
      } else {
        block.find('.one-photo').eq(0).css('marginLeft', 0);
      }
      $('#restaurant-photos a').click(function() {
          var $a = $(this),
          image = new Image();

          image.src = $a.attr('href');

          if (image.complete) {
            $main_photo.attr('src', $a.attr('href'));
          } else {
            $load_image.show();
            $(image).load(function() {
              $load_image.hide();
              $main_photo.attr('src', $a.attr('href'));
            });
          }

          return false;
        });
    }

    if ($('div.menu-wrap').size() > 1) {
      function menu_wrapper() {
        var current_index = 0,
        cur_cat_name = 'general' ,
        total_page = $('div.general.menu-wrap').size();
        if (total_page>1) { $('#menu-pages .page-next a').show()}
            else {$('#menu-pages .page-next a').hide()}

        
        function show_menu(num) {
          $('div.menu-wrap')
          .hide()
          .eq(num).show();
        }
        $('.menu-back').click(function() {
            var current_index = 0,
            cur_cat_name = 'general' ,
            total_page = $('div.general.menu-wrap').size();
            $('div.menu-wrap').hide();
            $('div.general.menu-wrap').eq(0).show();
            $('#menu-pages .page-prev a').hide();
            if (total_page>1) { $('#menu-pages .page-next a').show()}
            else {$('#menu-pages .page-next a').hide()}
        });
            
        $('tr.activ.menuha').click(function() {
            var id_el = $(this).attr('id');
            cur_cat_name = id_el ;
            current_index = 0;
            total_page =  $('div.'+cur_cat_name+'.menu-wrap').size();
            $('div.menu-wrap').hide();
            $('div.'+cur_cat_name+'.menu-wrap').eq(0).show();
            $('#menu-pages .page-prev a').hide();
            if (total_page>1) { $('#menu-pages .page-next a').show()}
            else {$('#menu-pages .page-next a').hide()}
        });
        $('#menu-pages .page-next a').click(function() {
            ++current_index;
            $('#menu-pages .page-prev a').show()
            if (current_index + 1 == total_page) {
              $(this).hide();
            }
            show_menu(current_index);
            return false;
          });

        $('#menu-pages .page-prev a')
          .click(function() {
            --current_index;
            $('#menu-pages .page-next a').show()
            if (current_index == 0) {
              $(this).hide();
            }
            show_menu(current_index);
            return false;
          })
          .hide();
      }
      menu_wrapper();
    } else {
      $('#menu-pages').hide();
    }

    if ($('a.calendar-arrows').size() > 0) {
    
      function bind_click() {
        $('a.calendar-arrows').click(function() {
            var
              $a = $(this);
              $('#loader').show();
            $.ajax({
              url: $a.attr('href'),
              type: "GET",
              success: function(data, textStatus) {
                $a.parents('div.box-calendar').html(data);
                bind_click();
                $('#loader').hide();
              },
              error: function() {
                $('#loader').hide();
              }
            });

            return false;
          });
      }
      bind_click();
    }

    $('#show-blog-more').click(function() {
      if ($('#blogs2').hasClass('hidden')) {
        $('#blogs2').slideDown('fast', function () {
          $('#show-blog-more').text('-5')
          $('#blogs2').removeClass('hidden')
        });
      } else {
        $('#blogs2').slideUp('fast', function () {
          $('#show-blog-more').text('+5')
          $('#blogs2').addClass('hidden')
        });
      }
	  
      return false
    });
  
    /*
  if ($('#show-blog-more').size() > 0) {

    var
      blog_more_loaded = false,
      $a = $('#show-blog-more'),
      showed = false;

    function load_more() {
      if (blog_more_loaded == true) {
        toggle_sliding();
      } else {
        $.ajax( {
          url: $a.attr('href'),
          type: "GET",
          success: function(data, textStatus) {
            blog_more_loaded = true;
            $a.parent('div.total-count').before(data);
            share_wrap();
            show_more();
          }
        });
      }
    }

    function toggle_sliding() {
      if (showed) {
        hide_more();
        showed = false;
      } else {
        show_more();
        showed = true;
      }
    }

    function show_more() {
      $('#blogs-more').slideDown();
      $a.text('-5');
    }

    function hide_more() {
      $('#blogs-more').slideUp();
      $a.text('+5');
    }
    
    $('#show-blog-more').click(function() {
      load_more();
      return false;
    });

  }
*/
    var Bulletin = {
      init: function() {
        var
          t = this;
        t.bind_click($('#show-bulletin-more'));
      }
      ,bind_click: function($a) {
        var
          t = this;
        $a.click(function() {
          $a
            .css('borderBottom', 'none')
            .css('paddingTop', '2px')
            .html('<img src="/images/indicator.gif" alt="" />')
            .click(function() {
              return false
            });
          $.ajax({
            url: $a.attr('href'),
            type: "GET",
            success: function(data, textStatus) {
              $('#more-bulletin').replaceWith('<br />' + "\n" + data);
              share_wrap();
              t.bind_click($('#show-bulletin-more'));
            }
          });
         return false;
        });
      }
    }
  
    if ($('#show-bulletin-more').length > 0) {
      Bulletin.init();
    }


    var TopNews = {
      init: function() {
        var
          t = this,
          $wrapper = $('#top-news div.wrapper'),
          sum_padding = 23,
          left_pos = 0;
        function scroll() {
          $wrapper.animate({
            'left': '-=1px'
          }, 20, function() {
            if ($('p:first', $wrapper).width() + sum_padding
            < Math.abs(parseInt($wrapper.css('left'))) - left_pos) {
              left_pos = Math.abs(parseInt($wrapper.css('left')));
              $wrapper.append($('p:first', $wrapper));
              $wrapper.css('paddingLeft', left_pos + 'px');
            }
            scroll();
          });
        }
        scroll();
      }
    }

    if ($('#top-news').size() > 0) {
      TopNews.init();
    }

    //очистить поле поиска от значения по умолчанию на фокусе
    $('#keywordsInput').focus(function() {
      if ($(this).val() == 'Поиск по ключевым словам') $(this).val('');
    });
  
    // валидация формы ввода комментариев
    if ($('#comment-form').size() > 0) {
      $("#comment-form").validationEngine({
        inlineValidation: false,
        success:  false
      });
    }

    var TopBoxes = {
      init: function() {
        $('#register-toggle').click(function() {
          $(this).toggleClass('act');
          $('#register-window').toggle();
          $('#login-window').hide();
          $('#login-toggle').removeClass('act');
          $.validationEngine.closePrompt('.formError', true);

          return false;
        });

        $('#login-toggle').click(function() {
          $(this).toggleClass('act');
          $('#login-window').toggle();
          $('#register-window').hide();
          $('#register-toggle').removeClass('act');
          $.validationEngine.closePrompt('.formError', true);

          return false;
        });
      }
    }

    TopBoxes.init();

    $('#authenticate').click(function() {
      $('html').animate({
        scrollTop: 0
      }, 'slow', function() {
        if (!$('#login-toggle').hasClass('act')) {
          $('#login-toggle').click();
        }
      });

      return false;
    });

    // register form validation
    if ($('#register-form').size() > 0) {
      var
        $username = $('#user-username-id'),
        $password = $('#user-password-id'),
        $email    = $('#user-email-id'),
        $login_u  = $('#signin-username-id'),
        $login_p  = $('#signin-password-id');
      $username.focus(function() {
        if ($(this).val() == 'Логин') {
          $(this).val('');
        }
      });
      $username.blur(function() {
        if ($(this).val() == '') {
          $(this).val('Логин');
        }
      });
      $password.focus(function() {
        if ($(this).val() == 'Пароль') {
          $(this).val('');
        }
      });
      $password.blur(function() {
        if ($(this).val() == '') {
          $(this).val('Пароль');
        }
      });
      $email.focus(function() {
        if ($(this).val() == 'Эл. почта') {
          $(this).val('');
        }
      });
      $email.blur(function() {
        if ($(this).val() == '') {
          $(this).val('Эл. почта');
        }
      });
      $login_u.focus(function() {
        if ($(this).val() == 'Логин') {
          $(this).val('');
        }
      });
      $login_u.blur(function() {
        if ($(this).val() == '') {
          $(this).val('Логин');
        }
      });
      $login_p.focus(function() {
        if ($(this).val() == 'Пароль') {
          $(this).val('');
        }
      });
      $login_p.blur(function() {
        if ($(this).val() == '') {
          $(this).val('Пароль');
        }
      });
      $("#register-form").submit(function() {
        if ($username.val() == 'Логин') {
          $username.val('');
        }
        if ($password.val() == 'Пароль') {
          $password.val('');
        }
        if ($email.val() == 'Эл. почта') {
          $email.val('');
        }
      });
      $("#register-form").validationEngine({
        inlineValidation: false,
        success:  false,
        failure: function() {
          $("#register-form input").blur();
        }
      });
      $("#login-form").submit(function() {
        if ($login_u.val() == 'Логин') {
          $login_u.val('');
        }
        if ($login_p.val() == 'Пароль') {
          $login_p.val('');
        }
      });
      $("#login-form").validationEngine({
        inlineValidation: false,
        success:  false,
        failure: function() {
          $("#login-form input").blur();
        }
      });
    }
    
    if ($('#description-toggle').size() > 0) {
      var
        $a = {},
        $profile_description = $('#profile-description'),
        $p = {},
        balance_height = 10;

      if ($('p', $profile_description).length) {
        $p = $('p', $profile_description).eq(0);
        $profile_description.height($p.height() + balance_height);
      } else {
        $profile_description.height($('#description-wrap').height() + balance_height);
        $('#description-toggle').hide();
      }
      if (typeof console != 'undefined') {
        console.log($p);
      }
      var
        need_close_height = $profile_description.height(),
        need_open_height = $('#description-wrap').height() + balance_height,
        state_is_open = 0;
      $('#description-toggle').click(function() {
        $a = $(this);
        $profile_description.animate({
          'height': (state_is_open ? need_close_height : need_open_height)
        }, 300, function() {
          $('img', $a).attr('src', '/images/arrow-' + (state_is_open ? 'down' : 'up') + '_green.gif');
          state_is_open ^= 1;
        });

        return false;
      });
    }

    $('.nice_select').click(function() {
      if (oTab = $(this).siblings('table.nice_table')) {
        if (oTab.css('display') == 'none') oTab.show();
        else oTab.hide()
      }
      
      return false
    })
    $('.nice_list a').click(function(){
      $(this).blur()
      if ($(this).hasClass('active')) $(this).removeClass('active')
      else $(this).addClass('active')
      
      return false
    })
    // collect checked items
    function collectNiceCheckbox(oTab, oInput) {
      if (oNice = $(oTab).find('.nice_list a')) {
        oSelIds  = ''
        oSelText = '' // new text for select box title
        $(oNice).each(function(){
          if ($(this).hasClass('active')) {
            oId = $(this).attr('href').substr(1)
            //alert($(this).html())
            oSelIds+= oId + ';'
            // show new selections
            oTitle = $(this).html()
            oSelText+= oTitle+';'
          }
        })
			
        //
        if (oInput) $(oInput).val(oSelIds)
			
        if (oSelText.length>18) oSelText = oSelText.substr(0,18)+'...'
			
        return oSelText
      }
    }
    $('a img.nice_ok').click(function(){
      if (oTab = $(this).parent().parent().parent().parent().parent('table.nice_table')) {
        oTab.hide()
			
        if (oSel = $(oTab).siblings('.nice_select').find('.inner')) $(oSel).html()
        if (oInput = $(oTab).siblings('input')) $(oInput).val()
			
        oSelText = collectNiceCheckbox(oTab, oInput);
			
        if (oSelText=='') oSelText = $(oTab).siblings('.default_text').html()
        if (oSel) $(oSel).html(oSelText)
      }
      return false
    });
    $('a img.nice_ok2').click(function(){
        if (oTab = $(this).parent().parent().parent().parent().parent('table.nice_table')) {
          oTab.hide()
          
          if (oSel = $(oTab).siblings('.nice_select').find('.inner')) $(oSel).html()
          if (oInput = $(oTab).siblings('input')) $(oInput).val()
          
          oSelText = collectNiceCheckbox($(oTab).find('.nice_outer').eq(0), $(oInput).eq(0));
          oSelText+= collectNiceCheckbox($(oTab).find('.nice_outer').eq(1), $(oInput).eq(1));
          
          if (oSelText=='') oSelText = $(oTab).siblings('.default_text').html()
          else if (oSelText.length>18) oSelText = oSelText.substr(0,18)+'...'
		  
          if (oSel) $(oSel).html(oSelText)
        }
        return false
      });
    $('#doAdvSearch').click(function(){
      if (oTabs = $('.search_ext .nice_list')) {
        $(oTabs).each(function(){
          oId = $(this).attr('id').replace(/_id$/,'');
			
          if (oSel = $('#'+oId+'_select').find('.inner')) $(oSel).html();
          if (oInput = $('input[name="'+oId+'"]')) $(oInput).val();
			
          oSelText = collectNiceCheckbox($(this).parent(), oInput);
			
          if (oSelText=='') oSelText = $(oInput).siblings('.default_text').html();
          if (oSel) $(oSel).html(oSelText);
        });
      }
      //$('.search_ext').hide()
      //$('.search-details').show()
      if ($('form.niceform').submit) $('form.niceform').submit();
      return false;
    })
  
    // check current values in search and update custom select boxes
    oBoxes = ['district','metro','kitchen','price_range','feature']
    populateNiceSelect()
  
    function populateNiceSelect() {
      $(oBoxes).each(function(){
        oItems = $('table.'+this+'Table').find('.nice_list')
        if (oPie = $('input[name="'+this+'"]').val()) {
          myArr = oPie.split(';')
          $(myArr).each(function(){
            if (this!='') {
              $(oItems).find('a[href="#'+this+'"]').addClass('active')
            }
          })
        }
      })
      $('a img.nice_ok').click()
      $('a img.nice_ok2').click()
    }
  
    // show/hide advanced search
    $('#showAdvSearch').click(function(){
      // clone selected items to the advanced search panel
      $(oBoxes).each(function(){
        oItems = $('#'+this+'_id')
		  
        if (oPie = $('input[name="'+this+'"]').val()) {
          myArr = oPie.split(';');
          $(myArr).each(function(){
            if (this!='') {
              $(oItems).find('a[href="#'+this+'"]').addClass('active')
            }
          })
        }
      });
	  
	  
      $('.search_ext').show()
      $('.search-details').hide()
      return false
    });
    // hide and clear advanced search
    $('#hideAdvSearch').click(function(){
      $('.search_ext').hide();
      $('.search-details').show();
      $('.nice_list a').removeClass('active');
	  
      $(oBoxes).each(function(){
        $('input[name="'+this+'"]').val('');
      });
      $('a img.nice_ok').click();
	  
      return false;
    });
  
    // nice scroll bars
    $('.arrUp').click(function(){
      if (oNice = $(this).parent().siblings().find('.nice_list')) {
        oTop = parseInt($(oNice).css('top'))
        oTop+=20
        if (oTop>0) oTop=0
        $(oNice).css('top', oTop+'px')
			
        // move ball
        oMaxHeight = parseInt($(oNice).height())-220
			
        if (oBall = $(this).parent().parent().siblings().find('.nice_ball')) {
          oHeight = $(oBall).parent().height() // max height for ball
          oBallTop = parseInt(-oTop * oHeight / oMaxHeight)-6
          $(oBall).css('top', oBallTop+'px')
        }
      }
		
      return false
    });
    $('.arrDown').click(function(){
      if (oNice = $(this).parent().parent().siblings().find('.nice_list')) {
        oMaxHeight = -(parseInt($(oNice).height())-220)
        oTop = parseInt($(oNice).css('top'))
        oTop-=20
        if (oTop<oMaxHeight) oTop=oMaxHeight
        $(oNice).css('top', oTop+'px')
			
        // move ball
        if (oBall = $(this).parent().parent().siblings().find('.nice_ball')) {
          oHeight = $(oBall).parent().height() // max height for ball
          oBallTop = parseInt(-oTop * oHeight / -oMaxHeight)-6
          $(oBall).css('top', oBallTop+'px')
        }
      }
      return false
    });
    $('.nice_ball').draggable({
      axis: 'y',
      containment: 'parent',
      drag: function(event, ui){
        //alert(event.pageY)
        // calculate offset
        oMinY = $(this).parent().offset().top
        oMaxY = oMinY + $(this).parent().height()
		  
        oNice = $(this).parent().parent().siblings().find('.nice_list')
        oMaxHeight = -(parseInt($(oNice).height())-220)
		  
        if (oMaxY==oMinY || event.pageY==oMinY) oTop = 0;
        else oTop = parseInt(oMaxHeight*(event.pageY-oMinY)/(oMaxY-oMinY))
		  
        if (oTop<oMaxHeight) oTop=oMaxHeight
        if (oTop>0) oTop=0
		  
        $(oNice).css('top', oTop+'px')
      //$('.logdiv').html('top='+oTop+ ' oMaxY='+oMaxY+ ' oMinY='+oMinY+' event.pageY='+event.pageY+' oMaxHeight='+oMaxHeight)
      }
    });
    // accordion
    $('.accord').click(function(){
      $(this).blur()
      $('.accord img').attr('src', '/images/nice/accordr.png');
      $(this).find('img').attr('src', '/images/nice/accord.png');
      $('.accord').siblings('.nice_outer').hide();
      $(this).siblings('.nice_outer').show()
      return false
    });
    $('.autoselect').focus(function(){
      $(this).select();
    })
    // favourites
    $('p.fav a').jFav();
  });
