dInclude("ajax.js");
dInclude("password.js");

var Market = function(caller){
    this.cartAction = "addCart";
    this.cartAction2 = "updateCart";
    this.cartAction3 = "changeCart";
    this.cartAction4 = "delCart";
    this.SwitchCatAction = "SwitchCat";

    this.cartrige="#cartrige";
    this.divCart = "#market_cart";
    this.miniCart = "#basket";
    this.ajax = new Ajax("module", "Market", "xx", caller);
}

Market.prototype.step3 = function(){
  if($('#step3').attr('rel')==0) alert ('Выберите способ оплаты');
  else{
    $("#b_step1").hide();
    $("#b_step2").show();
    if($('#step3').attr('rel')==2) beznal=true; else beznal=false;
  }
}

Market.prototype.step1 = function(form, mode){
	$(".er").hide();
	$(".er").html("");
    this.ajax.serializeForm(form);
    this.ajax.appendVar("mode", mode);
    if(beznal==false) this.ajax.appendVar("beznal", 1);
    return this.ajax.request("check",
        function(response){
            if (response == 1){
                $("#b_step2").hide();
                if(beznal==true) $("#b_step2b").show(); 
                else {
                  $("#uname2").html($("#uname").val());
                  $("#utel2").html($("#utel").val());
                  $("#uadress2").html($("#uadress").val());
                  $("#umail2").html($("#umail").val());
                  $("#udinf2").html($("#udinf").val());
                  $("#b_step3").show();
                  $('#small_cart').html('<a href="/cart/">В вашей корзине</a><span>Товаров: <big>0 шт.</big></span><span>На сумму: <big>0 руб.</big></span>');
                }
            }
            else {
                var tmp = $.evalJSON(response);
				$("#"+tmp.name+"_id").html(tmp.message);
				$("#"+tmp.name+"_id").show();
            }
            marketInit();
        }
    );    
}

Market.prototype.step2 = function(form){
    this.ajax.serializeForm(form);
    return this.ajax.request("step2",
        function(response){
            if (response){
                  var tmp = $.evalJSON(response);
                  // если форма заполнена, выводим сообщение о формировании заказа
                  if (tmp.zakaz){ 
                    $("#b_step3").show();
                    $('#small_cart').html('<a href="/cart/">В вашей корзине</a><span>Товаров: <big>0 шт.</big></span><span>На сумму: <big>0 руб.</big></span>');
                  }
            }
            marketInit();
        }
    );
}

Market.prototype.step4 = function(){
    return this.ajax.request("step3",
        function(response){
            if (response){
              location=response;
            }
            marketInit();
        }
    );
}

Market.prototype.newZakaz = function(form, mode){
    this.ajax.serializeForm(form);
    this.ajax.appendVar("mode", mode);

    return Market.ajax.request("newZakaz",
        function(response){
            if (response == 1){
                 alert('Заказ сформирован и отправлен!');
            }
            else {
                alert("Ошибка");
            }
        }
    );
}

Market.prototype.updateCaptcha = function(captcha, mode){
    this.ajax.appendVar("mode", mode);

    return this.ajax.request("update",
        function(response){
            $(captcha).attr("src",response);
            marketInit();
        }
    );
}

