$.fn.disable = function(options) {
  // iterate and reformat each matched element
  return this.each(function() {
    $(this).attr('disabled', 'disabled').change();
  });
};

$.fn.enable = function(options) {
  // iterate and reformat each matched element
  return this.each(function() {
    $(this).removeAttr('disabled').change();
  });
};

$.fn.equalHeight = function() {
	var tallest = 0;
	this.each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	this.height(tallest);
	return this;
}

$(function() {
  $('.category-grid .b-c-w').equalHeight();
  
  $('#b-products-promo td .b-c-w-2').equalHeight();
  
  $('#b-banner-intro .slides').height($('#b-banner-intro .slides a:first').height());
  
  $('#b-banner-intro .controls').tabs('#b-banner-intro .slides > a', {effect: 'fade', fadeOutSpeed: 500, rotate: true}).slideshow({autoplay: true, interval: 5000});
  
  $('[placeholder]').placeholder();
  
  $(' #header .contacts a, .phone-time a, #b-consult a, .reviews-panel > a, a.cart, .flypage-image a').overlay({
  	mask: {
  		color: '#000',
  		loadSpeed: 100,
  		opacity: 0.5
  	},
		fixed: false,
		onBeforeClose: function() {
		  $('div.error').hide();
		}
  });
  
  $('.zoom-product').overlay({
  	mask: {
  		color: '#000',
  		loadSpeed: 100,
  		opacity: 0.5
  	},
  	fixed: false,
  	onBeforeLoad: function(e) {
  	  var element = e.originalTarget || e.srcElement;
  	  var set_html = $(element).parent('a.zoom-product').next('.zoomable').html();
  	  $('#flypage-images .p-c-w-2').html(set_html);
  	  $('.p a.close').click(function(e) {
  	    e.preventDefault();
  	    $(element).parent('a.zoom-product').data('overlay').close();
  	  });
  	  
  	  $('#flypage-images .thumbs a').click(function(e) {
  	    e.preventDefault();
  	    set_src = $(this).attr('href');
  	    set_text = $(this).attr('title');
  	    $('#flypage-images .big').fadeTo(200, 0.01, function() {
  	      $(this).attr('src', set_src).fadeTo(200, 1);
  	      $('#flypage-images .photo-text').text(set_text);
  	    });
  	  });
  	}
  });
  
  $('.p a.close').click(function(e) {
    e.preventDefault();
  });
  
  $('#flypage-images .thumbs a').click(function(e) {
    e.preventDefault();
    set_src = $(this).attr('href');
    set_text = $(this).attr('title');
    $('#flypage-images .big').fadeTo(200, 0.01, function() {
      $(this).attr('src', set_src).fadeTo(200, 1);
      $('#flypage-images .photo-text').text(set_text);
    });
  });
  
  $.tools.validator.localizeFn('[required]', {
  	ru: 'Это обязательное поле. Пожалуйста, заполните его.'
  });
  
  $('form').validator({lang: 'ru', singleError: true});
  
  $('#b-products-promo .b-h').tabs('#b-products-promo div.panes > div', {
    onClick: function(e, index) { 
      $('#b-products-promo .b-h h3').removeClass('current'); 
      $('#b-products-promo .b-h h3:eq('+index+')').addClass('current'); 
    }
  });
  
  $('#b-flypage-info .b-h').tabs('#b-flypage-info div.panes > div', {
    onClick: function(e, index) { 
      $('#b-flypage-info .b-h h3').removeClass('current'); 
      $('#b-flypage-info .b-h h3:eq('+index+')').addClass('current'); 
    }
  });
  
  $('#nav td').hover(function() {
    $(this).addClass('hov');
    if ($.browser.msie && $.browser.version == '6.0') {
      $('select').hide();
    }
  },
  function() {
    $(this).removeClass('hov');  
    if ($.browser.msie && $.browser.version == '6.0') {
      $('select').show();
    }
  });
  $('#nav div > a').each(function(){
    if ($(this).height() < 20) {
      $(this).addClass('o-l');
    }
  });
  if ($.browser.msie) {
    $('.drop').each(function(){
      $('.drop-b', this).width($(this).width() - 12);
    }); 
  }
  $('form .reset').click(function(e) {
    e.preventDefault();
    $(this).parents('form')[0].reset();
  });
  
  $('select:disabled, textarea:disabled, input:disabled').each(function() {
    $(this).parents('.f-i').addClass('f-disabled');
  });
  
  $('select').live('change', function() {
    if ($(this).is(':disabled') == false) {
      $(this).parents('.f-i').removeClass('f-disabled');
    } else {
      $(this).parents('.f-i').addClass('f-disabled');  
    }
  });

});

