$().ready(function() {

	/* Смета */

	function number_format( number, decimals, dec_point, thousands_sep ) {	// Format a number with grouped thousands
		//
		// +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +	 bugfix by: Michael White (http://crestidg.com)

		var i, j, kw, kd, km, minus = "";

		if(number < 0){
			minus = "-";
			number = number*-1;
		}

		// input sanitation & defaults
		if( isNaN(decimals = Math.abs(decimals)) ){
			decimals = 2;
		}
		if( dec_point == undefined ){
			dec_point = ",";
		}
		if( thousands_sep == undefined ){
			thousands_sep = ".";
		}

		i = parseInt(number = (+number || 0).toFixed(decimals)) + "";

		if( (j = i.length) > 3 ){
			j = j % 3;
		} else{
			j = 0;
		}

		km = (j ? i.substr(0, j) + thousands_sep : "");
		kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
		//kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
		kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");



		return minus + km + kw + kd;
	}

	/**
	 *
	 * @access public
	 * @return void
	 **/
	function countTotal() {
		var sum = Number(0);
		$(".ProjectSmetaInfo input:checked").each(function() {
			tv = $(this).attr("id").split("_");

			if ( $("#inp_"+tv[1]).length > 0 ) {
				thisprice = Number( $(this).attr("rel") ) * $("#inp_"+tv[1]).val();
			}
			else {
				thisprice = Number( $(this).attr("rel") )
			}

			sum = sum + thisprice;
		});
		$("#total span").html( number_format(sum, 0, ',', ' ') );
	}

	$(".ProjectSmetaInfo input:radio, .ProjectSmetaInfo :checkbox").click(function() {
		countTotal();
	});


	function recountT(inputID, tMax, tMin, tNew) {

		var t = $("#"+inputID);

		var tf = inputID.split("_");

		var b = $("#ttl_"+tf[1]);
		var opt = $("#opt_"+tf[1]);

		if (tMax == tNew) {
			t.parent("div").find(".q-plus").removeClass("q-plus-active").addClass("q-plus-unactive");
		}
		if (tMax > tNew) {
			t.parent("div").find(".q-plus").removeClass("q-plus-unactive").addClass("q-plus-active");
		}
		if (tMin < tNew) {
			t.parent("div").find(".q-minus").removeClass("q-minus-unactive").addClass("q-minus-active");
		}
		if (tMin == tNew) {
			t.parent("div").find(".q-minus").removeClass("q-minus-active").addClass("q-minus-unactive");
		}

		if (tNew <=1 ) {
			var tPaste = " ";
		}
		else {
			var tPrice = Number( tNew ) * Number( opt.attr("rel") );
			var tPaste = "= " + number_format( tPrice , 0, ',', ' ');
		}
		b.fadeOut(200, function() { $(this).html( tPaste ).fadeIn(300); });
		countTotal();
	}

	$(".ProjectSmetaInfo .qua-form input").change(function() {

		var t = $(this);
		var tmax = Number( t.attr("max") );
		var tmin = Number( t.attr("min") );
		var tnow = tnew = Number( t.val() );

		if ( tnow > tmax ) {
			alert("Максимум " + tmax + " шт.");
			t.val( tmax );
			var tnew = tmax;
		}
		if ( tnow < tmin ) {
			alert("Минимум " + tmin + " шт.");
			t.val( tmin );
			var tnew = tmin;
		}

		recountT( t.attr("id"), tmax, tmin, tnew );

	});

	$(".ProjectSmetaInfo .qua-form .q-plus, .ProjectSmetaInfo .qua-form .q-minus").click(function() {

		var t = $(this).parent("div").find("input");

		var tmax = Number( t.attr("max") );
		var tmin = Number( t.attr("min") );
		var tnow = Number( t.val() );

		if ( $(this).hasClass("q-plus") ) {
			if ( tnow >= tmax ) {
				return false;
			}
			var tnew = tnow + 1;
		}
		else {
			if ( tnow <= tmin ) {
				return false;
			}
			var tnew = tnow - 1;
		}

		t.val( tnew );

		recountT( t.attr("id"), tmax, tmin, tnew );

		return false;
	});

	$("#orderlink").click(function() {
		$(".orderSent").slideUp(300, function() { $(".orderForm").slideDown(300); });
		return false;
	});

	$("#sendlink").click(function() {
		ertotal = 0;


		if ($('#v2').val()=="") {
			$('.c2').css('color', 'red');
			$('#v2').css('background-color', '#FFD7D7');
			alert("Вы не указали ни одного контакта для связи с Вами.\nЭто необходимо сделать, иначе мы просто не сможем с Вами связаться.");
			ertotal = 1
		}
		else {
			$('.c2').css('color', 'black');
			$('#v2').css('background-color', '#fff');
		}


		if (ertotal==0) {
			var dt = $("#optionsOrder").serialize();
			$.post("/ajax/order.php", dt, function(data){
				if (data == 1) { $(".orderForm").slideUp(300, function() { $(".orderSent").slideDown(300); }); }
				else { alert("Отправка не удалась. Повторите попытку."); }
			}, "html");
		}

		return false;
	});

	function fadeCover(){ $(".cvv").hover( function(){ var link = $(this).find("a").attr("href"); $(this).append('<a href=\"'+link+'\" class=\"readMore\">Нажмите, чтобы узнать<br />подробнее о проекте</a>'); $(this).find(".readMore").fadeIn(300); }, function(){ $(this).find(".readMore").fadeOut(300).remove(); });}

	fadeCover();
/*
	$(window).resize(function () {

		console.log("Height: " + jQuery('.content').height() + "\nWidth: " + jQuery('.content').width()+"\nWidth windows: " + jQuery(window).width());

	});
*/

	$(".wannaT").click(function () {
		var wID = $(this).attr("id");
		$("#wanna").val(wID);
		$(".wannaT").removeClass("curpos");
		$(this).addClass("curpos");
	});

	$("#cform").submit(function () {
		if ($(this).find("#comment").val()=="") { $(this).find(".error").html("&mdash; опишите хотя бы несколькими словами качество нашей работы"); return false; }
        else { return true;}
	});
	$(".poster").hover(function(){ if ($(this).css("opacity")==1) { $(this).animate({opacity: 0.7}, "fast").animate({opacity: 1}, "fast"); } });
	$(".poster").click(function(){
		var photoid = $(this).attr('rel');
		var photoalt = $(this).find("img").attr('alt');
		$(".poster").css("opacity", 1);
		$(this).css("opacity", 0.5);
		$('#posterimg').animate({opacity: 0},500,function(){ $(this).attr({ src: '/i/projects/'+photoid+'.c.jpg', title: photoalt, alt: photoalt}).bind('load',function(){ $(this).parent("#posterlink").attr({ href: '/i/projects/'+photoid+'.d.jpg'}); $(this).animate({opacity: 1},500); });
		});
		return false;
	});
	if ($("#posterlink").length) {
		$("#posterlink").fancybox({
			'zoomSpeedIn'		:	500,
			'zoomSpeedOut'		:	500,
			'overlayOpacity'    :   0
		});
	}
	if ($(".usefancy").length) {
		$(".usefancy").fancybox({
			'zoomSpeedIn'		:	500,
			'zoomSpeedOut'		:	500,
			'overlayOpacity'    :   0
		});
	}
	if ($(".gr").length) {
		$(".gr").fancybox({
			'zoomSpeedIn'		:	500,
			'zoomSpeedOut'		:	500,
			'overlayOpacity'    :   0
		});
	}
	if ($("ul.tabs").length) {
		$("ul.tabs").delegate("li:not(.current)", "click", function() {
			$(this).addClass("current").siblings().removeClass("current").parents(".desc").find("div.box").hide().eq($(this).index()).show();
		});
	}
});

