(function($){

/* --------- --------- */
/**       OVERLAY      **/
/* --------- --------- */

  $.Overlay = function (options) {
    return $.Overlay.fx.init(options); 
  }
  
  $.Overlay.remove = function () {
    $.Overlay.fx.remove();
  }
  
  $.Overlay.defaults = {
    opacity: 0.8,
    zIndex: 10000
  }

  $.Overlay.fx = {
    d: {},
    init: function(options){
      var fx = this;
      fx.settings = $.extend({}, $.Overlay.defaults, options);
      fx.create();       
    },
    create: function(){
      var fx = this;
      fx.d.overlay = $('<div id="over"></div>').appendTo('#wrapper');
      fx.d.overlay.css({ 'opacity': fx.settings.opacity, 'z-index': fx.settings.zIndex }).show();
      fx.d.exist = true;   
    },
    remove: function(){
      var fx = this;
      if (!fx.d.exist) {
        return false;
      }
      fx.d.overlay.remove();
      fx.d.exist = null;
    }
  }
    
})(jQuery);

(function($){

/* --------- --------- */
/**       LOADER       **/
/* --------- --------- */

  $.Loader = function (options) {
    return $.Loader.fx.init(options); 
  }
  
  $.Loader.remove = function (elm) {
    $.Loader.fx.remove(elm);
  }
  
  $.Loader.defaults = {
    targetEl: null, 
    css: {}, 
    imgPath: '/xxl_templ/images/loading.gif', 
    className: 'default', 
    loadingBox: false
  }
  
  $.Loader.fx = {
    d: {},
    init: function(options){
      var fx = this;
      fx.settings = $.extend({}, $.Loader.defaults, options); 
      return fx.create();       
    },
    create: function(){
      var fx = this;
      fx.d.loader = $('<ins class="loading_indicator" style="background:url(' + fx.settings.imgPath + ')"></ins>');
      fx.d.loader.addClass(fx.settings.className);
      fx.d.loader.css(fx.settings.css);
      if (fx.settings.loadingBox) {
        fx.addLoadingBox();  
      } 
      else{
        fx.settings.targetEl.append(fx.d.loader).show();
      }
      return fx.d.loader;   
    },
    addLoadingBox: function(){
      var fx = this;
      // some code... :D
    },
    remove: function(loader){
      var fx = this;
      if (!loader || !loader.length) {
        return false;
      }
      loader.remove();
    }
  }
    
})(jQuery);


/* --------- --------- */
/**    MODAL WINDOW    **/
/* --------- --------- */

(function($){

  IE7_8 = !$.support.opacity;

	$.Modal = function(options){
		return $.Modal.fx.init(options);
	};
	
	$.Modal.close = function(uniqueId){
		$.Modal.fx.close(uniqueId);
	};
	
	$.Modal.closeAll = function(){
		$.Modal.fx.closeAll();
	};	

	$.Modal.defaults = {
    position: 'auto',                // auto: absolute или fixed решает скрипт (auto, absolute, fixed, static)
    cssModal: null,                
    overlay: true,
    elHash: null,                    // якорь на модальное окно
    emptyModal: false,
    insertHTML: null,
    hideMethod: 'hidden',            // метод скрытия окна (remove, hidden)
    overlayClose: true,              // закрытие по клику на оверлее
    modalClass: null,
    onShow: null,                    // перед показом окошка
    onOpen: null,
    onClose: null                    // после показа окошка
  };

  $.Modal.fx = {
    d: {},
    itemCount: 0,
    
    init: function(options){
      var fx = this;
      fx.settings = $.extend({}, $.Modal.defaults, options);
      fx.create();
    },
    create: function(){
      var fx = this;
      if (fx.settings.emptyModal) {
        fx.modalObj = fx.addEmptyModal();
        fx.modalObj.prepend(fx.settings.insertHTML);
      }
      else {
        fx.modalObj = $(fx.settings.elHash);
      }      
      
      fx.d['m' + fx.itemCount] = fx.modalObj;
      fx.d['m' + fx.itemCount].settings = fx.settings;
      var modalObjWidth = fx.modalObj.innerWidth(),
          modalObjHeight = fx.modalObj.innerHeight(), 
          modalObjPosition = fx.settings.position;

      fx.modalObj.data('unique-id', fx.itemCount);
          
      fx.itemCount++;

      switch (modalObjPosition) {
        case 'auto':
          if (modalObjHeight >= $(window).height()) {
            fx.modalObj.css({ 
              'margin-left': -(modalObjWidth / 2) + 'px', 
              'margin-top': '0', 
              'position': 'absolute', 
              'top': $(document).scrollTop() + 50 + 'px' 
            });
          }
          else{
            fx.modalObj.css({
              'margin-left': -(modalObjWidth / 2) + 'px', 
              'margin-top': -(modalObjHeight / 2) + 'px', 
              'position': 'fixed', 
              'top': '50%'
            });
          }
          break;
        case 'absolute':
          fx.modalObj.css({
            'margin-left': -(modalObjWidth / 2) + 'px', 
            'margin-top': '0', 
            'position': 'absolute', 
            'top': $(document).scrollTop() + 50 + 'px'
          });
          break;
        case 'fixed':
          fx.modalObj.css({
            'margin-left': -(modalObjWidth / 2) + 'px', 
            'margin-top': -(modalObjHeight / 2) + 'px', 
            'position': 'fixed', 
            'top': '50%'
          });
          break;
        case 'static':
          fx.modalObj.css(fx.settings.cssModal);
          break;          
      } 
      
      fx.modalObj.addClass('active');
      
      if ($.isFunction(fx.settings.onShow)) {
        fx.settings.onShow(fx, fx.modalObj); 
      }
            
      fx.open();
      fx.bindEvents();      
      
      return fx.itemCount;
                    
    },
    addEmptyModal: function(){
      var fx = this;
      var emptyModal = $('<div class="popup_window modal">'+
                  '<div class="aux_sh tl"></div>'+
                  '<div class="aux_sh tr"></div>'+
                  '<div class="aux_sh bl"></div>'+
                  '<div class="aux_sh br"></div>'+
                  '<a href="#" class="close_window"></a>'+
                  '</div>').hide().appendTo('body').addClass(fx.settings.modalClass);
        
      return emptyModal;      
    },    
    open: function(){
      var fx = this;
      
      if (fx.settings.overlay) {
        fx.addOverlay();
      }

      if (fx.modalObj.hasClass('visualHidden')) {
        fx.modalObj.data('visualHidden', true).hide().removeClass('visualHidden');
      }

      (IE7_8)
      ?
      fx.modalObj.show(0, function(){
        if ($.isFunction(fx.settings.onOpen)) {
          fx.settings.onOpen(fx, fx.modalObj); 
        }          
      })      
      :
      fx.modalObj.fadeIn(300, function(){
        if ($.isFunction(fx.settings.onOpen)) {
          fx.settings.onOpen(fx, fx.modalObj); 
        }          
      });
       
    },
    bindEvents: function(){
      var fx = this;
      fx.modalObj.find('.close_window').bind('click.modal_close', function(e){
 				e.preventDefault();
				fx.close($(this).parents('.modal.active').data('unique-id'));       
      });
      if (fx.settings.overlayClose) {
        $('#over').bind('click.over_close', function(){
          fx.closeAll();        
        });  
      }      
    },
    addOverlay: function(){
      if (!$('#over').length) {
        $.Overlay();
      } 
    },
    unbindEvents: function(uniqueId){
      var fx = this;
      fx.d['m' + uniqueId].find('.close_window').unbind('click.modal_close');   
    },
    close: function(uniqueId){
      var fx = this,
          hideMethod = fx.d['m' + uniqueId].settings.hideMethod;

      if ($.isFunction(fx.d['m' + uniqueId].settings.onClose)) {
        fx.d['m' + uniqueId].settings.onClose(fx, fx.d['m' + uniqueId]); 
      } 
      
      if (hideMethod == 'hidden') {
        if (fx.d['m' + uniqueId].data('visualHidden')) {
          fx.d['m' + uniqueId].removeData('visualHidden').addClass('visualHidden');
        }
        fx.unbindEvents(uniqueId);
        fx.d['m' + uniqueId].removeClass('active').removeData('unique-id').hide();
      }  
      else if (hideMethod == 'remove') {
        fx.d['m' + uniqueId].removeClass('active').removeData('unique-id').remove();
      }
      
      if ((!$('.modal.active').length) && ($('#over').length)) {
        $.Overlay.remove();
      }
        
    },
    closeAll: function(){
      var fx = this;
      $('.modal.active').each(function(){
        var uniqueId = $(this).data('unique-id');
        var hideMethod = fx.d['m' + uniqueId].settings.hideMethod;
        
        if (hideMethod == 'hidden') {
          fx.unbindEvents(uniqueId);
          $(this).removeClass('active').removeData('unique-id').hide();
        }  
        else if (hideMethod == 'remove') {
          $(this).removeClass('active').removeData('unique-id').remove();
        }
      });
      
      $.Overlay.remove();
      
    }
  }
})(jQuery);


