jQuery(document).ready(function() {

    var images = ['pic1', 'pic2', 'pic3', 'pic4', 'pic5', 'pic6'];  /* Количество картинок */
    jQuery('.rotator').animate({opacity: 0.0}, 0);
    jQuery('.rotator').attr('id', ''+images[Math.floor(Math.random() * images.length)]+'');
    jQuery('.rotator').animate({opacity: 1.0}, 1000);

    /***************************
      TAB-Menu :: Обработка TAB-Menu в "Наш контент" и "SMS-платежи"
    ***************************/	
    jQuery('#tab_menu li a').click( function () { /* Если нажимаем на любую из вкладок, то,... */
      jQuery('#tab_menu li').removeAttr('id');          /* Удаляем все параметры в TAB вкладках id, в том чилсе id='current' - обнуляем */
      jQuery(this).parent('li').attr('id', 'current');  /* Уcтанавливаем в текущем списке самой TAB вкладки id='current' - активизируем (отображаем) ее */

      jQuery('div.tab').hide();         /* Убираем со всех tab-menu (содержимого вкладки) активность. Содержимое не показываем */
      jQuery('div#'+jQuery(this).attr('id')).show(); /* Показываем то содержимое, которое соответствует нажатой вкладке */
    });

    /***************************
      ButtonSlide :: Для IVR. Голосовые сервисы
    ***************************/	
    jQuery(".btn-slide").click(function() {
      jQuery("#slideBar_drop-down_list").slideToggle("slow");
      jQuery(this).toggleClass("active"); return false;
    });

    var click_btn = "";

    function setMainSlide(this_is, slide) {
      jQuery(slide).slideToggle("fast");
      jQuery("[id *= 'sub_slide_']").hide();
      jQuery(slide).show();
        /* Сохраняем текущие настройки */
      if (jQuery(this_is).hasClass("active")) { activem = "active"} else { activem = "" };

      jQuery("[class *= 'btn-slide-']").removeClass('active');
      jQuery("[class *= 'btn-main_slide-']").removeClass('active');

      jQuery(this_is).addClass(activem);
      jQuery(this_is).toggleClass('active');

      jQuery("[id *= 'b-scroll-']").hide();
      click_btn = slide;

      jQuery(slide+" #b-scroll-htm").show();
      jQuery(slide+" .btn-slide-htm").addClass('active');
    }

    var activem;

    jQuery(".btn-main_slide-1").click(function() { setMainSlide(this, "#sub_slide_1"); });
    jQuery(".btn-main_slide-2").click(function() { setMainSlide(this, "#sub_slide_2"); });
    jQuery(".btn-main_slide-3").click(function() { setMainSlide(this, "#sub_slide_3"); });
    jQuery(".btn-main_slide-4").click(function() { setMainSlide(this, "#sub_slide_4"); });
    jQuery(".btn-main_slide-5").click(function() { setMainSlide(this, "#sub_slide_5"); });
    jQuery(".btn-main_slide-6").click(function() { setMainSlide(this, "#sub_slide_6"); });
    var active;
    var id_scroll;
    var display;

      function setSlide(id_scroll, this_is) {
        /* Сохраняем текущие настройки */
        if (jQuery(this_is).hasClass("active")) { active = "active"} else { active = "" };
        display = jQuery(id_scroll).css("display");

        jQuery("[id *= 'b-scroll-']").hide();
        jQuery("[class *= 'btn-slide-']").removeClass('active');

        jQuery(this_is).addClass(active);
        jQuery(id_scroll).css("display", display);
        jQuery(id_scroll).slideToggle("fast");
        jQuery(id_scroll).show();
        jQuery(this_is).toggleClass('active');
      }

    jQuery(".btn-slide-htm").click(function() { setSlide(click_btn+" #b-scroll-htm", this); });
    jQuery(".btn-slide-perl").click(function() { setSlide(click_btn+" #b-scroll-perl", this); });
    jQuery(".btn-slide-php").click(function() { setSlide(click_btn+" #b-scroll-php", this); });

    jQuery('#menu ul a').each(function(n, element1)  {
      if (jQuery(element1).attr('id') == 'active') {
        jQuery('ul.sub-menu li a').each(function(n,element)  {
          if (jQuery(element).attr('id') == 'current') {
            jQuery(element1).next().css('display', 'block');
          }
        });
      }
    });


    // Ставим обработку события при наведении или отведении курсора на элементы главного меню.
    jQuery('#menu ul li').hover(
      function() { expand(jQuery(this)); },
      function() { collapse(jQuery(this)); }
    );

    // Обработка события при наведении курсора на элементы главного меню.
  function expand($elem)  {
    
    
    // Если выбранный элемент не активный - подвели курсор, то...
      //jQuery('#menu li a').each(function(n, element)  {
        
      //  if (jQuery(element:first).attr('id') != 'active')
       
    if ($elem.find('ul').attr('class') == 'sub-menu')  {
      if ($elem.find('a:first').attr('id') != 'active') {
        $elem.find('a:first').attr('id', 'select');   // ...то ставим id=select, для того чтобы при отведении курсора с области
        //alert('a');
        jQuery('ul.sub-menu').css('display', 'none');
        //alert('s');
        $elem.find('a:first').next().css('display', 'block');
      }
      else  {
        if ($elem.find('ul').attr('class') == 'sub-menu')  {
          //alert('a');
           $elem.find('ul').css('display', 'block');
           
           // alert($elem.find('ul').attr('class'));
          }
        /* Если active главное меню и current подменю */
        //alert('a');
        if ($elem.find('.sub-menu ul a').attr('id') == 'current')  {
        alert('ddd1');
          $elem.find('a:first').next().css('display', 'block'); /* fix подменю */
       }
       
        //else
        //alert('d');
      }

        //alert('f');
        //$elem.hide('blind', {}, 500); 
    //});
    // Применяем данное событие к меню, которое содержит дополнительные разделы (раскрывающийся список).
    if ($elem.find('ul').attr('class') == 'sub-menu')  {
}
  //jQuery('ul#sub-menu_menu li a').each(function(n, element)  {
    //alert('f');
  //});
  }  
  }
  
    // Обработка события при отведении курсора на другие элементы главного меню.
  function collapse($elem){
    //alert('d');
      //  alert($elem.index());
    // Применяем данное событие к разделам главного меню, которые не активны по click (раздел не выбран).
     if ($elem.find('ul').attr('class') == 'sub-menu')  {
    if ($elem.find('a:first').attr('id') != 'active') {

        //$elem.find('ul#sub-menu_menu').css('display', 'block');
      //jQuery(element).find('#sub-menu_menu').css('display', 'none');
      //alert('stop1');
      $elem.find('a:first').attr('id', '') ; /* Убираем у всех их select, тем самым остается только элемент с аттрибутом Active */

      jQuery('ul.sub-menu li a').each(function(n, element)  {
        //alert(element);
        //if (jQuery(this).is("#current")) alert('d');

        if (jQuery(element).attr('id') == 'current') {
 
          if ($elem.find('ul').attr('class') == 'sub-menu')  {
            //alert(jQuery(element).attr('id'));
             if ($elem.find('ul').prev().attr('id') != 'select')  {
              
              $elem.find('ul.sub-menu').css('display', 'none');
              jQuery('ul.sub-menu').each(function(n, element)  {
                
                if (jQuery(element).prev().attr('id') == 'active')  {
                //alert(jQuery(element).attr('class'));
                //jQuery(element).css('display', 'none');
                jQuery(element).css('display', 'block');
                //alert($elem.find('ul#sub-menu_menu').attr('class'));
                //jQuery(element).next().css('display', 'none');
                //alert('a1');
              }
              });
            }
            else
            $elem.find('ul.sub-menu').css('display', 'block');
            //alert($elem.find('ul#sub-menu_menu').attr('class'));
            //alert($elem.find('ul').attr('class'));
          }
        //if ($elem.attr('id') == 'active')  {
        //alert('c');
        //}
        //alert(element);
          else{
            alert('stop');
            jQuery(element).css('display', 'none');
            $elem.find('ul').css('display', 'none');
          }
        //else
          
        //alert(jQuery('ul#sub-menu_menu a').attr('id'));
        }
        else  {
          $elem.find('ul').css('display', 'none');
          //alert('d');
        }
      });
      //jQuery('ul#sub-menu_menu').css('display', 'none');  
      //alert('s');
    }
    else
      
      //alert($elem.find('a').attr('id'));
      if ($elem.find('a').attr('id') == 'active')  {
        $elem.find('a').next().css('display', 'none');
        jQuery('ul.sub-menu li a').each(function(n, element)  {
          if (jQuery(element).attr('id') == 'current') {
            //alert($elem.find('a').next().attr('class'));;
            $elem.find('a').next().css('display', 'block');
            //jQuery('ul#sub-menu_menu li a').//  $elem.find('ul').css('display', 'none');
            //alert('d');
          }
          //else
            //$elem.find('a').next().css('display', 'none');
        });
      }
      //find('ul').css('display', 'none');
       jQuery('ul.sub-menu li a').each(function(n, element)  {
        //alert(element);
        //if (jQuery(this).is("#current")) alert('d');
        
        
        if (jQuery(element).attr('id') != 'current') {
        //  $elem.find('ul').css('display', 'none');
        }
      });
    
    
    }
    else  {
      
      
      jQuery('ul.sub-menu li a').each(function(n, element)  {
        //alert(element);
        //if (jQuery(this).is("#current")) alert('d');

        if (jQuery(element).attr('id') == 'current') {
          jQuery(element).find('.sub-menu').css('display', 'block');
        }

      });
    }
  }
  
  
    /***************************
      Rotate картинки
      <div id="rotator">
          <ul>
            <li class="show" id="pic1"></li>
            <li id="pic2"></li>
            <li id="pic3"></li>
          </ul>
      </div>
    ***************************/
    function theRotator() {
      // Устанавливаем прозрачность всех картинок в 0
      $('div#rotator ul li').css({opacity: 0.0});
  
      // Берем первую картинку и показываем ее (по пути включаем полную видимость)
      $('div#rotator ul li:first').css({opacity: 1.0});
  
      // Вызываем функцию rotate для запуска слайдшоу, 5000 = смена картинок происходит раз в 5 секунд
      //setInterval('rotate()', 3800);
      rotate();
    }

    function rotate() {
      // Берем первую картинку
      var current = ($('div#rotator ul li.show')?  $('div#rotator ul li.show') : $('div#rotator ul li:first'));

      // Берем следующую картинку, когда дойдем до последней начинаем с начала
      var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div#rotator ul li:first') :current.next()) : $('div#rotator ul li:first'));

      // Показываем картинки в случайном порядке
       var sibs = current.siblings();
       var rndNum = Math.floor(Math.random() * sibs.length );
       var next = $( sibs[ rndNum ] );

      // Подключаем эффект растворения/затухания для показа картинок, css-класс show имеет больший z-index
      next.css({opacity: 0.0})
      .addClass('show')
      .animate({opacity: 1.0}, 1000);

      // Прячем текущую картинку
      current.animate({opacity: 0.0}, 2000)
      .removeClass('show');
    };
});