Market.prototype.addCart = function(idtov, count, color){
	$('#cscol').hide();
    if (!count){
        count = 1;
    }
	//alert(idtov);
	//alert(count);
	//alert(color);
    this.ajax.appendVar("idTov", idtov);
    this.ajax.appendVar("count", count);
    this.ajax.appendVar("color", color);
    var market = this;
    if ((!color)||(color==null)){
		//alert("4");
		var resultcolor = market.ajax.request('getColor', function(resultcolor){
			//alert("3");
			if(resultcolor==false){
				//alert("2 часть");
				market.ajax.request(market.cartAction2, function(result){
					$('#small_cart').html(result);
					if(document.getElementById('itemCount')){
						$('#itemCount').val('');
						$('#itemCount').html('');
					}
					var scrollTopOffset = document.documentElement.scrollTop; // Если страница прокручена, учитываем сдвиг
					if (scrollTopOffset == 0) scrollTopOffset = document.body.scrollTop; // Обходим унылый баг Chrome (http://code.google.com/p/chromium/issues/detail?id=2891)
					var topPosTemp = ($(window).height() / 2) - 114; // Высчитываем промежуточное значение
					if (topPosTemp < 0) topPosTemp = 0; // Если, ВНЕЗАПНО, попап оказался больше экрана - жестко прибиваем его к верху экрана
					var topPos = topPosTemp + scrollTopOffset; // Суммируем все данные
					$('#msgcol').css({'top':topPos+'px'}); // Собственно, задаём позицию
					$('#msgcol').hide();
					$('#msgcol').show();
					setTimeout('$("#msgcol").hide()', 1500);
				});
			}else{
				//alert("1 часть");
				if(resultcolor.indexOf("reler") != -1){
					market.addCart(idtov, count, parseInt(resultcolor.substring(resultcolor.indexOf("reler")+7,resultcolor.indexOf('">'))));
				}else{
					$('#resCol').html(resultcolor);
					$('#addToCart').attr('rel',idtov);
					$('#cscol').show();
					return;
				}
			}
		});
    }else{
		//alert("5");
		result = market.ajax.request(this.cartAction, function(result){
			market.ajax.request(market.cartAction2, function(result){
				$('#small_cart').html(result);
				if(document.getElementById('itemCount')){
					$('#itemCount').val('');
					$('#itemCount').html('');
				}
				var scrollTopOffset = document.documentElement.scrollTop; // Если страница прокручена, учитываем сдвиг
				if (scrollTopOffset == 0) scrollTopOffset = document.body.scrollTop; // Обходим унылый баг Chrome (http://code.google.com/p/chromium/issues/detail?id=2891)
				var topPosTemp = ($(window).height() / 2) - 114; // Высчитываем промежуточное значение
				if (topPosTemp < 0) topPosTemp = 0; // Если, ВНЕЗАПНО, попап оказался больше экрана - жестко прибиваем его к верху экрана
				var topPos = topPosTemp + scrollTopOffset; // Суммируем все данные
				$('#msgcol').css({'top':topPos+'px'}); // Собственно, задаём позицию
				$('#msgcol').hide();
				$('#msgcol').show();
				setTimeout('$("#msgcol").hide()', 1500);
			});
      });
      $('#addToCart').removeAttr('color');
	  $('.addToCart').removeAttr('color');
    }
}

Market.prototype.SwitchCat = function(idcat){
    this.ajax.appendVar("idcat", idcat);
    var market = this;
    var result = this.ajax.request(this.SwitchCatAction, function(result){
       // alert(result);
    $(market.cartrige).html(result);
    });
}


Market.prototype.changeCart = function(itemId, countItems){
    countItems = parseInt(countItems);
    if (!countItems) {
        countItems=0;
    }

    $("#cs"+itemId).val(countItems);
    $("#cs"+itemId).focus();

    this.ajax.appendVar("itemId", itemId);
    this.ajax.appendVar("countItems", countItems);
    var market = this;

    var result = this.ajax.request(this.cartAction3, function(result){
        var starsumm = $("#sum" + itemId).html(); 
        var itog = $("#itog").html();
        var newsumm = Math.floor($("#pr" + itemId).html()*countItems);
        $("#sum" + itemId).html(newsumm);

        var newitog = itog-starsumm+newsumm;
        $("#itog").html(newitog);
	if (newitog == 0){
	  $("#marketCart").html('<p class=\'notify\' style=\'text-align:center;\'>Ваша корзина пуста.</p>');
	}
	$('#small_cart').html(result);
    });
}