/* --------- --------- */
/**        INFO        **/
/* --------- --------- */

(function($){

  $.Info = function (options) {
    return $.Info.fx.init(options); 
  }
  
  $.Info.defaults = {
    text: '',
    overlay: true,
    infoClass: 'default',
    closeOnClickOK: true,
    onClickOK: null
  }  
  
  $.Info.fx = {
    d: {},
    itemCount: 0,
    init: function(options){
      var fx = this;
      fx.settings = $.extend({}, $.Info.defaults, options); 
      fx.create();       
    },
    create: function() {
      var fx = this;
      
      fx.infoObj = $('<div id="info_window-' + fx.itemCount + '" class="popup_window modal info_window"><p class="info_text" style="text-align:center;">'+
                  fx.settings.text+'</p>'+
                  '<div class="aux_sh tl"></div>'+
                  '<div class="aux_sh tr"></div>'+
                  '<div class="aux_sh bl"></div>'+
                  '<div class="aux_sh br"></div>'+
                  '<div class="info_ok_wrap"><div class="styled_btn main_btn btn1 info_ok"><span class="text">OK</span><i class="l"></i><i class="r"></i></div></div>'+
                  '<a href="#" class="close_window"></a>'+
                  '</div>').addClass('info_'+fx.settings.infoClass).hide().appendTo('body');
      
      fx.d['m' + fx.itemCount] = fx.infoObj;
      fx.infoObj.data('unique-id', fx.itemCount);            
      fx.itemCount++;
                  
      fx.infoObj.find('div.info_ok').bind('click.info', function(e){
        e.preventDefault();
        if ($.isFunction(fx.settings.onClickOK)) {
          fx.settings.onClickOK(fx, fx.d['m' + fx.itemCount]); 
        }        
        if (fx.settings.closeOnClickOK) {
          $.Modal.close($(this).parents('.info_window').data('unique-id'));    
        }
      });
      $.Modal({elHash: fx.infoObj, overlay: fx.settings.overlay, hideMethod: 'remove'});   
    }
  }
    
})(jQuery);


/* ----------- ----------- */
/**        CONFIRM        **/
/* ----------- ----------- */

(function($){

  $.Confirm = function (options) {
    return $.Confirm.fx.init(options); 
  }
  
  $.Confirm.defaults = {
    text: '',
    overlay: true,
    confirmClass: 'default',
    buttons: ['Да', 'Нет'],
    onButtonsClick: null
  }  
  
  $.Confirm.fx = {
    d: {},
    itemCount: 0,
    init: function(options) {
      var fx = this;
      fx.settings = $.extend({}, $.Confirm.defaults, options); 
      fx.create();       
    },
    create: function(){
      var fx = this;
      
      fx.confirmObj = $('<div id="confirm-window-' + fx.itemCount + '" class="popup_window modal confirm-window"><p class="confirm-text">'+
                  fx.settings.text+'</p>'+
                  '<div class="aux_sh tl"></div>'+
                  '<div class="aux_sh tr"></div>'+
                  '<div class="aux_sh bl"></div>'+
                  '<div class="aux_sh br"></div>'+
                  '<div class="confirm-btns"></div>'+
                  '<span class="close_window"></span>'+
                  '</div>').addClass('confirm-'+fx.settings.confirmClass).hide().appendTo('body');
      
      fx.d['m' + fx.itemCount] = fx.confirmObj;
      fx.confirmObj.data('unique-id', fx.itemCount);            
      fx.itemCount++;
      
      $.each(fx.settings.buttons, function(i, val) {
        var button = $('<div class="styled_btn main_btn btn1"><span class="text">' + val + '</span><i class="l"></i><i class="r"></i></div>');
        fx.confirmObj.find('.confirm-btns').append(button);
        button.bind('click', function() {
          if (fx.settings.onButtonsClick && typeof fx.settings.onButtonsClick == 'function') {
            fx.settings.onButtonsClick(fx.confirmObj, val);
            $.Modal.close($(this).parents('.confirm-window').data('unique-id'));
          }
        });       
      });
      $.Modal({elHash: fx.confirmObj, overlay: fx.settings.overlay, hideMethod: 'remove'});   
    }
  }
    
})(jQuery);


