var gosloto_game, gosloto_multi;

$(document).ready(function() {
	var jOneCoupon = $('#one_coupon'),
		jMultiCoupons = $('#multi_coupons'),
		jSwitcher =  $('.switcher .pseudo_link');
	
	if( $.browser.msie ){
		if (!document.namespaces['v']) {
			document.namespaces.add('v', 'urn:schemas-microsoft-com:vml');
			document.namespaces.add('o', 'urn:schemas-microsoft-com:office:office');
		}
		var ss = document.createStyleSheet();
		ss.cssText = 'v\\:arc, v\\:curve, v\\:extrusion, v\\:fill, v\\:formulas, v\\:group, v\\:handles, v\\:image, v\\:imagedata, v\\:line, v\\:oval, v\\:path, v\\:polyline, v\\:rect, v\\:roundrect, v\\:shadow, v\\:shape, v\\:shapetype, v\\:stroke, v\\:textbox, v\\:textpath, v\\:vmlframe {behavior:url(#default#VML);display:inline-block;} o\\:callout, o\\:locks, o\\:skew {behavior:url(#default#VML);}';
	}
	
	if(!$.browser.msie && !$.browser.opera) {
		jOneCoupon.addClass('rc14');
		jMultiCoupons.addClass('rc14');
	}

	gosloto_game = new (function(){
		var it = this;

		this.total_sum_is_updated = function(total_sum)
		{
		}
			
		/*
		 *	Определяем браузер для использования VML и Canvas
		 */
		var isLocked = 0;

		/*
		 *	Класс для создания кастомного селекта
		 *	@param {JQueryElement} element Элемент в который будет добавлен новый селект
		 *	@param {DomElement}	select Браузерный select который будет превращен в кастомный
		 *	@param {Function} [onChange] Событие изменения значения селекта
		 */
		window.SelectPopup = function( element, select, onChange ){
			var that = this;
			this.onChange = onChange ? onChange : 0;
			var popup = document.createElement('DIV');
			popup.className = 'select_popup';
			this.popup = popup = $(popup);
			this.parent = element;
			var content = '<div>';
			for(var i = 0; i < select.options.length; i++){
				content += '<span class="pseudo_link">' + select.options[i].text + '</span>';
			}
			content += '</div>';

			popup.html(content);
			popup.find('span').click(
				function(){
					that.select.options[$(this).prevAll('span').length].selected = true;
					that.link.html( that.select.options[that.select.selectedIndex].text );
					popup.hide();
					if( onChange )
						onChange( that.select );
				}
			);
			$(document.body).click(
				function(){
					popup.hide();
				}
			);
			popup.hide();
			element.append(popup);
		};
		window.SelectPopup.prototype = {
			addLink:function( popup, select ){
				select.style.display = 'none';
				var link = document.createElement('span');
				link.className = 'pseudo_link';
				$(window).load(
					function(){
						link.innerHTML = select.options[select.selectedIndex].text;
						if( popup.onChange )
							popup.onChange( select );
					}
				);
				select.parentNode.insertBefore(link, select);

				$(link).click(
					function(){
						$(popup.popup.find('span').removeClass('selected')[select.selectedIndex]).addClass('selected');
						popup.popup.show();
						var offset = $(this).offset(),
						offsetParent = popup.parent.offset(),
						offsetPopup = popup.popup.offset(),
						offsetLink = $(popup.popup.find('span')[select.selectedIndex]).offset();
						popup.popup.css('top', offset.top - offsetParent.top - offsetLink.top + offsetPopup.top).css('left', 1 + offset.left - offsetParent.left - offsetLink.left + offsetPopup.left);
						popup.select = select;
						popup.link = $(link);
						return false;
					}
				);
			}
		};


		/*
		 *	Класс игры
		 *	@param {Object} params Параметры игры
		 */
		window.Game = function( params ){
			var self = $(this), fields = $('#ticket > li'), selectedFields = [], tickets = [], numbers = [], not_auto_fields = [], auto_fields = [],
			hiddenFields = $('#hidden_fields'), firstElement = $('#ticket_chooser .scroller'), auto = $('#auto');
			var numbersCounter = 0, couponsCounter = 0, fieldsCounter = 0, globalFieldsCounter = 0, currentCoupon = 1, currentField = 1, summary = 0, all_combinations = 0, currentCirculation = 1;
			var error_block = $('<div id="error_block" class="hide"><span class="icon"/><p/></div>').insertAfter($('#clear_form'));
			var multi_error_block = $('#error_block_multi');
			
			$('#free').css('opacity',0.5);

			this.setCurrentField = function(coupon_field_number)
			{
				currentField = coupon_field_number;
			};
			
			this.setNumbersCounter = function(count)
			{
				numbersCounter = count;
			};
			
			function prepareNumber( iRoundBase ){
				if( iRoundBase < 10000 )
					return iRoundBase;

				return iRoundBase.nice();
			};
			
			/**
			 * Заполняет отмеченные числа из билета
			 */
			this.fill_in = function()
			{
				var ticket = window.ticket;

				if (typeof(ticket) === "undefined" || typeof(ticket.combinations) === "undefined")
					return false;
				
				//var the_game = window.gosloto_game.game;
				var the_game = this;
				
				var selected_number_values = jQuery('#hidden_fields');
				
				var drawSelect = $("#draw_selector select");
				if (drawSelect.length > 0)
				{
		    		drawSelect.val(ticket.draws);
		    		drawSelect.trigger('change');
				}
				
				var first_checked_coupon = 0;
				for (var int = 1; int <= ticket.combinations.length; int++) {
					first_checked_coupon = int;
					if (typeof(ticket.combinations[int]) !== "undefined") {
						break;
					}
				}
				
				self.trigger("changefield", first_checked_coupon);
				
				var coupon_field = 6;
				while (coupon_field >= first_checked_coupon)
				{
					the_game.setCurrentField(coupon_field);
					the_game.setNumbersCounter(0);

				    jQuery.each(fields.find("input"), function(i, input)
		           	{
		    			input.checked = false;
		           	});
				    
					if (typeof(ticket.combinations[coupon_field]) !== "undefined")
					{
		        		jQuery.each(ticket.combinations[coupon_field], function(i, number)
		        		{
							the_game.draw_field_map(coupon_field, number);
													
							if (coupon_field > first_checked_coupon)
							{
								selected_number_values.append('<input type="hidden" name="digit[' + coupon_field + '][' + number + ']" class="field' + coupon_field + '" title="' + (number - 1) + '"/>');
		    				
								fields.find("input").get(number - 1).checked = true;
							}
							else 
								$($('#ticket li').get(number - 1)).find('label').click();
		        		});

						if (coupon_field > first_checked_coupon)
							$(the_game).trigger("numbers", ticket.combinations[coupon_field].length);

						if (coupon_field == first_checked_coupon)
							the_game.setNumbersCounter(ticket.combinations[coupon_field].length);
						else
							the_game.setNumbersCounter(0);
					}

					coupon_field--;
				}
				
				return true;
			};
			
			/**
			 * Сбрасывает select "Тиражей:" в предыдущее правильное значение
			 */
			function reset_draw_select() {
				var drawSelect = $("#draw_selector select");
				drawSelect.val(drawSelect.data('original-value'));
			}

			/**
			 * Показывает ошибку выбора чисел
			 */
			function show_numbers_error(text) {
				error_block.removeClass('hide').find('p').text(text);
			}
			
			/**
			 * Показывает ошибку выбора чисел
			 */
			function no_numbers_errors() {
				error_block.addClass('hide');
			}
			
			function show_multi_coupons_error(text){
				multi_error_block.removeClass('hide').find('p').text(text);
			}
			
			function no_multi_coupons_errors() {
				multi_error_block.addClass('hide');
			}
			
			function initCoupon( index, element, isMakeClone ){

				// при выборе количества тиражей
				var drawSelect = $("#draw_selector select");
				
				// хранение предыдущего значения
		        drawSelect.data('original-value', drawSelect.val());
				
				drawSelect.change(function(){
					var select = $(this);
					var draw = select.val();
					// изменение количества выбранных номеров (ничего не отмечали и не разотмечали)
					numbers = 0;
			        
		            if (validate_total_sum(draw)) {
						select.data('original-value', draw);
						// запускается перерасчёт суммы
						self.trigger('numbers', numbers);
		            }
		            else {
		            	// reset the select field to its previous value
		            	reset_draw_select();
		            }
				});

				var result = new Game.Coupon( $(element).find('img')[0] );
				result.container.find('b').each(
					function( field ){
						$(this).click(
							function(){
								if( !isLocked && (index == 0 || index <= couponsCounter) ){
									isLocked = 1;
									self.trigger("changecoupon", [index + 1, field + 1]);
								}
							}
						);
					}
				);
				result.container.find('select').each(
					function(){
						if( !window.Game.popup ){
							window.Game.popup = new window.SelectPopup( $('#ticket_chooser'), this,
								function( select ){
									$(select).next().html( select.selectedIndex > 0 ? params.words[1] : params.words[0] );
								}
							);
							window.Game.popup.popup.find('div').addClass('rc10 rc-shape');
						}
						window.Game.popup.addLink(window.Game.popup, this);
					}
				);
				return result;
			}

			function combination(b, a){
				var result = 1;
				for(var i = 0; i <= b - 1; i++){
					result *= ( (a - i) / (b - i) );
				}
				return Math.round(result);
			}

			/*
			 *  Возвращает количество комбинаций
			 *  @param {Integer} numbersCount Количество отмеченных номеров
			 */
			function getCombinations( numbersCount ){
				var
					result = 0,
					i,
					numbers = hiddenFields.find('input'),
					field = 0,
					buffer,
					counter = 0;

				for(i = 0; i < numbers.length; i++){
					buffer = parseInt(numbers[i].className.replace('field', ''));
					if( buffer != field ){
						field = buffer;
						if( counter >= params.minNumbers ){
							result += combination( params.minNumbers, counter );
						}
						counter = 0;
					}
					counter++;
				}
				
				if( counter >= params.minNumbers ){
					result += combination( params.minNumbers, counter );
				}
				
				if( numbersCount + 1 >= params.minNumbers ){
					result += combination( params.minNumbers, numbersCount );
				}

				return result;
			}

			/*
			 *	Обработка события изменения поля
			 */
			self.bind('changefield',
				function( event, field, oldCoupon ){
					if( !oldCoupon )
						oldCoupon = currentCoupon;

					var i, inputs = fields.find('input'), fieldNumber = (oldCoupon - 1 ) * 6 + currentField;

					for(i = 0; i < inputs.length; i++)
					{
						if( inputs[i].checked )
							hiddenFields.append('<input type="hidden" name="' + params.format.replace('{%field}', fieldNumber).replace('{%number}', i + 1) + '" class="field' + fieldNumber + '" title="' + i + '" />');
						
						inputs[i].name = params.format.replace('{%field}', (currentCoupon - 1 ) * 6 + field).replace('{%number}', i + 1);
//							inputs[i].name = params.format.replace('{%field}', field).replace('{%number}', i + 1);
					}

					fields.filter('.selected').removeClass('selected').find('input').each(
						function(){
							this.checked = false;
						}
					);

					inputs = hiddenFields.find('.field' + ((currentCoupon - 1 ) * 6 + field));

					numbersCounter = 0;
					for(i = 0; i < inputs.length; i++){
						fields.eq(inputs[i].title).addClass('selected').find('input')[0].checked = true;
						inputs[i].parentNode.removeChild(inputs[i]);
						numbersCounter++;
					}

					self.trigger("numbers", 0);
				}
			);

			/*
			 *	Добавляем галочку, если заполнено достаточно полей
			 */
			self.bind('field', function( event, numbers ){
				if( numbers > 0 ){
					$(tickets[currentCoupon].container.find('b')[currentField - 1]).addClass('fill');
				}

				if( numbers < 0 ){
					$(tickets[currentCoupon].container.find('b')[currentField - 1]).removeClass('fill');
				}
			});

			/**
			 * Вызывается при обновлении итоговой суммы
			 */
			function total_sum_is_updated(total_sum)
			{
				it.total_sum_is_updated(total_sum);
			}

			/**
			 * Проверить общую сумму
			 */
			function validate_total_sum(multiplier) {
				if (!multiplier)
					multiplier = $("#draw_selector select").val();
				
				if (!multiplier)
					multiplier = 1;
				
				var total_sum = getCombinations( numbersCounter + numbers ) * params.price * multiplier;
				
				if( total_sum <= params.maxSum ){
					total_sum_is_updated(total_sum);
					return true;
				}
				else {
					show_numbers_error(params.errors.coupon);
					return false;
				}
			}
			
			// очистка данного поля
			function clear_field(field){
				remove_element(field, not_auto_fields);
				remove_element(field, auto_fields);
				
				if(not_auto_fields.length == 0 && auto_fields.length == 0) auto.val('false');
				if(not_auto_fields.length > 0) auto.val('false');
				if(not_auto_fields.length == 0 && auto_fields.length > 0) auto.val('true');
			}
			
			// удаляем элемент из массива
			function remove_element(field, array){
				for(var i = 0; i < array.length; i++){
					if(field == array[i]){
						array.splice(i, 1);
						return;
					}
				}
			}
			
			// Если купон заполняется не автоматически (выполн. при клике на цифру поля или очистить)
			function fill_in_not_auto(field){
				for(var i = 0; i < not_auto_fields.length; i++){
					// Если элемент уже заполнен автоматически
					if(field == not_auto_fields[i]){
						return;
					}
				}
				// Удаляем автом. поле больше не автом. поле
				remove_element(field, auto_fields);

				not_auto_fields.push(field);
				not_auto_fields.sort();
				if(auto.val() != 'false') auto.val('false');
			}
			
			/* Если поле заполняется автоматически (выполн. при клике на Автоматич. и Отметить все) */
			function fill_in_auto(field){
				// Смотрим есть поле в не автом. заполненных
				remove_element(field, not_auto_fields);
				
				not_auto_fields.sort();
				auto_fields.push(field);
				auto_fields.sort();
				
				// если нет полей заполненных не автом. ставим индикатор auto = true
				if(not_auto_fields.length == 0 && auto_fields.length > 0) auto.val('true');
			}
			
			/*
			 *  Элемент выбирания номеров
			 */
			fields.find('label').click(
				function() {
					if( isLocked )
						return false;
					
					if (numbersCounter >= params.maxSelectNumbers && !$(this).parent().hasClass('selected')) {
						error_block.removeClass('hide').find('p').text(params.errors.field);
						return false;
					}

					var parent = $(this).parent();
					var isSelected = !parent.hasClass('selected');

					if( isSelected ){
						// изменение количества выбранных номеров
						numbers = 1;
						
						if (validate_total_sum()) {
							parent.addClass('selected');
							self.trigger("numbers", [1, parseInt($(this).html())]);
							parent.find('input')[0].checked = isSelected;
							no_numbers_errors();
						}
					}
					else {
						// изменение количества выбранных номеров
						numbers = -1;
						
						parent.removeClass('selected');
						self.trigger("numbers", [-1, parseInt($(this).html())]);
						parent.find('input')[0].checked = isSelected;
						no_numbers_errors();
					}
					fill_in_not_auto(currentField);
					
					return false;
				}
			);

			/*
			 *  Счетчик выбранных номеров
			 *  ("Отмечено номеров")
			 */
			$('#select_numbers').each(
				function(){
					var element = $(this).show();
					element = element.find('i');

					self.bind('numbers', function( event, numbers ){
						element.html( numbers == 0 ? numbersCounter : (numbersCounter + numbers) );
					});
				}
			);

			/*
			 *	Счетчики купонов, полей и комбинаций
			 * (на 18.02.2011 - может быть только один купон; несколько купонов - убрали)
			 */
			$('#counters').each(
				function(){
					var element = $(this),
					coupons = element.find('.coupon i'),
					fields = element.find('.fields i'),
					combinations = element.find('.combinations i');
					
					self.bind('numbers', function( event, numbers ){
						if( numbers == 0 ){
							//return;
						}

						if( numbersCounter >= params.minNumbers && numbersCounter + numbers < params.minNumbers ){
							self.trigger("field", [-1]);
						}

						if( numbersCounter < params.minNumbers && numbersCounter + numbers >= params.minNumbers ){
							self.trigger("field", [1]);
						}

						if( couponsCounter > 0 ){
							var c = getCombinations( numbersCounter + numbers );
							self.trigger("combinations", c);
							combinations.html( prepareNumber(c) );
						}
						else {
							self.trigger("combinations", 0);
						}

						numbersCounter += numbers;
					});

					self.bind('field', function( event, numbers ){
						if( fieldsCounter == 0 && fieldsCounter + numbers > 0 ){
							self.trigger("coupon", [1]);
						}

						if( fieldsCounter > 0 && fieldsCounter + numbers <= 0 ){
							self.trigger("coupon", [-1]);
						}

						fieldsCounter += numbers;
						globalFieldsCounter += numbers;
						fields.html( globalFieldsCounter );
					});

					self.bind('coupon', function( event, numbers ){
						if( couponsCounter == 0 && numbers > 0 ){
							element.css('visibility', 'visible');
						}
						
						couponsCounter += numbers;
						if( couponsCounter == 0 ){
							element.css('visibility', 'hidden');
						}
						coupons.html( couponsCounter );
					});
				}
			);

			/*
			 *	Счетчик стоимости поля
			 */

			$('#field_price').each(
				function(){
					var element = $(this).show();
					element = element.find('i');

					self.bind('numbers', function( event, numbers ){
						numbers = numbersCounter;

						if( numbers >= params.minNumbers )
							element.html( prepareNumber(combination(params.minNumbers, numbers) * params.price) );
						else
							element.html(0);
					});
				}
			);

			/*
			 *	Элемент подсчета общей стоимости билетов
			 */
			$('#full_price').each(
				function(){
					var that = $(this).find('i');
					self.bind('combinations', function( event, combinations ){
						all_combinations = combinations;
						summary = combinations * params.price;
											
						// количество тиражей
		                var gameNumber = 1;
		                var draw = $("#draw_selector select");
		                
		                if(draw.length)
		                    gameNumber = parseInt(draw.val());
		                if (gameNumber < 1)
		                    gameNumber = 1;
		                   
		                if (validate_total_sum(gameNumber)) {
		                	that.html( prepareNumber(gameNumber*summary) );
		                	no_numbers_errors();
		                }
					});
				}
			);

			/*
			 *  Элемент изменения купонов
			 */
			$('#chooser_prev').each(
				function(){
					var that = $(this).addClass('disabled');

					self.bind('changecoupon',
						function( event, newCouponIndex ){
							if( newCouponIndex > 1 )
								that.removeClass('disabled');
							else
								that.addClass('disabled');
						}
					);

					that.click(
						function(){
							if( isLocked || that.hasClass('disabled') )
								return false;

							self.trigger("changecoupon", [currentCoupon - 1, (selectedFields[currentCoupon - 1] ? selectedFields[currentCoupon - 1] : 1) ]);
						}
					);
				}
			);

			$('#chooser_next').each(
				function(){
					var that = $(this).addClass('disabled');

					self.bind('coupon',
						function( event, numbers ){
							if( couponsCounter < currentCoupon )
								that.addClass('disabled');
							else
								that.removeClass('disabled');
						}
					);

					self.bind('changecoupon',
						function( event, newCouponIndex ){
							if( couponsCounter < newCouponIndex )
								that.addClass('disabled');
							else
								that.removeClass('disabled');
						}
					);

					that.click(
						function(){
							if( isLocked || that.hasClass('disabled') )
								return false;

							self.trigger("changecoupon", [currentCoupon + 1, (selectedFields[currentCoupon + 1] ? selectedFields[currentCoupon + 1] : 1)]);
						}
					);
				}
			);

			/*
			 *  Кнопка "Сыграть"
			 */
			$('#play_button').each(
				function(){
					var that = $(this).addClass('disabled');

					self.bind('coupon',
						function( event, numbers ){
							if( couponsCounter == 0 ){
								that.addClass('disabled');
							}
							else {
								that.removeClass('disabled');
						}
					});

					that.find('input').click(
						function(){
							if( isLocked || that.hasClass('disabled') )
								return false;
						}
					);
				}
			);

			/*
			 *  Элемент перехода на следующее поле/купон
			 */
			$('#next_ticket').each(
				function(){
					var that = $(this),
						jInformation = $('#information'); 
					that.show().find('span:last').hide();
					self.bind('coupon',
						function( event, numbers ){
							if( currentField == 6 ){
								if( currentCoupon <= couponsCounter ){
									that.hide();
									//that.show().find('span').hide().filter(':last').show();
								}
								else {
									that.hide();
								}
								jInformation.addClass('correction');
							}
							else {
								that.show().find('span').hide().filter(':first').show();
								jInformation.removeClass('correction');
							}
						}
					);
					self.bind('changefield',
						function( event, field ){
							if( field == 6 ){
								if( currentCoupon <= couponsCounter ){
									that.hide();
									
									//that.show().find('span').hide().filter(':last').show();
								}
								else {
									that.hide();
								}
								jInformation.addClass('correction');
							}
							else {
								that.show().find('span').hide().filter(':first').show();
								jInformation.removeClass('correction');
							}

							if( getCombinations( numbersCounter+1 ) * params.price > params.maxSum ){
								error_block.removeClass('hide').find('p').text(params.errors.coupon);
							} else {
								error_block.addClass('hide');
							}
						}
					);
					that.click(
						function(){
							if( isLocked )
								return false;

							isLocked = 1;
							if( currentField < 6 )
								self.trigger("changefield", currentField + 1);
							else
								self.trigger("changecoupon", [currentCoupon + 1, 1]);
						}
					);
				}
			);

			/*
			 *
			 */
			$('#coupon_number').each(
				function(){
					var that = $(this).find('i');
					self.bind('changecoupon',
						function( event, newCouponIndex ){
							that.html(newCouponIndex);
						}
					);
				}
			);

			/*
			 *  Инициализируем новые купоны, для рисования
			 */
			$('#ticket_chooser .coupon').each(
				function(){
					tickets[1] = initCoupon( 0, this, true );
					$(window).load(
						function(){
							firstElement[0].scrollTop = 0;
						}
					);
				}
			);
			
			// Автоматическая отправка купонов
			$('#auto_all_coupon').click(function(){
					// Если кнопка заблокирована
					if($('.play_button_multi').hasClass('disabled')) 
						return false;
					
					var c = $('#coupons_count').val(); // кол-во купонов
					var pattern = /^\d+$/;
					if(!c.match(pattern) && c != ''){
						show_multi_coupons_error('Вводить можно только числа');
						$('.play_button_multi').addClass('disabled');
						return false;
					}
					if(c > params.maxCoupons){
						show_multi_coupons_error(params.errors.maxcoupons);
						$('.play_button_multi').addClass('disabled');
						return false;
					}
					
					var coupons = $('#coupons_count').val();
					var host_name = window.location.hostname;
					var reg = /dev\./;
					var result = host_name.match(reg);
					
					// если dev. есть :)
					var action = (result != null) ? 'https://' + host_name + '/payment/autocoupon' : '/payment/autocoupon';

					//$('#gameForm').attr('action', action);
				}
			);
			
			// Переключение между вкладками "Один купон" и "Автоматическая мультивставка"
			jSwitcher.click(function(){
				var jCurrent = $(this),
					jCurrentContent = $('#'+ jCurrent.attr('id') + '_content'),
					jCurrentHasClass = jCurrent.hasClass('selected'),
					
					jOld = jSwitcher.not(jCurrent),
					jOldContent = $('#' + jOld.attr('id') + '_content');
					
					if(!jCurrentHasClass){
						jCurrent.toggleClass('selected', !jCurrentHasClass);
						jOld.toggleClass('selected', jCurrentHasClass);
						
						jCurrentContent.show();
						jOldContent.hide();
					}
					else{
						return false;
					}
			});

			$('#auto_form span').each(
				function(){
					var that = $(this).show();
					self.bind('numbers',
						function( event, field ){
							if( (numbersCounter == 0 || numbersCounter < params.minNumbers) && (all_combinations * params.price + params.price) <= params.maxSum ){
								that.show();
							}
							else if ( numbersCounter >= params.minNumbers ){
								//comment this, because everyone likes this
								//that.hide();
							}
						}
					);
					
					that.click(
						function(){
							//refresh field on repeat click
							$('#clear_form span').trigger("click");
							
							if( isLocked || (all_combinations * params.price + params.price) > params.maxSum ){
								return false;
							}

							var _set = numbersCounter, item;

							while( _set < params.minNumbers ){
								item = $(fields[ Math.round(Math.random() * (params.maxNumbers - 1)) ]);
								if( item.length && !item.hasClass('.selected') ){
									item.find('label').click().parent().find('input')[0].checked = true;
									_set++;
								}
							}
							fill_in_auto(currentField);
						}
					);
				}
			);

			/*
			 *	Очистка текущих заполненных значений
			 */
			$('#clear_form span').each(
				function(){
					var that = $(this).show();
					self.bind('numbers',
						function( event, field ){
							if( numbersCounter == 0 )
							{
								//comment this, because everyone likes this
								//that.hide();
							}
							else
							{
								that.show();
							}
						}
					);
					that.click(
						function(){
							if( isLocked )
								return false;
							fields.filter('.selected').find('label').click().parent().find('input').each(
								function(){
									this.checked = false;
								}
							);
							clear_field(currentField);
						}
					);
				}
			);

			/*
			 *  Элемент перехода между полями А, Б и тд.
			 */
			$('#coupon_field').each(
				function(){
					var that = $(this);

					self.bind('changefield',
						function( event, field ){
							that.find('span').removeClass('selected').eq( field - 1 ).addClass('selected');
						}
					);

					that.find('span').click(
						function(){
							if( isLocked || $(this).hasClass('selected') )
								return false;

							isLocked = 1;
							self.trigger("changefield", $(this).prevAll('span').length + 1 );
						}
					);
				}
			);
			
			// Блок Многокупонности
			$(function(){
				var tirages = $('#tirages'), 
					tirages_field = $('.tirages_count > i'), 
					coupons_field = $('.coupons_count > i'),
					price_field = $('#multi_full_price > i'), 
					marked = $('#marked_num'), 
					coupons_count = $('#coupons_count'),
					circulations = [],
					marked_numbers = [],
					summ = 0;
				
				// Подсчет суммы итоговой суммы
				$('#full_price > i').bind('getTotalSum', function(){
					// t - кол-во тиражей, n - кол-вой купонов, p - цена 1-го купона
					
					var t = tirages_field.val(), 
						n = coupons_field.val(), 
						p = self.getCouponAmount(marked.val());
					summ = t * n * p;
				});
				
				$('.circulation').click(function(){
					jCirculation = $(this);
					
					if(jCirculation.hasClass('circ_selected')) return false;
					
					$('.circ_selected').removeClass('circ_selected'); jCirculation.addClass('circ_selected');
					var counts = jCirculation.find('span').html(); // кол-во тиражей
					summ = counts * self.getCouponAmount(marked.val()) * coupons_count.val();
					tirages.val(counts);
					price_field.html(summ);
					tirages_field.html(counts);
					
					$('#error_block_multi').trigger('error_block_multi');
				});
				
			
				// Переключение кол-ва полей
				$('.marked_num .num').click(function(){
					jMarked_num = $(this);
					
					if(jMarked_num.hasClass('marked')) return false;
					
					$('.marked').removeClass('marked');
					var fields_count = jMarked_num.find('span').html(); // кол-во полей
					marked.val(fields_count);
					summ = tirages.val() * self.getCouponAmount(fields_count) * coupons_count.val();
					jMarked_num.addClass('marked');
					price_field.html(summ);
					
					$('#error_block_multi').trigger('error_block_multi');
				});
	
				
				// изменение кол-ва купонов по нажатию клавиши
				$('#coupons_count').keyup(function(){
					 // кол-во купонов
					var c = $(this).val(),
						pattern = /^\d+$/,
						jPlayButton = $('.play_button_multi');
					
					if(!c.match(pattern) && c != ''){
						show_multi_coupons_error('Вводить можно только числа');
						jPlayButton.addClass('disabled');
						return false;
					}
					
					if(c > params.maxCoupons){
						show_multi_coupons_error(params.errors.maxcoupons);
						jPlayButton.addClass('disabled');
						return false;
					}
					
					summ = tirages.val() * self.getCouponAmount(marked.val()) * c;
					price_field.html(summ);
					(c != '') ? coupons_field.html(c) : coupons_field.html(0);
					
					$('#error_block_multi').trigger('error_block_multi');
				});
				
				// вывод ошибок связанных с суммой
				$('#error_block_multi').bind('error_block_multi', function(){
					var error_field = $(this),
						coupons = coupons_count.val(),
						jButton = $('.play_button_multi');
					
					no_multi_coupons_errors();
					jButton.removeClass('disabled');
					
					// если кол-во купонов больше 1, узнаем цену 1 купона
					if(coupons > 1){
						if(summ/coupons > params.maxSum){
							show_multi_coupons_error(params.errors.coupons);
							jButton.addClass('disabled');
						}
					}
					else if(summ > params.maxSum){
						show_multi_coupons_error(params.errors.coupons);
						jButton.addClass('disabled');
					}
				});
				
				// Подсчет суммы
			});
			
			// стоимость 1-го купона, в зависимости от кол-ва полей
			self.getCouponAmount = function(coeff){
				var coeff = parseInt(coeff);
				
				switch(params.game_type){
					case '5x36':
						switch(coeff){
							case 5:
								return 180;
							break;
							case 6:
								return 1080;
							break;
							case 7:
								return 3780;
							break;
						}
					break;
					
					case '6x45':
						switch(coeff){
							case 6:
								return 300;
							break;
							case 7:
								return 2100;
							break;
							case 8:
								return 8400;
							break;
						}
					break;
					
					case '7x49':
						switch(coeff){
							case 7:
								return 600;
							break;
							case 8:
								return 4800;
							break;
							case 9:
								return 21600;
							break;
						}
					break;
				}
			};
			
			// конец многокупонности :)
			self.bind('numbers',
				function(event, action, number)
				{
					
					if (action == 0 || typeof(number) == "undefined")
							return;
					//self.check_number_thumbnail(number);
					tickets[currentCoupon].fill(tickets[currentCoupon], currentField, number, action);
				}
			);
			
			self.getTickets = function()
			{
				return tickets;
			};
			
			/**
			 * field_number - номер поля (1..6)
			 * number - число
			 */
			this.draw_field_map = function(coupon_field_number, number)
			{
				// action - 7 (галка), 1 (квадрат числа)
				if (typeof(number) === "undefined")
					action = 7;
				else
					action = 1;
				
				var coupon_number = 1;
				tickets[coupon_number].fill(tickets[coupon_number], coupon_field_number, number, action);
			};

			$(window).load(
				function(){
					if (window.gosloto_game.game.fill_in())
						return;
					/* Глюк с неправильной суммой, если начать ссылку "Автоматически" до полной загрузки страницы */
					/*fields.find('input').each(
						function( index ){
							if( this.checked ){
								self.trigger("numbers", [1,index + 1]);
								$(this).parent().addClass('selected');
							}
							else
								$(this).parent().removeClass('selected');
							
							this.checked = this.checked;
						}
					);*/
				}
			);
			

			/*
			 *	Запускаем изменение положения поля
			 */
			self.bind('changefield',
				function( event, newFieldIndex ){
					currentField = newFieldIndex;
					tickets[currentCoupon].changeField( tickets[currentCoupon], newFieldIndex );
				}
			);


			/*
			 *	Запускаем изменение положения купона
			 */
			self.bind('changecoupon',
				function( event, newCouponIndex, newFieldIndex ){
					if( currentCoupon != newCouponIndex ){
						selectedFields[currentCoupon] = currentField;
						if( !tickets[newCouponIndex + 1] ){
							tickets[newCouponIndex + 1] = initCoupon( newCouponIndex, $('#ticket_chooser .coupon')[newCouponIndex] );
						}
						tickets[currentCoupon].selected.fadeOut(200,
							function(){
								firstElement.animate(
									{
										scrollTop:parseInt(firstElement[0].scrollTop) -
											(tickets[currentCoupon].container.offset().top - tickets[newCouponIndex].container.offset().top)
									},
									300,
									'swing',
									function(){
										tickets[currentCoupon].container.removeClass('selected');
										tickets[newCouponIndex].container.addClass('selected');
										tickets[newCouponIndex].selected.fadeOut(0).fadeIn(200,
											function(){
												fieldsCounter = 0;
												for(var i = 1; i <= 6; i++){
													if( hiddenFields.find('input.field' + ((newCouponIndex - 1) * 6 + i)).length > 0 )
														fieldsCounter++;
												}

												var oldCoupon = currentCoupon;
												currentCoupon = newCouponIndex;
												self.trigger('changefield', [newFieldIndex, oldCoupon]);
											}
										);
									}
								);
							}
						);
					}
					else
						self.trigger('changefield', newFieldIndex);
				}
			);

			var numbers_block = $('#numbers');
			var frequent = numbers_block.find('.inner .pseudo_link');
			frequent.click(
				function(){
					$('#clear_form span').click();
					$(this).parents('li').find('b').each(
						function(){
							var index = parseInt(this.innerHTML, 10) - 1;
							if( fields[index] && !$(fields[index]).hasClass('selected') )
								$(fields[index]).find('label').click();
							frequent.addClass('hidden');
							
							fill_in_auto(currentField);
						}
					);
				}
			);

			var
				prev = numbers_block.find('.prev').addClass('disabled'),
				next = numbers_block.find('.next'),
				stripe = numbers_block.find('ul'),
				items = stripe.find('li'),
				items_amount = items.size(),
				current_item = 0,
				is_animate = false;

			prev.click(function(){
				if( current_item > 0 && !is_animate ){
					var me = $(this);
					next.removeClass('disabled');
					is_animate = true;

					stripe.animate(
						{left: -100 * (current_item - 1) + '%'},
						function(){
							current_item--;
							is_animate = false;

							if( current_item === 0 ){
								me.addClass('disabled');
							}
						}
					);
				}
			});

			next.click(function(){
				if( current_item < (items_amount - 1) && !is_animate ){
					var me = $(this);
					prev.removeClass('disabled');
					is_animate = true;

					stripe.animate(
						{left: -100 * (current_item + 1) + '%'},
						function(){
							current_item++;
							is_animate = false;

							if( current_item === (items_amount - 1) ){
								me.addClass('disabled');
							}
						}
					);
				}
			});
		};

		/*
		 * Класс отвечает за перерисовку купонов
		 */
		window.Game.Coupon = function( element ){
			if( !Game.Coupon.first ){
				Game.Coupon.color = $(element).parent().css('color');
				Game.Coupon.left = parseInt($(element).css('marginLeft').replace('px',''));
				Game.Coupon.width = element.clientWidth + Game.Coupon.left;
				Game.Coupon.height = element.clientHeight + parseInt($(element).css('marginBottom').replace('px',''));
				if( $.browser.msie ){
					Game.Coupon.height++;
				}
				Game.Coupon.first = 1;
			}
			this.selected = $(element).parent().find('i').css('width', element.clientWidth - 2).css('height', element.clientHeight - 2);
			this.container = $(element).parents('.coupon:first');
			for( var i = 0; i < 6; i++ ){
				this.selected.parent().append('<b style="width:'+element.clientWidth+'px;height:'+element.clientHeight+'px;top:'+(Math.floor(i / 2) * Game.Coupon.height)+'px;left:'+(i % 2 * Game.Coupon.width + Game.Coupon.left)+'px;"></b>');
			}

			var me = this;
			this.canvas = new Array();
			if( $.browser.msie ){
				$(element).parent().find('img').each(
					function( index ){
						var container = document.createElement('v:image');
						container.className = 'shape';

						container.style.width = this.clientWidth;
						container.style.height = this.clientHeight;
						container.src = this.src;

						me.canvas[ index + 1 ] = container;
						this.parentNode.appendChild(container);
						this.parentNode.removeChild(this);
					}
				);
			}
			else{
				$(element).parent().find('img').each(
					function( index ){
						var container = document.createElement('canvas');
						container.width = this.clientWidth;
						container.height = this.clientHeight;
						var canvas = container.getContext('2d');
						var image = new Image();
						$(image).load(function(){
							canvas.globalCompositeOperation = 'destination-over';
							canvas.drawImage(image, 0, 0, container.width, container.height);
							canvas.globalCompositeOperation = 'source-over';
						});
						image.src = this.src;
						me.canvas[index + 1] =  canvas;
						this.parentNode.appendChild(container);
						this.parentNode.removeChild(this);
					}
				);
			}
		};

		window.Game.Coupon.prototype = {
				fill:function( coupon, field, number, action ){
					var x = (number - 1) % 6 * 6 + 3;
					var y = Math.floor((number - 1) / 6)* 6 + 11;
					if( $.browser.msie ){
						if( action > 0 ){
							var rect = document.createElement('v:rect');
							rect.className = 'number' + number;
							rect.fillcolor = '#723526';
							rect.strokecolor = 'none';
							rect.style.width = '5px';
							rect.style.height = '5px';
							rect.style.position = 'absolute';
							rect.style.left = ((field - 1) % 2 * Game.Coupon.width + Game.Coupon.left - 1) + x + 'px';
							rect.style.top = (Math.floor((field - 1) / 2) * Game.Coupon.height - 1) + y + 1 + 'px';
							coupon.canvas[field].parentNode.insertBefore(rect, coupon.canvas[field]);
						}
						else{
							var prev = coupon.canvas[field];
							while( prev = prev.previousSibling ){
								if( prev.className == 'number' + number ){
									prev.parentNode.removeChild(prev);
									break;
								}
							}
						}
					}
					else{
						if( action > 0 ){
							coupon.canvas[field].fillStyle = '#723526';
							coupon.canvas[field].fillRect(x, y, 4, 4);
						}
						else{
							coupon.canvas[field].fillStyle = Game.Coupon.color;
							coupon.canvas[field].fillRect(x, y, 4, 4);
							coupon.canvas[field].fillStyle = 'rgb(255,255,255)';
							coupon.canvas[field].fillRect(x + 1, y + 1, 2, 2);
						}
					}
				},
				changeField: function( coupon, field ){
					coupon.selected.animate(
						{
							left:((field - 1) % 2 * Game.Coupon.width + Game.Coupon.left - 1) + 'px',
							top:(Math.floor((field - 1) / 2) * Game.Coupon.height - 1) + 'px'
						},
						200,
						'swing',
						function(){
							isLocked = 0;
						}
					);
				}
			};
		})();
});
