// Функция обратного вызова для AddIntoCart
function callbackfunction_AddIntoCart(responseJS)
{
	// Результат принят
	sended_request = false;
	
	if (typeof responseJS != 'undefined')
	{
		//alert(responseJS.cart);
        // Данные.
		if (typeof responseJS.cart != 'undefined')
		{
			var little_cart = $('.cart');
			
			if (little_cart)
			{
				// Создадим скрытый SPAN для IE, в который поместим текст + скрипт.
				// Если перед <script> не будет текста, нехороший IE не увидит SCRIPT
				
				little_cart.replaceWith(responseJS.cart);
			}
			else
			{
				alert('Ошибка! Краткая корзина не найдена');
			}
		}
	}
}

function AddIntoCart(shop_path, item_id, item_count)
{
	//location.href = shop_path + 'cart/?ajax_add_item_id=' + item_id + '&count=' + item_count;
	cmsrequest = shop_path + 'cart/?ajax_add_item_id=' + item_id + '&count=' + item_count;
	
	// Отправляем запрос backend-у
	sendRequest(cmsrequest, 'get', callbackfunction_AddIntoCart);
	
	return false;
}

$(document).ready(function(){
    //Подготовительные действия для листалки в сайдбаре
    var $messagesCont = $('.messages');
    $messagesCont.data('currentItem', 0).data('items', $('.message-item', $messagesCont));
    $('.btn-prev', $messagesCont).click(function(){
        var items = $messagesCont.data("items");
        var currentItem = $messagesCont.data("currentItem");
        if(currentItem > 0){
            $(items.get(currentItem)).fadeOut("normal", function(){
                $(items.get(currentItem-1)).fadeIn("normal");       
            });
            $messagesCont.data("currentItem", currentItem-1);
        }
        return false;
    });
    $('.btn-next', $messagesCont).click(function(){
        var items = $messagesCont.data("items");
        var currentItem = $messagesCont.data("currentItem");
        if(currentItem < items.length-1){
            $(items.get(currentItem)).fadeOut("normal", function(){
                $(items.get(currentItem+1)).fadeIn("normal");       
            });
            $messagesCont.data("currentItem", currentItem+1);
        }
        return false;
    });
    
    //Подготовительные действия для раскрывающихся списков на главной странице
    $(".info-block li>a").click(function(event){        
        $('div:first', $(this).parents("li")).toggle('normal');
        event.stopPropagation();
        return false;
    });
    
    //Галерея 
  $(".catalog td").each(function(){
    $this = $(this);
    var price = $this.attr("title");
    var goodID = $this.attr("id");
    $('.gallery a', $this).lightBox({
      'imageBtnPrev': '/img/lightbox/lightbox-btn-prev.png',
  	  'imageBtnNext': '/img/lightbox/lightbox-btn-next.png',
  	  'imageBtnClose': '/img/lightbox/close-btn.png',
  	  'imageLoading': '/img/lightbox/lightbox-ico-loading.gif',
  	  'imageBlank': '/img/lightbox/lightbox-blank.gif',
      'price': price,
      'goodID': goodID
    });
  }); 
  
  $(".foto-block").each(function(){
    $this = $(this);
    var price = $this.attr("price");
    var goodID = $this.attr("id");
    $('.gallery', $this).lightBox({
      'imageBtnPrev': '/img/lightbox/lightbox-btn-prev.png',
  	  'imageBtnNext': '/img/lightbox/lightbox-btn-next.png',
  	  'imageBtnClose': '/img/lightbox/close-btn.png',
  	  'imageLoading': '/img/lightbox/lightbox-ico-loading.gif',
  	  'imageBlank': '/img/lightbox/lightbox-blank.gif',
      'price': price,
      'goodID': goodID
    });
  }); 
  
  //Кнопки увеличить-уменьшить количестов товара
  $(".button-up").click(function(){
    var container = $(this).parents("p");
    var input = $("input", container);
    var newValue = input.val()*1+1;
    input.val(newValue);
  });
  
  $(".button-down").click(function(){
    var container = $(this).parents("p");
    var input = $("input", container);
    var newValue = input.val()*1-1;
    input.val((newValue>=1) ? newValue : 1);
  });
  
  if (!($.browser.msie && $.browser.version == 6)) {
      $(".comment-top").corner("top 6px");
      $(".comment-bottom").corner("bottom 6px");   
      $(".opt-price-cont").corner("5px");
  }
  
  //Показ формы добавления комментария
  $(".add-comment").click(function(){
    $(".comment-form").slideDown('normal');
    return false;
  });
  
  //Функции и привязки для работы механизма выставления оценок
  function setRating(contID, value){
    $stars = $("#"+contID+" li");
    $stars.removeClass("star_on").addClass("star_off");
    for(index = 0; index < value; index++){
        $($stars[index]).addClass("star_on").removeClass("star_off");
    }
  }
  
  $("#stars_counter li").hover(function(){
    var value = $(this).attr("id").replace("star_","");
    setRating("stars_counter", value);
  }).click(function(){
    var value = $(this).attr("id").replace("star_","");
    setRating("stars_counter", value);
    $("#shop_comment_grade").val(value);
  });
  $("#stars_counter").mouseout(function(){
    var value = $("#shop_comment_grade").val();
    setRating("stars_counter", value);
  });
  
  /*Корзина*/
  
  //Действие для кнопки "Пересчитать"
  $("#recount").click(function(){
    $("#post_field").attr("name", "recount");
    $("#post_form").submit();
    return false;
  });
  
  //Действие выполняемое перед отпавкой формы
  $("#post_form").submit(function(){
    $this = $(this);
    $(".deleted", $this).val("0");
  });
  
  //Действие по удалению-добавлению товара в корзине
  $(".del-item a").click(function(){
    $this = $(this);
    if($this.html().indexOf("Удалить") != -1){            
        $this.html("<img src='/img/add-icon.gif' /><br />Восстановить");
    }else{
        $this.html("<img src='/img/del-icon.gif' /><br />Удалить");
    }
    $this.parent().toggleClass("del-item").toggleClass("add-item");
    $row = $this.parents("tr");
    $("input", $row).toggleClass("deleted");
    return false;
  });
  
  //Действие для кнопки "Оформить"
  $("#step_1").click(function(){
    $("#post_field").attr("name", "step_1");
    $("#post_form").submit();
    return false;
  });
  
  //Действие для кнопки "Назад" ведущей с начальной стадии
  $("#back-to-step0").click(function(){
    $("#post_form input[type='hidden']").removeAttr("name");
    //$("#post_field").attr("name", "returning");
    $("#post_form").submit();
    return false;
  });
  
  //Действие для кнопки "Далее" ведущей с заключительной стадии оформления заказа
  $("#step-2").click(function(){
    $("#post_form").submit();
    return false;
  });
  
  //Действие для кнопки "Назад" ведущей со страницы проверки данных
  $("#back-to-step1").click(function(){
    $("#post_form input[name='step_2']").attr("name", "step_1");
    $("#post_form").submit();
    return false;
  }); 
  
  //Действие для кнопки "Далее" ведущей с заключительной стадии оформления заказа
  $("#submit-order").click(function(){
    $("#post_form").submit();
    return false;
  });
  
  //Всплывающая подсказка для поля "комментарий" в корзине
  $("#comment-help, #beznal-help, .popup-help").betterTooltip({speed: 150, delay: 300});
  
  $(".opt-price-link").hover(function(){
    var td = $(this).parents("td")[0];
    $(".opt-price-cont", $(td)).show();
  }, function(){
    var td = $(this).parents("td")[0];
    $(".opt-price-cont", $(td)).hide();
  });
});