/* --------- --------- */
/**        TABS        **/
/* --------- --------- */

(function($){

  var defaults = { activeTab: 0, onClick: function(){} };
  
  var methods = {
  
    // initialise
    init: function(options){
      var settings = $.extend({}, defaults, options);
      var init = $(this).data('tabs');
      if (init){
        return this;
      }
      else{
        $(this).data('tabs', true);
        return this.each(function(){
          var $this = $(this),
              $tabs = $this.find('.tab_link'),
              $items = $this.find('.tabs_item');
          $tabs.bind('click.tabs', function(e){
            e.preventDefault();
            var $this = $(this);
            $tabs.removeClass('active').filter($this).addClass('active');
            $items.addClass('hidden').filter(this.hash).removeClass('hidden');
            settings.onClick.call($(this.hash));
          });
          
          $tabs.eq(settings.activeTab).trigger('click.tabs');
                 
        });        
      }
    },
    
    // switch tabs
    switchTab: function(index){
      $(this).find('.tab_link').eq(index).trigger('click.tabs');
    }
  };
  
  $.fn.Tabs = function(method){
    if (methods[method]){
      return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || ! method){
      return methods.init.apply(this, arguments);
    } else{
      $.error('Method "' +  method + '" does not exist on jQuery.Tabs');
    }
  };
  
})(jQuery);


/* --------- --------- */
/**     ACCORDION      **/
/* --------- --------- */

(function($){
  
  var defaults = { activeItem: 0, speed: 200, maxOneVisible: true, openAllItems: false, onClick: function(){} };
  
  var methods = {
  
    // initialise
    init: function(options){
      var settings = $.extend({}, defaults, options);
      var init = $(this).data('accordion');
      if (init){
        return this;
      }
      else{
        $(this).data('accordion', true);
        return this.each(function(){
          var $this = $(this),
              $headers = $this.find('.accrs_title'),
              $items = $this.find('.accrs_item'),
              $current_item = $items.eq(settings.activeItem);
          $headers.bind('click.accordion', function(e){
            e.preventDefault();
            var $this = $(this),
                $target_item = $this.next($items);
            
            if ($this.hasClass('active') && settings.maxOneVisible) { return false; }

            if (settings.maxOneVisible){
              $headers.removeClass('active').filter($this).addClass('active');
              $current_item.slideUp(settings.speed);
              $target_item.hide().removeClass('hidden').slideDown(settings.speed);
              $current_item = $target_item;
            }                   
            else{
              $this.toggleClass('active');
              $target_item.slideToggle(settings.speed);
            }

            settings.onClick.call($target_item);
            
          });
          
          //$tabs.eq(settings.activeTab).trigger('click.accordion');
                 
        });        
      }
    }    
  };

  $.fn.Accordion = function(method){
    if (methods[method]){
       return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || ! method){
      return methods.init.apply(this, arguments);
    } else{
      $.error('Method "' +  method + '" does not exist on jQuery.Accordion');
    }
  };
  
})(jQuery);


/* --------- --------- */
/**    SUBMIT FORM     **/
/* --------- --------- */

/*(function($){
  var defaults = { disableAnchor: true, disableClass: 'disabled' };
  var methods = {
    init: function(options){
      var settings = $.extend({}, defaults, options);
      var init = $(this).data('submitAnchor');
      if (init){
        return this;
      }
      else{
        $(this).data('submitAnchor', true);
        return this.each(function(){
          var $this = $(this);
          $this.bind('click.submitAnchor', function(e){
            e.preventDefault();
            if ($(this).hasClass(settings.disableClass)){
              return false;
            }
            if (settings.disableAnchor){
              methods.disAnchor.call(this, settings.disableClass);
            }
            $(this).parents('form').submit();
          });  
        });
      }    
    },
    disAnchor: function(disClass){
      $(this).addClass(disClass);
    },
    enableAnchor: function(disClass){
      $(this).removeClass(disClass);
    }
  }

  $.fn.SubmitAnchor = function(method){
    if (methods[method]){
      return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || ! method){
      return methods.init.apply(this, arguments);
    } else{
      $.error('Method "' +  method + '" does not exist on jQuery.SubmitAnchor');
    }
  };    
})(jQuery);*/



