var AjaxNS = {
	NiceNumber : function(v){
		return v.toString().replace(/(\d)(?=(\d\d\d)+([^\d]|$))/g, '$1 ');
	},
	Ru : {
		NNum : true,
		N : function(v,w1,w2,w5){
			v = v + '';
			var s = AjaxNS.Ru.NNum ? AjaxNS.NiceNumber(v) + ' ' : '';
			if(arguments.length == 2){
				w2 = w1[1];
				w5 = w1[2];
				w1 = w1[0];
			}
			v = v % 100;
			var o = v % 10;
			if((o >= 5 && o <= 9) || (o == 0) || (v >=10 && v <=20)){
				return s + w5;
			}
			else if(o == 1){
				return s + w1;
			}
			else{
				return s + w2
			}
		},
	},
	DownloadForms : function(secsToWait){
		var history = new function(){
			var a = [];

			this.add = function(form){
				a.push(getFormData(form));
			}

			this.clicked = function(form){
				var n = getFormData(form);
				for(var i in a){
					var o = a[i];
					if(n.t - o.t < secsToWait * 1000){
						if(n.cc == o.cc && n.sub == o.sub && o.mid == n.mid)
							return true
					}
				}
				return false;
			}

		}

		function getFormData(form){
			return {
				cc : form.find('input[name=cc]').val(),
				sub : form.find('input[name=sub]').val(),
				mid : form.find('input[name=mid]').val(),
				t : new Date					
			};
		}

		var forms = new function(){
			var a = {};
			this.add = function(form){
				var i = geti(form);
				if(!a[i]) a[i] = [];
				a[i].push(form);
			}

			function geti(form){
				var data = getFormData(form);
				return 'cc_'+data.cc+'sub_'+data.sub+'mid_'+data.mid;
			}

			this.click = function(form,dt){
				var o = a[geti(form)];
				for(var i in o){
					o[i].countupd(dt);
				}
			}
		};

		$('form.download').each(function(){
			var me = $(this),
				button = me.find('.dwnbtn'),
				eCount = me.find('.count'),
				lastDownload;

			me.countupd = eCountUpd;
			forms.add(me);

            button[0].onclick = function(){};

			button.click(function(e){
				e.preventDefault();
				if(history.clicked(me) || (lastDownload && (new Date - lastDownload) < secsToWait * 1000))
					return false;
				history.add(me);
				lastDownload = new Date;
				setTimeout(function(){forms.click(me,1)},1000);

                ga('send', 'event', 'Info', 'Download', 'Program Download');
				me.submit();
				return false;
			});

			function eCountUpd(dt){
				eCount.each(function(){
					var izb = $(this).is('.izb'),
						v = parseInt($(this).text().replace(/\s/g, ''))+dt;

					AjaxNS.Ru.NNum = false;
					$(this).parent().find('.befcount').html(AjaxNS.Ru.N(v, ['скачал','скачали','скачали']));
					$(this).html('<b>' + AjaxNS.NiceNumber(v) + '</b> ' + AjaxNS.Ru.N(v, izb ? ['избиратель','избирателя','избирателей'] : ['раз','раза','раз']));
					AjaxNS.Ru.NNum = true;
				});

				function fancyOutput(){

				}
			}


			eCountUpd(0);
		});
	}
}

$(window).load(function(){
	new AjaxNS.DownloadForms(5);
	$('p.setText').each(function(){
		$(this).html(text[$(this).attr('data-id')]);
	})
});
