
jQuery(function($) {
    
    

    $(".buy_button").click(function(e){
        e.preventDefault();
        form = $(this).parents("form:first");
        addOrderItem(form);
    });
    $(".buy_form").submit(function(e){
        e.preventDefault();
        form = $(this);
        addOrderItem(form);
    });
  
    cartTriggers();

});

function formPath(form){
  path   = form.attr("action").split("?");
  url    = path[0]+".json"
  lang   = path[1] ? "?"+path[1] : ""
  path   = url+lang
  return path
}

function addOrderItem(form){
    own_preloader(true); // Показываем прелоадер
    fields = form.serialize();
    path   = formPath(form);
    $.ajax({
        url:      path,
        type:     'post',
        data:     fields,
        dataType: 'json',
        success:  function(response) {
            own_preloader(false); // Убираем прелоадер
	    
	    $(".parse_items").empty();
	    var item_row = $('#order_item_js_template').html();
	    $.each(response.items, function(){
	      var item = this;
	      $(".parse_items").append(item_row);
	      var last_item_row = $(".parse_items .parse_item:last");
	      
	      parse_product_url = last_item_row.find('a.parse_product_url:first');
		parse_product_url.attr('href',item.product_url);
		parse_product_url.attr('title',item.title);
		parse_product_url.html(item.title);
	      parse_item_quantity = last_item_row.find('input.parse_item_quantity:first');
		parse_item_quantity.attr('name','cart[quantity]['+item.stock_item_id+']');
		parse_item_quantity.attr('id','cart_quantity_'+item.stock_item_id);
		parse_item_quantity.val(item.quantity);
	      parse_remove_action = last_item_row.find('a.parse_remove_action:first');
		parse_remove_action.attr('href',item.url);
		parse_remove_action.attr('id','delete_'+item.stock_item_id);
	      last_item_row.find('.parse_sale_price:first').html(item.sale_price+' '+response.currency);
	    });
	    $('.parse_cart .parse_total_price').html(response.total_price+' '+response.currency);
	    $('.basket_full').show();
	    $('.basket_empty').hide();
	    $("#cart .checkout_inactive").removeClass("checkout_inactive");
	    cartTriggers();
        },
        error:  function(response) { process_error(response) }
    });
}



function cartTriggers(){
  $(".parse_cart .parse_remove_action").each(function(i) {
        if ( $(this).attr('processed') ) { return; }
	$(this).attr('processed',true);
	
	$(this).click(function(e){
        e.preventDefault();
	var link = $(this);
	var item_row = link.parents(".parse_item:first");
	var fields =  new Object;
        fields['_method'] = 'delete';
	id = link.attr("id").replace("delete_","");
	var path   = '/cart_items/'+id+'.json';
	own_preloader(true); // Показываем прелоадер
	$.ajax({
	    url:      path,
	    type:     'post',
	    data:     fields,
	    dataType: 'json',
	    success:  function(response) {
		own_preloader(false); // Убираем прелоадер
		item_row.hide("normal", function(){ item_row.remove(); });
		
		$('.parse_cart .parse_total_price').html(response.total_price+' '+response.currency);
		if (response.items_count == 0) {
		  $("#cart .checkout").addClass("checkout_inactive");
		  $('.basket_full').hide();
		  $('.basket_empty').show();
		}
		
	    },
	    error:  function(response) { alert("произошла ошибка") }
	});
	return false;
	
    });
  });

    // Пересчитать
    $("input[@id^=cart_quantity]").each(function() {
        if ( $(this).attr('processed') ) { return; }
	$(this).attr('processed',true);
	$(this).bind("change keyup", function() {
	    val = $(this).val();
	    if (!isNaN(val) && val > 0){recalculate_order();}
	});
    });
    
    
    function recalculate_order() {
	  var fields =  new Object;
	  fields = $('#cartform').serialize();
	  var path   = $('#cartform').attr('action')+'.json';
	  
	  own_preloader(true); // Показываем прелоадер
	  $.ajax({
	      url:      path,
	      type:     'post',
	      data:     fields,
	      dataType: 'json',
	      success:  function(response) {
		  own_preloader(false); // Убираем прелоадер		
		  $(".js_cart_update").hide();
		  $('.parse_cart .parse_total_price').html(response.total_price+' '+response.currency);
	      },
	      error:  function(response) {  alert("произошла ошибка") }
	  });
    
    }

}







function changeCss(OBJ){
    var imageHeight = OBJ.height();
    var imageWidth = OBJ.width();
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    OBJ.css({
        "position" : "absolute",
        "left" : windowWidth / 2 - imageWidth / 2,
        "top" : getPageScroll()[1] + (getPageHeight() / 2)
    });
};


// getPageScroll() by quirksmode.com
function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
        xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
        yScroll = document.documentElement.scrollTop;
        xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
        xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
}

// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowHeight = document.body.clientHeight;
    }
    return windowHeight
}

function own_preloader(event){
    if (event==true) {
        if (!($("#own_preloader").attr("id"))){
            preloader='<div id="own_preloader" style="z-index:1000; width:32px; height:32px;"><img src="/images/loading.gif"/></div>';
            $("body").append(preloader);
        }
        preloader = $("#own_preloader");
        preloader.show();

        changeCss(preloader);
        $(window).bind("resize", function(){
            changeCss(preloader);
        });
        $(window).bind("scroll", function(){
            changeCss(preloader);
        });
    }
    else{
        $(window).unbind("resize");
        $(window).unbind("scroll");
        if (typeof(preloader) != 'undefined') preloader.hide();
    }
}