jQuery.extend(Number.prototype, {

	/* Возвращает красиво оформленное число: 1234567.0981 => 1 234 567,10 */
	nice: function (iRoundBase) {
		var re = /^(-)?(\d+)([\.,](\d+))?$/;
		var iNum = Number(this);
		var sNum = String(iNum);
		var aMatches;
		var sDecPart = '';
		var sMinusSign = '&minus;';
		var sTSeparator = '&nbsp;';
		if ((aMatches = sNum.match(re))) {
			var sSign = aMatches[1] ? sMinusSign : '';
			var sIntPart = aMatches[2];
			var iDecPart = aMatches[4] ? Number('0.' + aMatches[4]) : 0;

			if (iDecPart) {
				var iRF = Math.pow(10, iRoundBase ? iRoundBase : 2);
				iDecPart = Math.round(iDecPart * iRF);
				sDecPart = iDecPart ? ',' + iDecPart : '';
			}

			if (Number(sIntPart) < 10000) {
				return sSign + sIntPart + sDecPart;
			}
			else {
				var sNewNum = '';
				var i;
				for (i = 1; i * 3 < sIntPart.length; i++) {
					sNewNum = sTSeparator + sIntPart.substring(sIntPart.length - i * 3, sIntPart.length - (i - 1) * 3) + sNewNum;
				}
				return sSign + sIntPart.substr(0, 3 - i * 3 + sIntPart.length) + sNewNum + sDecPart;
			}
		}
		else { // нам что-то не то подсунули
			return sNum;
		}
	}

});

Array.prototype.exists = function(o) {
	for(var i = 0; i < this.length; i++)
	   if(this[i] === o)
	     return true;
	return false;
}

check_browser = function(){
	var body = $('body');

	if($.browser.mozilla){
		body.addClass('ff');
	}
	else if($.browser.opera){
		body.addClass('opera');
	}
	else if($.browser.safari){
		body.addClass('safari');
	}
}

search_placeholder = function(search_element, place_holder_string){
	var start_val = search_element.val();

	if(start_val == '' || !start_val){
		search_element.val(place_holder_string);
	}

	if(start_val == '' || start_val == 'поиск'){
		search_element.addClass('empty');
	}

	//проверяем состояния при наступлении события сброса фокуса
	search_element.blur(function(){
		var me = $(this);

		switch(me.val()){
			case '':
				me.val(place_holder_string);
			case place_holder_string:
				me.addClass('empty');
				break;
			default:
				me.removeClass('empty');
		}
	});

	//проверяем состояния при наступлении события фокус
	search_element.focus(function(){
		var me = $(this);

		switch(me.val()){
			case '':
				break;
			case place_holder_string:
				me.removeClass('empty');
				me.val('');
				break;
		}
	});
}

var exampleInput = function(){
	var is_search_field = $('.search_field input:text');
	var search_field = is_search_field.size() ? is_search_field : $('.search_field input[type=search]');

	$('.example_input .pseudo_link').click(function() {
		search_field.val($(this).text()).blur();
	});
};