$(function(){

  /* Tiny-scrollbar */
 
  $('.show-cart').click(function(e) {
    e.preventDefault();
    $.Modal({
      elHash: this.hash,
      onOpen: function(fx, modal) {
        /*if ((modal.find('.overview').height() > 470) && (!modal.find('.scrollbar-y').data('tsb'))) {
          modal.find('.scrollbar-y').tinyscrollbar({
            size: 141,
            sizethumb: 63
          });
        }
        else if (modal.find('.scrollbar-y').data('tsb')) {
          modal.find('.scrollbar-y').tinyscrollbar_update({
            size: 141,
            sizethumb: 63            
          });
        }*/      
      }
    });
  });


  $('.scrollbar-y').tinyscrollbar({
    size: 141,
    sizethumb: 63
  });
  
  $('.goto-ordering').click(function(e) {
    e.preventDefault();
    $('.big-cart-wrap').fadeOut(200, function() {
      $('.ordering-wrap').hide().removeClass('visualHidden').fadeIn(200);
    });
  });

 /* AJAX-регистрация пользователя */
 
  $('#reg-user-form').bind('submit', function(e) {
    e.preventDefault();
    var formData = $(this).serialize(),
        loader = $.Loader({ targetEl: $(this).find('.submit_button .btn2'), css: { 'right': -20 + 'px', 'top' : 12 + 'px' } });
    $.ajax({
      url: '/xxl_user_admin/ajax_registration.php',
      type: 'post',
      data: formData + '&req_ajax=register_user',
      dataType: 'json',
      success: function(JSONdata) {
        $.Info({ text: JSONdata.text });
        $.Loader.remove(loader);
      }
    });      
  });


  $('.simple-tabs, #goods_ext_descr').Tabs();
  //$('.simple-tabs .tab-links ul').tabs(".simple-tabs .tabs_item", { current: 'active', history: true });
  $('#goods_tabs_content, .filters_box').Accordion({ maxOneVisible: false });
  
  /* IE 7, 8? */

  var IE7_8 = !$.support.opacity;
  var IE7 = !$.support.opacity && $.browser.msie && $.browser.version == 7;

  $('.styled_btn').live('mousedown', function(e){
    $(this).addClass('clicked').focus();
  }).live('mouseup mouseleave', function(){
    $(this).removeClass('clicked');
  });

                                
/* Обработка фокуса и блюра для текстовых полей */

$('input.toggleValue').focus(function(){
  $this = $(this);
  if($this.val()==$this.attr('title')){
    $this.val('');
  };
});
$('input.toggleValue').blur(function(){
  $this = $(this);
  if($this.val()==''){
    $this.val($(this).attr('title'));
  }
});

/* Переключение list & cubs */

$('#method_output a').click(function(e){
  var $this = $(this);
  var goods = $('.list_goods_items.' + $this.parent().attr('class'));
  if ($this.hasClass('active')){
    return false;
  } 
  else{
    $('#method_output a').removeClass('active');
    $this.addClass('active'); 
    if ($this.hasClass('list')){
      goods.removeClass('cubs').addClass('list');  
    } 
    else{
      goods.removeClass('list').addClass('cubs'); 
    }
  } 
  e.preventDefault();
});



/* Подробнее в новостях */

$('.read_full_news').click(function(){
  $(this).parents('.all_news_item').find('.hidden_text').fadeIn(500);
  $(this).hide();
  return false;
});

  $('.show_window').click(function(e){ e.preventDefault(); $.Modal({ elHash: this.hash }); });


/* Всплывающее меню */

if($('#categories .left, #categories .right, #categories .center').length){
var scrW = document.documentElement.clientWidth;    /* Ширина экрана браузера */
var scrH = document.documentElement.clientHeight;   /* Высота экрана браузера */
var scrM = scrH/2;                                  /* Середина экрана браузера */
  $('#categories .left, #categories .right, #categories .center').hover(function(e){
  /* Координата мыши по вертикали */
    var coordY = e.clientY;
    if((!$.support.opacity) && ($.browser.msie) && ($.browser.version==7)){
      $(this).css('z-index','2').find('.tooltip').delay(400).fadeIn(0);
    }
    else{
      $(this).find('.tooltip').delay(400).fadeIn(0).css('z-index','30');
    }
    /* Если курсор в верхней части экрана */
    if(coordY<=scrM){
      /* Левые иконки */
      if($(this).hasClass('left')){
        $(this).find('.tooltip').removeClass('tip_bottom').addClass('tip_top');
        $(this).find('.tooltip .lm').css('background-position','-25px -2470px');
        $(this).find('.arrow').removeClass('bottom').addClass('top');
      }
      /* Правые иконки */
      else if($(this).hasClass('right')){
        $(this).find('.tooltip').removeClass('tip_bottom').addClass('tip_top');
        $(this).find('.tooltip .rm').css('background-position','0 -2470px');
        $(this).find('.arrow').removeClass('bottom').addClass('top');          
      }
      /* Средние иконки */
      else{
        var mL = -$(this).find('.tooltip').innerWidth()/2;
        $(this).find('.tooltip').css({'margin-left': mL});
        $(this).find('.tooltip').removeClass('tip_top').addClass('tip_bottom');
        $(this).find('.tooltip .mt').css('background-position','50% -25px');
        $(this).find('.tooltip .mb').css('background-position','0 0');
        $(this).find('.arrow').removeClass('bottom').addClass('top');
      }
    } 
    /* Если курсор в нижней части экрана */
    else{
      /* Левые иконки */
      if($(this).hasClass('left')){
        $(this).find('.tooltip').removeClass('tip_top').addClass('tip_bottom');
        $(this).find('.arrow').removeClass('top').addClass('bottom');
        var bg = -(2500-($(this).find('.tooltip').height()-30));
        $(this).find('.tooltip .lm').css('background-position','-25px '+bg+'px');
      }
      /* Правые иконки */
      else if($(this).hasClass('right')){
        $(this).find('.tooltip').removeClass('tip_top').addClass('tip_bottom');
        $(this).find('.arrow').removeClass('top').addClass('bottom');
        var bg = -(2500-($(this).find('.tooltip').height()-30));
        $(this).find('.tooltip .rm').css('background-position','0 '+bg+'px');         
      }
      /* Средние иконки */
      else{
        var mL = -$(this).find('.tooltip').innerWidth()/2;
        $(this).find('.tooltip').css({'margin-left': mL});
        $(this).find('.tooltip').removeClass('tip_bottom').addClass('tip_top');
        $(this).find('.tooltip .mt').css('background-position','0 -25px');
        $(this).find('.tooltip .mb').css('background-position','50% 0');
        $(this).find('.arrow').removeClass('top').addClass('bottom');          
      }       
    }
    }, 
    function(e){
      $(this).find('.tooltip').clearQueue().stop(true,true).fadeOut(0,function(){
        if((!$.support.opacity) && ($.browser.msie) && ($.browser.version==7)){
          $('#categories .goods_category').css('z-index','auto');
        }
        return; 
      });
    });
};

  
/* Аккордеон поиска */

  $('.search_anchor').click(function(){
    var hash = this.hash;
    $('.search_accrd').filter('.active_search_accrd').removeClass('active_search_accrd').animate({'height': 'hide'},300);
    $('.search_accrd').filter(hash).addClass('active_search_accrd').hide().removeClass('hidden').animate({'height': 'show'},300);
    return false;
  }); 


/* ЧПУ в поиске */

$('#advanced_search form').bind('submit.action', function(){
  var newUrlValues = "";
  newUrlValues += $('input[name=s_part_id]').val()+'/';
    
  if ( $('input[name=s_cat_id]').val() == 'null' ) { newUrlValues += '0' + '/'; }
  else { newUrlValues += $('input[name=s_cat_id]').val() + '/'; }
    
  if ( $('input[name=s_cat_chld_id]').val() == 'null' ) { newUrlValues += '0' + '/'; }
  else { newUrlValues += $('input[name=s_cat_chld_id]').val() + '/'; }
    
  if ( $('input[name=s_prod_firm]').val() == '' ) { newUrlValues += '0' + '/'; }
  else { newUrlValues += $('input[name=s_prod_firm]').val().replace(/\/()/g, "")+'/'; }
    
  if ( $('input[name=s_prod_mod]').val() == '' ) { newUrlValues += '0' + '/'; }
  else { newUrlValues += $('input[name=s_prod_mod]').val().replace(/\/()/g, "")+'/'; }
    
  if ( $('input[name=price_from]').val() == '' ) { newUrlValues += '0' + '/'; }
  else { newUrlValues += $('input[name=price_from]').val().replace(/\/()/g, "")+'/'; }
    
  if ( $('input[name=price_to]').val() == '' ) { newUrlValues += '0' + '/';  }
  else { newUrlValues += $('input[name=price_to]').val().replace(/\/()/g, "")+'/'; }
    
  newUrlValues += $('input[name=s_curr_id]').val()+'/';   
  newUrlValues = encodeURI(newUrlValues);
  $(this).attr('action','/searchex/'+newUrlValues); 

});

$('#simple_search form, #price_search_form').bind('submit.action', function(){
  var newUrlValues = "";
  
  if ( $('input[name=text]').val() == '' ) { newUrlValues += '0' + '/';  }
  else { newUrlValues += $('input[name=text]').val().replace(/\/()/g, "")+'/'; }

  newUrlValues = encodeURI(newUrlValues);
  $(this).attr('action','/search/'+newUrlValues);
});


/* Слайдер */

if($('.sliderbox').length){
var el = $('.sliderbox ul');
var parEl= el.parent('.sliderbox');
var count_el = el.find('li').size();
var width_el = el.find('li').outerWidth(true);
var width_parEl = parEl.width();
$('a.next').click(function(){
  if(!el.is(':animated')){
    if(parseInt(el.css('margin-left'))==-(count_el-parseInt(width_parEl/width_el))*width_el){return false;}
    else{el.animate({'margin-left': parseInt(el.css('margin-left'))-width_el}, 300); }
  };
  return false;
});
$('a.prev').click(function(){
  if(!el.is(':animated')){
    if(parseInt(el.css('margin-left'))==0){return false;}
    else{el.animate({'margin-left': parseInt(el.css('margin-left'))+width_el}, 300);}
  };
  return false;
});
};

  
/* Тур */

$('a.down, a.up').click(function(){
  var clickInd = parseInt($(this).text())-1,
      clickTarget = $(this).parents('.main_tabs').find('.three_clicks_box').eq(clickInd).position();
  $("html:not(:animated)" + (!$.browser.opera ? ",body:not(:animated)" : "")).animate({scrollTop: clickTarget.top}, 400);
  return false;
});
$('a.go_first').click(function(){
  var clickTargetFirst = $(this).parents('.main_tabs').find('.three_clicks_box').eq(0).position();
  $("html:not(:animated)" + (!$.browser.opera ? ",body:not(:animated)" : "")).animate({scrollTop: clickTargetFirst.top}, 400);
  return false;  
});


/* Подсчёт символов */

$.countSymbols = function(el, limit){
  if((el.val().length) > limit){
    el.val(el.val().substr(0, limit)); 
    return false;
  }
  el.next('.count_symbols').find('ins').text(limit-(el.val().length));
};

$('#social_text').keyup(function(){
  return $.countSymbols($(this), 100);
});
$('#social_text').change(function(){
  return $.countSymbols($(this), 100);
});
$('#text_of_ads').keyup(function(){
  return $.countSymbols($(this), 75);
});
$('#text_of_ads').change(function(){
  return $.countSymbols($(this), 75);
});
$('#edit_text_of_ads').bind('keyup change', function(){
  return $.countSymbols($(this), 75);
});


/* Less - more */

$('a.all').click(function(){
  $(this).toggleClass('active').prev('.other').slideToggle(300);
  if($(this).hasClass('active')){
    $(this).html('свернуть');
  }
  else{
    $(this).html('все производители &rarr;')
  }
  return false;
});


/* Показ инфы по клику */

$.fn.QuickShow = function(){
  return this.each(function(){
    $(this).click(function(){
      var $this = $(this);
      $this.toggleClass('active').next('.quick_show_item').toggleClass('hidden');
    });
  });
}

$('.quick_show').QuickShow();


/* Распределение классов в выпадающем меню */

function topmenu_categories(){
  var topmenu_li_pos = 29,
      z = 100;
  $('.topmenu_categories_inner ul.topmenu .tooltip').removeClass('left centerleft centerright right');
  $('.topmenu_categories_inner ul.topmenu > li').removeClass('nbt nbl').each(function(i){
    if (IE7) {
      $(this).children('div').css('z-index', z);
      $(this).children('.tooltip').css('z-index', z);
      z--;
    }
  var pooo = $(this).position(); 
  if(pooo.left <= 285){
    $(this).find('.tooltip').addClass('left');
  }
  else if((pooo.left > 285) && (pooo.left <= 500)){
    $(this).find('.tooltip').addClass('centerleft');
  }
  else if((pooo.left > 500) && (pooo.left <= 715)){
    $(this).find('.tooltip').addClass('centerright');
  }
  else{
    $(this).find('.tooltip').addClass('right');
  };
  if (i == 0){ $(this).addClass('nbl'); }
  if(pooo.top == 0){
    $(this).addClass('nbt');
  }
  else if(pooo.top > topmenu_li_pos){
    topmenu_li_pos = topmenu_li_pos + 30;
    $(this).addClass('nbl');
  }        
  });
}

topmenu_categories();

$('.topmenu_categories_inner ul.topmenu > li:first').resize(topmenu_categories);


/* Выпадающее верхнее меню */

$('.topmenu_categories_inner ul.topmenu > li').hover(function(){
  var $this = $(this),
      liWidth = $this.innerWidth() + 14,
      tooltip = $this.find('.tooltip'),
      mt = $this.find('.mt');

  $this.find('.auxiliary_grey').width(liWidth);
  
  if (tooltip.hasClass('left')){
    mt.css('left', liWidth + 'px');    
  }
  else if (tooltip.hasClass('centerleft')){
    mt.css('left', liWidth + 155 + 'px');   
  }
  else if (tooltip.hasClass('centerright')){
    mt.css('right', liWidth + 155 + 'px');
  }
  else{
    mt.css('right',liWidth + 'px');    
  }
  tooltip.delay(400).fadeIn(0,function(){
    $(this).parents('li').addClass('active');
  });
},
function(){
  $(this).find('.tooltip').clearQueue().stop(true,true).fadeOut(0, function(){
    $(this).parents('li').removeClass('active');  
  });
});


  /* Ползунок с ценами */

  $.initSliderRange = function(elmSlider, elmFrom, elmTo, minValue, maxValue, step){  
    $(elmSlider).slider({
		  range: true,
		  min: minValue,
		  max: maxValue,
		  values: [minValue, maxValue],
		  slide: function(event, ui){
        $(elmFrom).val(ui.values[0]);
        $(elmTo).val(ui.values[1]);
		  },
		  step: step
    });
    var sliderWidth = $(elmSlider).width();
    $(elmFrom).val($(elmSlider).slider("values",0));
    $(elmTo).val($(elmSlider).slider("values",1));
  };


  /* Подгрузка селектов */

  $.ajaxLoadSelects = function(el, url){
    var el_parent_cusel = el.parents('.cusel:first');
    var id__ = el_parent_cusel.attr('id').slice(11);
    if (id__ == 'section_search'){
      $.doChange(el, 's_cat_id', el.find('span').attr('val'), url, 'cats'); 
    }
    else if (id__ == 'category_search'){
      $.doChange(el, 's_cat_chld_id', el.find('span').attr('val'), url, 'cats');
    }
    else if (id__ == 'shop_country'){
      $.doChange(el, 'region_id', el.find('span').attr('val'), url, 'geo');
    }
    else if (id__ == 'shop_region'){
      $.doChange(el, 'city_id', el.find('span').attr('val'), url, 'geo');
    }
    else{
      return;
    }     
  }

  $.doChange = function(eventEl, src, val, url, type){
    var targetEl = eventEl.parents('form').find('#'+src);
    targetEl.find('.cuselText').text('Загрузка...');
		$.ajax({
      url: url,
      type: 'get',                                        
      data: 'data='+src+'&val='+val,
      dataType: 'html',
      success: function(data){
        targetEl.html(data);
        cuSel({ changedEl: targetEl.find('.repl'), visRows: 8, scrollArrows: false });
        targetEl.find('ins').click(function(){
          $.ajaxLoadSelects($(this), url);
        });           
      }
    });    
  }

  $('#s_part_id .cusel ins').live('click', function(){
    $.ajaxLoadSelects($(this), '/xxl_func_lib/xxl_func_price_srch.php');
  });
  
  $('#cntr_id .cusel ins').live('click', function(){
    $.ajaxLoadSelects($(this), '/xxl_func_lib/xxl_func_geo.php');
  });
  
  
  /* Очищаем селект с городом, если сменили страну */
  $('#cuselFrame-shop_country').live('change', function(){
    if($('#cuselFrame-shop_city ins').length){
      $('#cuselFrame-shop_city').find('.cusel-scroll-wrap').remove().end().find('.cuselText').empty();
    }  
  });
  
  
  /* Очищаем селект с подкатегорией, если сменили раздел */
  $('#cuselFrame-section_search').live('change', function(){
    if($('#cuselFrame-subcategory_search ins').length){
      $('#cuselFrame-subcategory_search').find('.cusel-scroll-wrap').remove().end().find('.cuselText').empty();
    }  
  });


  /* Инициализация кусэла */
  function initCusel(){
    var params = {
      changedEl: ".repl",
      visRows: 8,
      scrollArrows: false
    }
    cuSel(params);
    init_cusel = true;    
  }
  if($('.repl').length){
    initCusel();
  }


/* Каталог компаний и прайсов */

$('div.dyn_catalog_item').Accordion({ maxOneVisible: false, openAllItems: true });

$('div.dyn_catalog_item div.show_all a').click(function(e){
  e.preventDefault();
  $(this).toggleClass('link_popular link_alphabet');
  $('div.dyn_catalog_item ul.popular').slideToggle();
  $('div.dyn_catalog_item ul.alphabet').slideToggle();
  if ($(this).hasClass('link_popular')) {
    $(this).text('Показать популярные');
  }
  else {
    $(this).text('Показать все');
  }
});

/* Подгрузка карты с расположением компании из каталога */

$.loadYandexMap = function() {
  var $this = $(this),
      linkToCompany = $this.parents('div.info').find('div.name a').attr('href'),
      $hiddenInputs = $this.nextAll('input:hidden'),
      coord1 = parseFloat($hiddenInputs.filter('.map_coord1').val()),
      coord2 = parseFloat($hiddenInputs.filter('.map_coord2').val()),
      name = $hiddenInputs.filter('.map_name').val(),
      description = $hiddenInputs.filter('.map_description').val(),
      map;
      
  $.Modal({
    emptyModal: true,
    insertHTML: '<div class="mini_map"></div><div class="goto_company"><div class="styled_btn main_btn btn2"><a href="#">Перейти к компании</a><i class="l"></i><i class="r"></i></div></div>',
    hideMethod: 'remove',
    modalClass: 'mini_map_popup',
    onOpen: function(fx, modal) {          
      modal.find('div.goto_company a').attr('href', linkToCompany);         
      map = new YMaps.Map(YMaps.jQuery(".mini_map", modal)[0]);
            
      // Add new bubble
      var placemark = new YMaps.Placemark(new YMaps.GeoPoint(coord1, coord2));
      placemark.name = name;
      placemark.description = description;
            
      // Set bubble content
      placemark.setIconContent(name); 
            
      // Устанавливает начальные параметры отображения карты: центр карты и коэффициент масштабирования
      map.setCenter(new YMaps.GeoPoint(coord1, coord2), 16);			      
			map.addOverlay(placemark); 
      map.addControl(new YMaps.Zoom());
    },
    onClose: function(fx, modal) {
      map.destructor();  
    }
  });
  
  return false;  
}

$('div.company_catalog div.address a').click($.loadYandexMap);


/* * * * * TEMPORARY SOLUTION * * * * */

var regshop_valid = true;

$('#reg-shop-form #name_shop').blur(function() {
  var el = $(this),
      error;
  if (el.val() == '') {
    error = 'Обязательное поле';
    regshop_valid = false;
  }
  if (error) {
    createErrorMessage(el, error)
  }
});

$('#reg-shop-form #cuselFrame-shop_region, #reg-shop-form #cuselFrame-shop_city').live('blur', function() {
  var el = $(this),
      error;
      cuselVal = el.find('input:hidden').val();
  if (cuselVal == 'null' || cuselVal == '0' || cuselVal == '') {
    error = 'Выберите вариант';
    regshop_valid = false;
  }
  if (error) {
    createErrorMessage(el, error)
  }
});

$('#reg-shop-form #street_shop').blur(function() {
  var el = $(this),
      error;
  if (el.val() == '') {
    error = 'Обязательное поле';
    regshop_valid = false;
  }
  else if (!/^[A-Za-zА-ЯЁа-яё0-9-.\s]+$/.test(el.val())) {
    error = 'Только буквы, цифры, ., -';
    regshop_valid = false;
  }
  if (error) {
    createErrorMessage(el, error)
  }
});

$('#reg-shop-form #house_shop, #reg-shop-form #housing_shop, #reg-shop-form #office_shop').blur(function() {
  var el = $(this),
      error;
  if (el.val() != '' && !/^[A-Za-zА-ЯЁа-яё0-9-.\s]+$/.test(el.val())) {
    error = 'Только буквы, цифры, ., -';
    regshop_valid = false;
  }
  if (error) {
    createErrorMessage(el, error)
  }
});

$('#reg-shop-form #code_country, #reg-shop-form #code_city, #reg-shop-form #tel').blur(function() {
  var el = $(this),
      error;
  if (el.val() == '') {
    error = 'Обязательное поле';
    regshop_valid = false;
  }
  else if (!/^[0-9-+*.()\s]+$/.test(el.val())) {
    switch (el.attr('id')) {
      case 'code_country': error = 'Некорректный код страны'; break;
      case 'code_city': error = 'Некорректный код города'; break;
      case 'tel': error = 'Некорректный телефон'; break;
    }
    regshop_valid = false;
  }
  if (error) {
    createErrorMessage(el, error)
  }
});

$('#reg-shop-form #webaddr_shop').blur(function() {
  var el = $(this),
      error;
      webregexp = /^(?:(?:https?):\/\/(?:[a-z0-9а-яё_-]{1,32}(?::[a-z0-9а-яё_-]{1,32})?@)?)?(?:(?:[a-z0-9а-яё-]{1,128}\.)+(?:com|net|org|mil|edu|arpa|ru|gov|biz|info|aero|inc|name|[a-zа-яё]{2,6})|(?!0)(?:(?!0[^.]|255)[0-9]{1,3}\.){3}(?!0|255)[0-9]{1,3})(?:\/[a-z0-9а-яё.,_@%&?+=\~\/-]*)?(?:#[^ \'\"&<>]*)?[\s]*$/i;
  if (el.val() != '' && !webregexp.test(el.val())) {
    error = 'Некорректный URL';
    regshop_valid = false;
  }
  if (error) {
    createErrorMessage(el, error)
  }
});

$('#reg-shop-form #shop_email').blur(function() {
  var el = $(this),
      error;
  if (el.val() == '') {
    error = 'Обязательное поле';
    regshop_valid = false;
  }
  else if (!/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}[\s]*$/.test(el.val())) {
    error = 'Некорректный e-mail';
    regshop_valid = false;
  }
  else {
    var loader = $.Loader({ targetEl: el.parent(), css: { 'right': -20 + 'px', 'top' : 9 + 'px' } });
      $.ajax({
        url: '/xxl_seller_admin/ajax_registration.php?req_ajax=email_repeat',
				data: {req_ajax: 'email_repeat'},
        type: 'get',
        data: { req_ajax: "email_repeat", email: el.val() },
        success: function(data) {
          if (data == 'no') {
            el.parent().append('<span class="check_step"></span>');
          }
          else {
            error = 'E-mail занят';
            createErrorMessage(el, error);
            regshop_valid = false;
          }
          $.Loader.remove(loader);
        }
      });
  }
  if (error) {
    createErrorMessage(el, error)
  }
});

$('#reg_form #email_reg').blur(function() {
  var el = $(this),
      error;
  if (el.val() == '') {
    error = 'Обязательное поле';
    regshop_valid = false;
  }
  else if (!/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}[\s]*$/.test(el.val())) {
    error = 'Некорректный e-mail';
    regshop_valid = false;
  }
  else {
    var loader = $.Loader({ targetEl: el.parent(), css: { 'right': -20 + 'px', 'top' : 9 + 'px' } });
      $.ajax({
        url: '/xxl_user_admin/ajax_registration.php?req_ajax=email_repeat',
				data: {req_ajax: 'email_repeat'},
        type: 'get',
        data: { req_ajax: "email_repeat", email: el.val() },
        success: function(data) {
          if (data == 'no') {
            el.parent().append('<span class="check_step"></span>');
          }
          else {
            error = 'E-mail занят';
            createErrorMessage(el, error);
            regshop_valid = false;
          }
          $.Loader.remove(loader);
        }
      });
  }
  if (error) {
    createErrorMessage(el, error)
  }
});

$('#reg_form .validate').focus(function() {
  removeErrorMessage($(this).attr('id'));
});

$('#reg-shop-form #password').blur(function() {
  var el = $(this),
      error;
  if (el.val() == '') {
    error = 'Обязательное поле';
    regshop_valid = false;
  }
  else if (el.val().length < 6) {
    error = 'Не менее 6 символов';
    regshop_valid = false;
  }
  if (error) {
    createErrorMessage(el, error)
  }
});


$('#reg-shop-form .validate').focus(function() {
  removeErrorMessage($(this).attr('id'));
});

$('#reg-shop-form #cuselFrame-shop_region, #reg-shop-form #cuselFrame-shop_city').live('focus', function() {
  removeErrorMessage($(this).attr('id'));
});


$('#reg-shop-form').submit(function(e) {
  var form = $(this),
      valid = true,
      countErrors = 0;
  regshop_valid = true;
  removeErrorMessage('all', form);
  /*form.find('.validate').each(function() {
    var currentEl = $(this);
    currentEl.blur();
    valid = regshop_valid;
    if (!valid) {
      countErrors++;
    }
  });*/
  if (countErrors > 0) { return false; }
  else {
    createCaptcha(form);
    return false;
  }
});



function createErrorMessage(el, error) {
  var elPosLeft = el.position().left,
      elPosTop = el.position().top,
      errorBox = $('<div class="notice_error" id=notice_error_'+el.attr('id')+'><div></div></div>').hide();
      errorBox.css({
        'left': (elPosLeft - 20) + el.outerWidth(true) * 2/3,
        'top': elPosTop - 28
      });
      el.parent().append(errorBox);
      errorBox.find('div').text(error).end().show()
              .bind('click', function() {
                var $this = $(this),
                focusElmSelector = ($this.attr('id')).slice(13);
                removeErrorMessage(focusElmSelector);
                $('#' + focusElmSelector).focus();
              });
}


function removeErrorMessage(id, form) {
  if (id == 'all') {
    form.find('div.notice_error').remove();
  }
  else {
    $('#notice_error_' + id).remove();
  }
}


function createCaptcha(form) {
      var captcha = $('<form id="captcha" class="form_code xxl_form" method="get">'+
                    '<div class="form_item code"><label for="code" class="block">Введите проверочный код:</label>'+
                    '<div class="ss inp_wrap"><div class="styled_input inp1"><input type="text" id="code" name="code" /></div></div>'+
                    '</div><img src="/xxl_templ/php/secpic.php?'+Math.random()+'" width="100" height="60" alt="captcha" /><p class="err"></p>'+
                    '<div class="submit_button">'+
                    '<div class="styled_btn main_btn btn2"><button type="submit" value="Отправить">Отправить</button><span>Отправить</span><i class="l"></i><i class="r"></i></div></div></form>');

      $.Modal({
        emptyModal: true,
        hideMethod: 'remove',
        insertHTML: captcha,
        modalClass: 'captcha_modal',
        overlay: false,
        onOpen: function(fx, modal) {
          modal.find('form').bind('submit', function(e){
            e.preventDefault();
            var code = $('#code').val();
            if ( !code ) {
              return false;
            }
            else {
              var loader = $.Loader({ targetEl: modal.find(':submit').parent(), css: { 'right': -20 + 'px', 'top' : 11 + 'px' } });
              $.ajax({
                url: form.attr('action'),
                type: 'post',
                data: form.serialize() + '&code=' + code,
                dataType: 'json',
                success: function(JSONdata) {
                  if (JSONdata.status == 0) {
                    $('p.err').html('Неверный код!');
                  }
                  else {
                    $.Modal.close(modal.data('unique-id'));
                    $.Info({ 
                      text: JSONdata.text, 
                      overlay: false,
                      onClickOK: function(fx, modal) {
                        $.Modal.close($('#registration-shop-modal').data('unique-id'));
                      }  
                    });
                  }
                  $.Loader.remove(loader);
                }
              });
            }
          });
        }
      });
      return false;
    }


  /* Подгрузка селектов */

  $.ajaxLoadSelects = function(el, url){
    var el_parent_cusel = el.parents('.cusel:first');
    var id__ = el_parent_cusel.attr('id').slice(11);
    if (id__ == 'section_search'){
      $.doChange(el, 's_cat_id', el.find('span').attr('val'), url, 'cats');
    }
    else if (id__ == 'category_search'){
      $.doChange(el, 's_cat_chld_id', el.find('span').attr('val'), url, 'cats');
    }
    else if (id__ == 'shop_country'){
      $.doChange(el, 'region_id', el.find('span').attr('val'), url, 'geo');
    }
    else if (id__ == 'shop_region'){
      $.doChange(el, 'city_id', el.find('span').attr('val'), url, 'geo');
    }
    else{
      return;
    }
  }

  $.doChange = function(eventEl, src, val, url, type){
    var targetEl = eventEl.parents('form').find('#'+src);
    targetEl.find('.cuselText').text('Загрузка...');
		$.ajax({
      url: url,
      type: 'get',
      data: 'data='+src+'&val='+val,
      dataType: 'html',
      success: function(data){
        targetEl.html(data);
        cuSel({ changedEl: targetEl.find('.repl'), visRows: 12 });
        //eventEl.parents('form').XXLForm('reInit');
        targetEl.find('ins').click(function(){
          $.ajaxLoadSelects($(this), url);
        });
      }
    });
  }

  $('#s_part_id .cusel ins').live('click', function(){
    $.ajaxLoadSelects($(this), '/xxl_func_lib/xxl_func_price_srch.php');
  });

  $('#cntr_id .cusel ins').live('click', function(){
    $.ajaxLoadSelects($(this), '/xxl_func_lib/xxl_func_geo.php');
  });


  $('.dropdown-list-wrap a.dropdown-list-link').click(function(e) {
    e.preventDefault();
    var $t = $(this),
        ddlist = $(this.hash);
    $('.dropdown-list:visible').not(ddlist).hide();
    ddlist.toggle(200);
    $(document).unbind('click.ddlist');
    var firstClick = true;
    $(document).bind('click.ddlist', function(e) {
      if (!firstClick) {
        ddlist.hide();
        $(document).unbind('click.ddlist');        
      }
      firstClick = false;  
    });
  });

  $('.expand-product-description a').click(function(e) {
    e.preventDefault();  
    var $t = $(this);
    if ($t.hasClass('expand')) {
      $t.text('Свернуть все');
      $('.goods_accrs_descr').find('.accrs_title').not('.active').click();
    }
    else {
      $t.text('Развернуть все');
      $('.goods_accrs_descr').find('.accrs_title.active').click();
    }
    $t.toggleClass('expand hide');
    
  });

  /***** ADMIN *****/
  
  $('#info-about-user .registration-user form').bind('submit', function(e) {
  	e.preventDefault();
		var formData = $(this).serialize(),
				loader = $.Loader({ targetEl: $(this).find('.submit_button .btn2'), css: { 'right': -20 + 'px', 'top' : 11 + 'px' } });
		$.ajax({
			method: 'post',
			data: formData + '&req_ajax=save_user',
      dataType: 'json',
      success: function(JSONdata) {
        $.Info({ text: JSONdata.text, overlay: true });
        $.Loader.remove(loader);
      }
		});
  });


  
  $('form.sortable-form').submit(function(e) {
    e.preventDefault();
    var formData = $(this).serialize(),
        loader = $.Loader({ targetEl: $(this).find('.submit_button .btn2'), css: { 'right': -20 + 'px', 'top' : 12 + 'px' } });
    $.ajax({
      type: 'post',
      data: formData,
      dataType: 'json',
      success: function(JSONdata) {
        $.Info({ text: JSONdata.text });
        $.Loader.remove(loader);
      }
    });
  });  

});