$(function() {
  $('#feedback-form').submit(function() {
      $form = $(this);
	  $.post("/ajax/add_review.php",
              $(this).serialize(), 
              function(ret) {
                if (ret == '1') { // если все ок, возвращай 1
//                  $(this).replaceWith('<h1>Ваш отзыв успешно добавлен!</h1>');
					$form.replaceWith('<h1>Ваш отзыв успешно добавлен!</h1>');
                } else if (ret == '2') { // если капча неправильно введена, возвращай 2
                  $(this).find('#feedback-captcha').addClass('error');
                 // $form.replaceWith('<h1>Ваш запрос отправлен!</h1>');
                }
              }
      ); 


//	 $(this).replaceWith('<h1>Ваш отзыв успешно добавлен</h1>');

    return false;
  });


  $('a.cart').click(function() {
      $cart_link = $(this);
	  $product_added = $('#product-added');
	  $.post("/ajax/add2basket.php",
              { id: $cart_link.attr("id")}, 
              function(ret) {
					$product_added.text(ret.NAME);
					$(".cart a").text('Корзина ('+ret.COUNT+')');
              },
			  "json"
      ); 


//	 $(this).replaceWith('<h1>Ваш отзыв успешно добавлен</h1>');

    return false;
  });

  $('#select_SORT1').change(function(){
//	  alert('123');
	$('#form_sort1').data('validator').destroy();
	$('#form_sort2').data('validator').destroy();
	$('form#form_sort1').submit();
  });


/*
 	jQuery("#PersonNameField, #PersonPhoneField").keyup(function(){
		var name_len = jQuery("#PersonNameField").val().length;
		var phone_len = jQuery("#PersonPhoneField").val().length;
		if(name_len > 0 && phone_len > 0)
		{
			jQuery("#callback_submit").attr({disabled: ""});
			jQuery("#randField").attr({value: "<?=time()?>"});
		}
		else
		{
			jQuery("#callback_submit").attr({disabled: "disabled"});
			jQuery("#randField").attr({value: ""});
		}
	});
*/
	
	
//	var options = { target:"#callback_changer",url:"/call.php"};
//	jQuery("#cant-call-form").ajaxForm(options);

  $('#cant-call-form').submit(function(e) {
    $form = $(this);
    if (!e.isDefaultPrevented()) {
	  $.post("/call.php",
              $(this).serialize(), 
              function(ret) {
                if (ret == '1') { // если все ок, возвращай 1
//                  $(this).replaceWith('<h1>Ваш отзыв успешно добавлен!</h1>');
										$form.find('.reset').click();
                }
              }
      ); 


//	 $(this).replaceWith('<h1>Ваш отзыв успешно добавлен</h1>');
		}
    return false;
  });


});


function load_sub_podbor(val) {
    $("#sub_podbor").html('<img src="/img/loading.gif">');
    var senddata = "action=get_podbor&id="+val;
    $.post("/ajax.php", senddata,
                  function(ret) {
    					$("#sub_podbor").html(ret);
                  }
        );
}

function load_end_podbor(val) {
    $("#sub_end_podbor").html('<img src="/img/loading.gif">');
    var senddata = "action=get_end_podbor&id="+val;
    $.post("/ajax.php", senddata,
                  function(ret) {
    					$("#sub_end_podbor").html(ret);
                  }
        );
}

function load_podbor_item_(val) {
    $("#sub_podbor_item").append('<div id="item_loading"><img src="/img/loading.gif"></div>');
    var senddata = "action=get_podbor_item&id="+val;
    $.post("/ajax.php", senddata,
                  function(ret) {
                      $.each(ret,function(k,v)
                      {
                         $('#replace_'+k).html(v);
                      });
                      $('#item_loading').remove();
                      $("#sub_podbor_item").show('fast');
                  }, "json"
        );

}

function load_podbor_item(val) {
    $(".cpt_maincontent").html('<div class="item_loading"><img src="/img/loading.gif"></div>');
    $('.cpt_maincontent').load("/podbor_inc.php");
    $(".cpt_maincontent").before('<div class="item_loading"><img src="/img/loading.gif"></div>');
    var senddata = "action=get_podbor_item&id="+val;
    $.post("/ajax.php", senddata,
                  function(ret) {

                      $.each(ret,function(k,v)
                      {
                         $('#replace_'+k).html(v);
                      });
                      $('.item_loading').remove();
                      $("#sub_podbor_item").show('fast');
                  }, "json"
        );

}


function gosub() {WRSub=window.open('http://tok-shop.ru/1/vote.php?id=1','WRGolos','width=450,height=350,left=250,top=100'); WRSub.focus();}
function gorez() {WRSub=window.open('http://tok-shop.ru/1/rezult.php?id=1','WRRezultGolos','width=450,height=350,left=250,top=100'); WRSub.focus();}

var _gaq = _gaq || [];
   _gaq.push(['_setAccount', 'UA-23843604-1']);
   _gaq.push(['_trackPageview']);

   (function () {
       var ga = document.createElement('script');
       ga.type = 'text/javascript';
       ga.async = true;
       ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
       var s = document.getElementsByTagName('script')[0];
       s.parentNode.insertBefore(ga, s);
   })();

   $(document).ready(function () {
       $('#slider').nivoSlider({effect:'fold'});
       $("#tabs").tabs();

       //$("#ibp_types").dropdownchecklist({ emptyText: "Все типы" });
       //$("#ibp_brands").dropdownchecklist({ emptyText: "Все бренды" });

       $('.acc_brands__click, .acc_brands__list').hover(
               function () {
                   $('.acc_brands__list').fadeIn(1000);
               },
               function () {
                   $('.acc_brands__list').fadeOut(1000);
               }
       );

   });


(function ($) {
  var ajax = null;

  $(document).delegate('.topTabs a', 'click', function (event) {
    event.preventDefault();
    var href = ($(this).attr('href'));
    var n = $('.topTabs a').index(this);

    $('.topTabs a, .bottomTabs a').removeClass('current');

    $($('.topTabs a').get(n)).addClass('current');
    $($('.bottomTabs a').get(n)).addClass('current');

    if (ajax !== null && ajax.readyState != 4) {
      ajax.abort();
    }

    ajax = $.ajax({
      url: '/ajax.php',
      data: {
        action: 'get_tabs_content',
        info: this.id,
        pid: $('#tabs_product_id').val()
      },
      type: 'post',
      success: function (data) {
        $('.fContent').html(data);
      }
    });

  });

}(jQuery));