var init_popup_check_bulletin = function(){
	this.layout = $('#layout');
	this.layout.append('<div class="rc1" style="potition: absolute; left: -1000%; top: 0; height:0; width:0;" />');

	this.popup = $('#popup_big');
	this.check_bulletin_form = $('#check_bulletin_form');
	this.check_bulletin_link = $('.check_bulletin_link a, span.check_bulletin_link, a.check_bulletin_link');
	this.was_loaded = false;
	this.was_opened = false;

	this.jFade = $('#fade');
	if( !this.jFade.size() ){
		this.jFade = $(document.createElement('div')).attr('id', 'fade').addClass('not_display');
		$('#layout').append(this.jFade);
	}

	var that = this;

	this.check_bulletin_link.click(function(){
		var
			me = $(this),
			top_position = document.documentElement.scrollTop || document.body.scrollTop;
			
		that.popup.removeClass(current_game);
			
		if( me.hasClass('game_5_36') ){
			current_game = 'game_5_36';
		} else if( me.hasClass('game_6_45') ){
			current_game = 'game_6_45';
		} else if( me.hasClass('game_7_49') ){
			current_game = 'game_7_49';
		}
		
		if(that.check_bulletin_form.size() && that.was_loaded){
			that.was_loaded = true;
			that.popup.find('form').removeClass('not_display');
			that.popup.addClass('check_bulletin ' + current_game).removeClass('not_display').css({top: top_position + 20});

			if( $.browser.msie && $.browser.version == 6 ){
				that.jFade[0].style.height = that.layout[0].offsetHeight + 'px';
			}

			that.jFade.removeClass('not_display');

			if(!that.was_opened){
				that.check_bull = new check_bulletin(me);
				that.was_opened = true;
			}
		} else {
			$.ajax({
				url: popup_url,
				success: function(msg){
					$('#popup_big > .content').append(msg);
					that.check_bulletin_form = $('#check_bulletin_form').removeClass('not_display');
					that.popup = $('#popup_big').addClass('check_bulletin ' + current_game).removeClass('not_display').css({top: top_position});
					that.jFade = $('#fade').removeClass('not_display');

					if( $.browser.msie && $.browser.version == 6 ){
						that.jFade[0].style.height = that.layout[0].offsetHeight + 'px';
					}

					that.was_opened = true;
					that.was_loaded = true;
					that.check_bull = new check_bulletin(me);
					that.check_bull.toggle_game_types_action(current_game);
				}
			});
		}
		
		if(that.was_loaded){
			that.check_bull.toggle_game_types_action(current_game);
		}

		return false;
	});
}

var check_bulletin = function(pointer){
	this.pointer = pointer;
	this.init();
}

