﻿jQuery.ajaxSetup({cache:false, dataType:"json"});

var alertTimeOut = 2000;

/**
 * Форматирует числа с разделением по разрядам
 */
function numberFormat(str) {
    return str.replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ');
}

/**
 * Переопределяем функцию alert
 */
function alert(text) {
    if(window.innerWidth){
        width = window.innerWidth;
        height = window.innerHeight;
    } else if(document.body && document.body.clientWidth){
        width = document.body.clientWidth;
        height = document.body.clientHeight;
    }
    //document.getElementById("dialog").style.top = "" + round((height - $("#dialog").width) / 2) + "px";
    //$("#dialog .text").html("" + round((height - $("#dialog").width) / 2) + "px");
    $("#dialog").css("margin-top", "" + Math.round((height - $("#dialog").height()) / 3) + "px");
    
    $("#dialog .text").html(text);
    $("#dialog").fadeIn('slow');
    setTimeout('$("#dialog").fadeOut("slow");', alertTimeOut);

}

function substr_replace (str, replace, start, length) {
	str = String(str);
	if (start < 0) start = start + str.length;
    length = length !== undefined ? length : str.length;
    if (length < 0) length = length + str.length - start;
    return str.slice(0, start) + replace.substr(0, length) + replace.slice(length) + str.slice(start + length);
}

function drawPrice(price){
	return price ? numberFormat(substr_replace(round(price * 100,1), ',', -2, 0)) : '0,00';
}

var Basket = {
	reload: function(){
		$.ajax({
			url: "/catalog",
			data: {basket:1},
			success:function(data){
				if(data == 'empty'){
					$("#basket").fadeOut(300);
				}else{
					$("#basket").html(numberFormat(data)).fadeIn(300);
				}
			},
			dataType: "html",
			type: "get"
		});
	}
};

function renderHeader(){
	if(jQuery(document).width() > 1400){
		jQuery("div.right-car").show();	
		jQuery("#central").removeClass('show');
	}else{
		jQuery("div.right-car").hide();	
		jQuery("#central").addClass('show');
	}
}

jQuery(window).resize(function(){
	renderHeader();
});

jQuery(function(){
	renderHeader();
	$("#basket").hide();
	Basket.reload();

	jQuery("a[rel^='prettyPhoto']").prettyPhoto({animationSpeed: 'normal',theme: 'facebook'});
	
	jQuery(".authorization a.in.superactive").bind("click", function(){
		if(jQuery(this).data("opened")){
			jQuery(".authorization .form-author").fadeOut(300);
			jQuery(this).data("opened", false);
		}else{
			jQuery(".authorization .form-author").fadeIn(300);
			jQuery(this).data("opened", true)
		}
		return false;
	});
	var about_opened_id = 0;
	jQuery(".content .catalogue-variants .icon a").bind("click", function(event){
		var id = jQuery(this).attr("rel");
		if(about_opened_id == id){
			jQuery("#about").hide();
			about_opened_id = 0;
		}else{
			about_opened_id = id;
			jQuery("#about div.open-window > div.inner").html(jQuery(this).parent().find("div.cont").html());
			jQuery("#about").css({left:(event.pageX+10)+"px",top:(event.pageY-jQuery("#about").height()/2+50)+"px"});
			jQuery("#about").addClass("opened").show();
		}
        return false;
    });
	
	jQuery(document).bind("click", function(event){
		if($(event.target).closest("#about").length < 1){
			jQuery("#about").hide();
			about_opened_id = 0;
		}
	});

	

$("#variant-catalogue").bind("change", function(){
	$(this).parent().submit();
});

$(".catalogue-list").collapsorz({
    minimum: 10, showText: "Развернуть список", hideText: "Свернуть список"
});

$(".content .add-basket a").bind("click", function(){
   
	if($(this).hasClass('opened')){
                var getAlso = false;
		var id = $(this).attr('rel');
		var amount = $(this).parent().children('input').val();
		if($(this).attr('amount') == 1){
			$.post('/catalog?cart', {id:id, amount:amount}, function(data){
				if(data.success){
					Basket.reload();
					alert(data.success);			
				}else{
					alert('Произошла ошибка');
				}
			});
		}else{
			if(confirm('К сожалению, данного товара нет в наличии. Хотите выбрать из товаров заменителей?')){
                                /*
				$.post('/catalog?getmore', {id:id, amount:amount});
				alert('Ваша заявка принята');
                                */
                               getAlso = true;
			}
		}
		
		$(".content .add-basket input").fadeOut(100);	
		$(".content .add-basket a").removeClass('opened');
                
                if (getAlso) {
                    flashAlso();
                    return true;
                }
		
	}else{
		$(".content .add-basket input").hide(100);		
		$(this).parent().children("input").show(100).focus();
		$(".content .add-basket a").removeClass('opened');
		$(this).addClass('opened');
	}
	
	return false;
});

$(".content .add-basket input").bind("change", function(){
	var amount = Number($(this).val());
	var packing = Number($(this).attr("rel"));
	if(amount < 1 || !amount) amount = 1;
	if(packing > 1){
		var rest = Math.floor(amount / packing);
		if(rest < 1) rest = 1;
		amount = packing * rest;
	}
	$(this).val(amount);
});

$(".content .add-basket input").bind("keydown", function(event){
	if(event.keyCode == 13) $(this).parent().children('a').click();
});

});