Market.prototype.delCart = function(idtov){

    this.ajax.appendVar("idTov", idtov);
    var market = this;

    var starsumm=$("#sum"+idtov).html();
    var itog=$("#itog").html();
    var newitog=Math.floor(itog-starsumm);
    $("#itog").html(newitog);
    $("#cs"+idtov).val("0");
    $("#tr"+idtov).attr("style", "display:none;");

    var result = this.ajax.request(this.cartAction4, function(result){
        $('#small_cart').html(result);
    });
    if (newitog == 0){
	$("#marketCart").html('<p class=\'notify\' style=\'text-align:center;\'>Ваша корзина пуста.</p>');
    }
}

Market.prototype.clearCart = function(idtov){
    var market = this;

    var result = this.ajax.request("clearCart", function(result){
        str="<p class='notify' style='text-align:center;'>Ваша корзина пуста.</p>";
        $("#marketCart").html(str);
        $('#small_cart').html(result);
    });

}

Market.prototype.search = function(input){
    this.ajax.appendVar("search", input);
    var result = this.ajax.request("search", function(result){
        document.location.href = "/search/";
    });

}

// Функция определения абсолютных координат элемента (относительно body)
function absPosition(obj) {
	var x = y = 0;
	while(obj) {
		x += obj.offsetLeft;
		y += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return {x:x, y:y};
}

function marketInit(){
    $("#clearCart").unbind();
    $("#clearCart").click(function(){
        var cat = new Market(this);
        cat.clearCart();
    });

    $(".addToCart").unbind();
    $(".addToCart").click(function(){
        var count = $(this).parent().find("input[name=itemCount]").val();
        var cat = new Market(this);
        cat.addCart($(this).attr("rel"), count, $(this).attr("color"));
	});
	
	$(".addToCartWithColor").unbind();
    $(".addToCartWithColor").click(function(){
        var count = $(this).parent().find("input[name=itemCount]").val();
        var cat = new Market(this);
        cat.addCart($(".addToCart").attr("rel"), count, $(".addToCart").attr("color"));
	});


    $(".part_swt a").unbind();
    $(".part_swt a").click(function(){
        var cat = new Market(this);
        cat.SwitchCat($(this).attr("rel"));

	});

/*    $(".left").unbind();
    $(".left").click(function(){
        var cat = new Market(this);
        cat.SwitchCat($(this).attr("rel"));

	});*/

    $(".cnt_f").unbind();
    $(".cnt_f").keyup(function(){
        var cat = new Market(this);
        cat.changeCart($(this).attr("rel"),$(this).val());
    });

    $(".deltov").unbind();
    $(".deltov").click(function(){
        var cat = new Market(this);
        cat.delCart($(this).attr("rel"));
    });

    $("#closeMainCart").click(function(){
        $("#divMainCart").attr("style", "display:none;");
    });

    $("#captcha_market").unbind();
    $("#captcha_market").click(function(){
        $(this).unbind();
        var cat = new Market(this);
        cat.updateCaptcha("#captcha_market", "858585");
    });

    $("#step1").unbind();
    $("#step1").click(function(){
        var cat = new Market(this);
        cat.step1("#userform", "1");
    });

    $("#step2").unbind();
    $("#step2").click(function(){
        var cat = new Market(this);
        cat.step2("#userform");
    });

    $("#step3").unbind();
    $("#step3").click(function(){
        var cat = new Market(this);
        cat.step3();
    });

    $("#step4").unbind();
    $("#step4").click(function(){
        var cat = new Market(this);
        cat.step4();
    });

    $("a[class*=b_step]").unbind();
    $("a[class*=b_step]").click(function(){
        var name = $(this).attr("class");
        $(".steps").hide();
        $("#"+name).show();
    });

    $(".btn_make_order").unbind();
    $(".btn_make_order").click(function(){
        document.location.href = "/order/";
    });
    
    $("#searchbut").unbind();
    $("#searchbut").click(function(){
        var cat = new Market(this);
        cat.search($("#search").val());
    });

    $("#search").keypress(function(e){
        if(e.which == 13){
            var cat = new Market(this);
            cat.search($(this).val());
        }
    });
}


$(document).ready(function(){
    marketInit();
});