check_bulletin.prototype = {
	game_types: {
		'game_5_36': {
			game_name: '5 из 36',
			selected: false,
			min: 5,
			max: 36,
			max_available: 23
		},
		'game_6_45': {
			game_name: '6 из 45',
			selected: false,
			min: 6,
			max: 45,
			max_available: 30
		},
		'game_7_49': {
			game_name: '7 из 49',
			selected: false,
			min: 7,
			max: 49,
			max_available: 30
		}
	},

	error: {
		less_than_min_amount: 'Нужно отметить минимум %amount% чисел',
		more_than_max_amount: 'Вы не&nbsp;можете отметить более %amount% чисел',
		bulletin_number_content: 'Номер билета может состоять только из&nbsp;цифр',
		bulletin_number_amount: 'Номер билета должен содержать не&nbsp;менее десяти цифр',
		combination_content: 'На&nbsp;билете можно отмечать только числа',
		combination_whitespace: 'Числа должны быть разделены пробелами',
		combination_duplicate: 'Вы дважды ввели число %digit%',
		combination_not_existed: 'В&nbsp;игре %game% вряд&nbsp;ли когда-нибудь выпадет число %digit%'
	},

	init: function(){
		this.current_url = document.location.href;
		this.jFade = $('#fade');
		this.popup = $('#popup_big').addClass(current_game);
		this.close = this.popup.find('.close');
		this.main_content = this.popup.find('.content .main_content');
		this.checked_numbers = this.popup.find('.checked_numbers');
		this.clear_form = this.checked_numbers.find('.clear_form');
		this.items = this.checked_numbers.find('li');
		this.inputs = this.items.find('input');
		this.labels = this.items.find('label');

		this.game_switcher = $('#game_type_switcher');
		this.game_switcher_items = this.game_switcher.find('.pseudo_link');
		this.game_switcher_current_item = this.game_switcher.find('.' + current_game).addClass('selected').find('.pseudo_link')[0];

		this.check_form = this.popup.find('form').removeClass('not_display');
		this.submit_block = this.popup.find('.submit');
		this.submit_button = this.submit_block.find('input');

		this.close_button = this.popup.find('.close');

		this.disable_button();

		this.check_by_hands = $('.check_by_hands');
		this.bulletin_number = this.check_by_hands.find('.bulletin_number');
		this.combination = this.check_by_hands.find('.combination');
		this.bulletin_number_link = this.bulletin_number.find('.pseudo_link');
		this.combination_link = this.combination.find('.pseudo_link');
		this.bulletin_number_input_block = this.bulletin_number.find('.input_block');
		this.combination_input_block = this.combination.find('.input_block');
		this.bulletin_number_input = this.bulletin_number_input_block.find('input');
		this.combination_input = this.combination_input_block.find('input');
		this.bulletin_number_arrow = this.bulletin_number.find('.arrow');
		this.combination_arrow = this.combination.find('.arrow');

		this.choose_type = $('.choose_type');
		this.check_numbers_link = this.choose_type.find('.check_numbers_link');
		this.check_bulletin_link = this.choose_type.find('.check_bulletin_link');

		this.error_block = $(document.createElement('p')).addClass('error');

		this.items.prepend('<span class="icon"></span>');

		this.ajax_url = this.check_form[0].action;

		this.elements_amount = this.items.size();

		this.drawing_list = $('#drawing_list');
		this.drawing_list_options = this.drawing_list.find('option');
		this.drawing_date = this.check_form.find('.drawing .date');
		this.drawing_list.find('.' + current_game)[0].selected = true;
		
		for( var j in this.game_types ){
			this.game_types[j].options = this.drawing_list.find('.' + j);
		}

		var that = this;

		this.drawing_list.change(function(){
			that.init_balls();
		});

		this.update_corners();

		this.check_form_func();

		for (var i = 0; i < this.elements_amount; i++){
			if( this.inputs[i].checked ){
				this.items.eq(i).addClass('selected');
			}
		}

		this.inputs.bind('change click', function(){
			var me = $(this);

			if( me[0].checked ){
				me.parent().addClass('selected');
			} else {
				me.parent().removeClass('selected');
			}

			that.check_form_func();
		});

		this.toggle_fields();
		this.toggle_game_types();

		this.clear_form.click(function(){
			var index = that.drawing_list[0].selectedIndex;
			that.items.removeClass('selected');
			that.inputs.attr('checked', false);
			that.disable_button();
			that.drawing_list_options[index].selected = true;
		});

		this.close.click(function(){
			that.show_check_bulletin_form();
		});
		
		this.attach_events();
		this.choose_checking_type();

		this.sended = false;
		this.submit_form();

		this.init_balls();
	},

	init_balls: function(){
		var
			selected_option = this.drawing_list.find('option:selected'),
			numbers_array = $.trim(selected_option.attr('class').split(current_game)[0]).split(' ');

		this.drawing_date.text(selected_option[0].title);

		if( !this.win_numbers_list_block ){
			this.win_numbers_list_block = $(document.createElement('div')).addClass('win_numbers');
			this.win_numbers_list = $(document.createElement('ul'));
			this.win_numbers_list_block.append(this.win_numbers_list).prepend('<div class="edge" />');
		} else {
			this.win_numbers_list.empty();
		}

		for (var i = 0; i < numbers_array.length; i++){
			var ball = new Image();
			var item = $(document.createElement('li'));

			this.win_numbers_list.append(item);

			item.onload = function(){
				ball.alt = numbers_array[i];
			}

			ball.alt = numbers_array[i];
			ball.src = '/media/html/f/i/popup_balls/type_' + current_game.split('game_')[1] + '/' + numbers_array[i] + '.png';
			item.append($(ball));
		}
		
		this.main_content.before(this.win_numbers_list_block);
	},

	toggle_game_types: function(){
		var that = this;

		this.game_switcher_items.click(function(){
			if( that.game_switcher_current_item !== this ){
				var
					me = $(this),
					parent = me.parents('li'),
					game_type = current_game.split('game')[1],
					popup_class = that.popup.attr('class');
				
				if(
					( popup_class.split('win').length > 1 ||  popup_class.split('type').length > 1 ) && 
					( !me.hasClass('win' + game_type) && !me.hasClass('type' + game_type) )
				){
					that.show_check_bulletin_form();
				}
				
				that.toggle_game_types_action(parent.attr('class'));
				
				that.check_form_func();
				that.init_balls();
			}
		});
	},
	
	toggle_game_types_action: function(cur_game){
		this.popup.removeClass(current_game);
		$(this.game_switcher_current_item).parents('li').removeClass('selected');
		
		current_game = cur_game;

		this.game_switcher_current_item = this.game_switcher.find('.' + current_game).addClass('selected').find('.pseudo_link')[0];
		this.popup.addClass(current_game);
		
		this.drawing_list.html(this.game_types[current_game].options);
		this.game_types[current_game].options.eq(0).attr('selected', 'selected');
	},

	toggle_fields: function(){
		var that = this;

		this.bulletin_number_link.click(function(){
			if( !that.bulletin_number_link.hasClass('selected') ){
				that.bulletin_number_link.addClass('selected');
				that.bulletin_number_input_block.slideDown('fast', function(){
					that.bulletin_number_arrow.removeClass('not_display');
				});
				that.validate_by_bulletin_number();
				that.combination_link.removeClass('selected');
				that.combination_arrow.addClass('not_display');
				that.combination_input_block.slideUp('fast');
			}
		});

		this.combination_link.click(function(){
			if( !that.combination_link.hasClass('selected') ){
				that.combination_link.addClass('selected');
				that.combination_input_block.slideDown('fast', function(){
					that.combination_arrow.removeClass('not_display');
				});
				that.validate_by_combination();
				that.bulletin_number_link.removeClass('selected');
				that.bulletin_number_arrow.addClass('not_display');
				that.bulletin_number_input_block.slideUp('fast');
			}
		});
	},

	choose_checking_type: function(){
		var that = this;

		this.check_numbers_link.click(function(){
			var me = $(this);

			if(!me.hasClass('selected')){
				try {
					pageTracker._trackPageview(that.current_url + '/check_numbers');
				} catch(e){};
				
				me.addClass('selected');
	 			that.check_bulletin_link.removeClass('selected');
				that.check_by_hands.addClass('not_display');
				that.checked_numbers.removeClass('not_display');

				var index = that.drawing_list[0].selectedIndex;
				that.check_form_func();
				that.drawing_list_options[index].selected = true;
				that.update_corners();
			}
		});

		this.check_bulletin_link.click(function(){
			var me = $(this);

			if(!me.hasClass('selected')){
				try {
					pageTracker._trackPageview(that.current_url + '/check_by_hands');
				} catch(e){};
				
				me.addClass('selected');
				that.check_numbers_link.removeClass('selected');
				that.checked_numbers.addClass('not_display');
				that.check_by_hands.removeClass('not_display');

				var index = that.drawing_list[0].selectedIndex;
//				that.reset_form();

				if( that.combination_link.hasClass('selected') ){
					that.validate_by_combination();
				} else if( that.bulletin_number_link.hasClass('selected') ){
					that.validate_by_bulletin_number();
				}

				that.drawing_list_options[index].selected = true;
				that.update_corners();
			}
		});
	},

	update_corners: function(){
		rocon.update(this.check_numbers_link[0]);
		rocon.update(this.check_bulletin_link[0]);
	},

	attach_events: function(){
		var that = this;

		this.bulletin_number_input.bind('keyup change', function(){
			that.validate_by_bulletin_number();
		});

		this.combination_input.bind('keyup change', function(){
			that.validate_by_combination();
		});

		this.close_button.click(function(){
			that.popup.addClass('not_display').removeClass('check_bulletin');
			that.check_form.addClass('not_display');
			that.jFade.addClass('not_display').removeAttr('style');

			that.sended = false;
			that.clear_all();
		});
	},

	validate_by_bulletin_number: function(){
		this.json = {};

		var current_val = this.bulletin_number_input[0].value;

		//Если цифры
		if( /[\D\s]/.test(current_val) === false ){

			//Если есть хотя бы один символ
			if( current_val.length > 0 ){
				this.json = {};
				this.json.bulletin_number = current_val;
				this.error_block.text('');
				this.enable_button();
			} else {
				this.disable_button();
			}
		} else {
			this.disable_button();
			this.bulletin_number.append(this.error_block.html(this.error.bulletin_number_content));
		}
	},

	validate_by_combination: function(){
		this.json = {};

		var current_val = this.combination_input[0].value;

		this.error_block.text('');

		//Если цифры или пробелы
		if( /^[\d\s]*$/.test(current_val) === true ){

			//Если есть хотя бы один символ
			if( current_val.length > 0 ){
				this.json = {};
				this.json.combination = current_val;

				if( this.combination_parsing(current_val) ){
					this.enable_button();
				} else {
					this.disable_button();
				}
			} else {
				this.disable_button();
			}
		} else {
			this.disable_button();
			this.combination_input_block.before(this.error_block.html(this.error.combination_content));
		}
	},

	combination_parsing: function(val){
		var
			//Парсим значение по пробелам
			numbers_array = $.trim(val).split(' '),
			new_numbers_array = [],
			that = this;

//		this.new_numbers_array = [];

		for (var i = 0; i < numbers_array.length; i++){

			//Если не NaN
			if( !isNaN(parseInt(numbers_array[i], 10)) ){

				/*
				 * Если число состоит более чем из двух знаков,
				 * значит юзер забыл пробел - выводим ошибку.
				 */
				if( numbers_array[i].toString().length > 2 ){
					this.combination_input_block.before(this.error_block.html((this.error.combination_whitespace)));
					return false;
				} else {
					new_numbers_array[i] = parseInt(numbers_array[i], 10);
				}
			}
		}

		//Если отметили не меньше чисел, чем нужно
		if( new_numbers_array.length >= this.game_types[current_game].min ){
			this.json = {};
			this.json.checked_numbers = new_numbers_array;
			return true;
		} else {
			return false;
		}
	},

	check_form_func: function(){
		var checked_numbers_values = [];
		this.json = {};

		if( !this.checked_numbers.hasClass('not_display') ){
			for (var i = 0; i < this.elements_amount; i++){
				if(this.inputs[i].checked){
					checked_numbers_values.push(this.inputs[i].value);
				}
			}

			if( checked_numbers_values.length >= this.game_types[current_game].min ){
				this.json.checked_numbers = checked_numbers_values;
				this.enable_button();

				if( checked_numbers_values.length > this.game_types[current_game].max_available ){
					this.checked_numbers.prepend(this.error_block.html((this.error.more_than_max_amount.replace('%amount%', this.game_types[current_game].max_available))));
				} else {
					this.error_block.text('');
				}
			} else {
				this.disable_button();
			}
		}
	},

	submit_form: function(){
		var that = this;

		this.check_form.submit(function(){
			var last_check = true;

			if( that.combination_link.hasClass('selected') && that.check_bulletin_link.hasClass('selected') ){
				last_check = that.last_checking();
			}

			if( last_check && !that.sended ){
				that.sended = true;
				that.current_drawing = $(document.createElement('span')).text(that.drawing_list[0].value);
				that.drawing_list.addClass('not_display');
				that.drawing_list.after(that.current_drawing);

				that.json.drawing = that.drawing_list[0].value;

				that.send_request();
			}

			return false;
		});
	},

	last_checking: function(){
		var
			//Парсим значение по пробелам
			numbers_array = $.trim(this.combination_input[0].value).split(' '),
			new_numbers_array = [],
			that = this;

		for (var i = 0; i < numbers_array.length; i++){

			var int_value = parseInt(numbers_array[i], 10);

			//Если число ввели больше одного раза
			if( new_numbers_array.exists(int_value) ){
				setTimeout(function(){
					that.combination_input_block.before(that.error_block.html((that.error.combination_duplicate.replace('%digit%', numbers_array[i]))));
				}, 200);
				return false;
			} else {

				//Существует ли такое число в данной игре?
				if(numbers_array[i] <= this.game_types[current_game].max){

					//Проверка на 0
					if( int_value === 0 ){
						setTimeout(function(){
							that.combination_input_block.before(that.error_block.html((that.error.combination_not_existed.replace('%game%', that.game_types[current_game].game_name).replace('%digit%', numbers_array[i]))));
						}, 200);
						return false;
					} else {
						new_numbers_array[i] = int_value;
					}
				} else {
					setTimeout(function(){
						that.combination_input_block.before(that.error_block.html((that.error.combination_not_existed.replace('%game%', that.game_types[current_game].game_name).replace('%digit%', numbers_array[i]))));
					}, 200);
					return false;
				}
			}
		}

		return true;
	},

	send_request: function(){
		var that = this;

		this.json.game_type = current_game;
		
		$.ajax({
			dataType: 'json',
			url: that.ajax_url,
			data: this.json,
			success: function(msg){
				that.change_form(msg);
			}
		});
	},

	change_form: function(msg){
		if( msg.win ){
			this.popup_class = 'win_' + msg.type;
		} else {
			this.popup_class = 'type_' + msg.type;
		}

		this.popup.addClass(this.popup_class);

		var balls = this.win_numbers_list.find('li img');

		for (var i = 0; i < balls.size(); i++){
			this.balls_animate(balls.eq(i), i, msg);
		}

		this.check_by_hands.addClass('not_display');
		this.checked_numbers.addClass('not_display');
		this.choose_type.addClass('not_display');
		this.submit_block.addClass('not_display');

		this.new_content = $(document.createElement('div'));
		this.new_content[0].innerHTML = msg.content;
		this.new_content[0].style.visibility = 'hidden';

		this.main_content.prepend(this.new_content);

		this.update_content();
	},

	update_content: function(){
		var rounded = this.main_content.find('.coincidence');

		for (var i = 0; i < rounded.size(); i++){
			rocon.update(rounded[i]);
		}

		var that = this;

		this.main_content.find('.check_another_bulletin').click(function(){
			that.show_check_bulletin_form();
		});
	},

	show_check_bulletin_form: function(){
		this.items.removeClass('selected');
		this.inputs.attr('checked', false);
//		this.check_form[0].reset();
		this.sended = false;
		this.clear_all();
	},
	
	clear_all: function(){
		this.disable_button();

		if(this.popup_class){
			this.popup.removeClass(this.popup_class);
		}
		if(this.new_content){
			this.new_content.remove();
		}
		if(this.win_numbers_list){
			this.win_numbers_list.empty();
		}
		if(this.current_drawing){
			this.current_drawing.remove();
			this.drawing_list.removeClass('not_display');
		}

		this.choose_type.removeClass('not_display');
		this.submit_block.removeClass('not_display');

		if( this.check_numbers_link.hasClass('selected') ){
			this.checked_numbers.removeClass('not_display');
			this.check_by_hands.addClass('not_display');
		} else if( this.check_bulletin_link.hasClass('selected') ){
			this.checked_numbers.addClass('not_display');
			this.check_by_hands.removeClass('not_display');
		}

		this.drawing_date.text(this.drawing_list_options[this.drawing_list[0].selectedIndex].label);

		this.init_balls();
	},

	disable_button: function(){
		//this.submit_button[0].disabled = true;
		this.submit_button.addClass('disabled');
	},

	enable_button: function(){
		this.submit_button[0].disabled = false;
		this.submit_button.removeClass('disabled');
	},

	balls_animate: function(image, i, msg){
		var that = this;

		setTimeout(function(){
			image.animate({
				width: 115,
				height: 99,
				top: 0,
				left: 0
			}, 300);

			if((i+1) === that.game_types[current_game].min){
				setTimeout(function(){
					that.new_content[0].style.visibility = 'visible';
				}, 500);
			}
		}, 200*i);
	}
}

var ruslotto_popup = function(){
	this.init();
}

ruslotto_popup.prototype = {
	init: function(){
		this.popup = $('#popup_ruslotto');
		this.close_button = this.popup.find('.content .close');
		this.show_button = $('.table_results');
		
		var that = this;
		
		$(document).click(function(){
			that.close_results();
		});
		
		this.popup.click(function(evt){
			evt.stopPropagation();
		});
		
		this.show_button.click(function(evt){
			that.show_results();
			return false;
		});
		
		this.close_button.click(function(){
			that.close_results();
		});
	},
	
	show_results: function(){
		this.popup.removeClass('not_display');
	},

	close_results: function(){
		this.popup.addClass('not_display');
	}
}

$(function() {
	new exampleInput();
	new check_browser();
	new ruslotto_popup();
	//new init_popup_check_bulletin();
});

