var ua = navigator.userAgent.toLowerCase();
isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1);

jQuery.fn.maxlength = function(options) {
	var settings = jQuery.extend({
		maxChars: 100,
		leftChars: "знаков осталось"
	}, options);
	return this.each(function() {
		var me = $(this);
		var l = settings.maxChars;
		me.bind('keydown keypress keyup',function(e) {
			if(me.val().length>settings.maxChars) me.val(me.val().substr(0,settings.maxChars));
			l = settings.maxChars - me.val().length;
			me.next('div').html(l + ' ' + settings.leftChars);
		});
		me.after('<div class="maxlen">' + settings.maxChars + ' ' + settings.leftChars + '</div>');
	});
};

jQuery.fn.maxwords = function(options) {
	var settings = jQuery.extend({
		maxWords: 20,
		leftWords: "слов осталось"
	}, options);
	return this.each(function() {
		var me = $(this);
		var l = settings.maxWords;
		me.bind('keydown keypress keyup',function(e) {
			var text = me.val();
			var arr = text.split(' ');
			if(arr.length>settings.maxWords) me.val(me.val().substr(0,me.val().length-1));
			l = settings.maxWords - arr.length;
			if(l<0) {
				l=0;
			}
			if(me.val().length==0) {
				l=settings.maxWords;
			}
			me.next('div').html(l + ' ' + settings.leftWords);
		});
		me.after('<div class="maxlen">' + settings.maxWords + ' ' + settings.leftWords + '</div>');
	});
};

function default_input_text(el_path, text, empty_class)
{
	if ($(el_path)) {
		$input = $(el_path);

		if ('' == $input.attr('value')) {
			$input.attr('value', text).addClass(empty_class);
		}

		$input.click(function(){
			if (text == $(this).attr('value')) {
				$(this).attr('value', '').removeClass(empty_class);
			}
		});

		$input.blur(function(){
			if ('' == $(this).attr('value')) {
				$(this).attr('value', text).addClass(empty_class);
			}
		});
	}
}


// Выравниваем блоки по высоте
	function doEqualCustom(path_elements, min_height)
	{
		var max_height = min_height;
		$(path_elements).each(function(){
			height = $(this).height();
			if (max_height < height) {
				max_height = height;
			}
		});
		$(path_elements).each(function(){
			$(this).height(max_height + 'px');
		});
	}


function che(id) {
	return document.getElementById(id).checked;
}
function val(id) {
	return $('#' + id).attr('value') != '';
}
function red(id) {
	result = false;
	for (i in id) {
		if ($('#' + id[i]).attr('value') == '') {
			$('#' + id[i]).addClass('error');
			result = true;
		}
	}
	return result;
}
$(document).ready(function() {
	default_input_text('.sort_inputs .input_number', 'Введите название или регистрационный номер', 'empty');
	$('.sortirovka').submit(function() {
		if ($('.sort_inputs .input_number').attr('value') == 'Введите название или регистрационный номер') {
			$('.sort_inputs .input_number').attr('value', '');
		}
	});

	doEqualCustom('.guri_item', '220');

	$('.scroll-pane').jScrollPane();

	$('.select_drugoe').click(function() {
		$('#' + $(this).attr('value')).slideToggle();
	});

	$('#add_application :file').each(function() {
		$(this).before('<div class="custom_file"></div><div class="file_name"></div>');
		$(this).clone().appendTo($(this).prev().prev());
		$(this).remove();
	});
	$('#add_application :file').change(function() {
		var file_name = $(this).attr('value');
		$(this).parent().parent().find('.file_name').html(file_name + ' <a href="#">X</a>');

		$('.file_name a').click(function() {
			var $inp = $(this).parent().parent().find('input');
			$inp.replaceWith($inp.clone(true)); // очищаем инпут, с сохранением событий
			$(this).parent().html('');
			return false;
		});
	});


	$('.nominations input').change(function() {
		$('.select_nomination').hide();
		$(this).parent().find('.select_nomination').css('display', 'block');
	});

	$('.nominations :checked').each(function() {
		$(this).parent().find('.select_nomination').css('display', 'block');
	});

	$('.select_nomination').click(function() {
		var n = $('#step1 :checked').attr('value');
		$('#step2 tbody, .nom89, .nom90').hide();
		$('#step2 .all').show();
		$('#step2 .nom' + n).show();

		$('#step1, #step2').toggle();
		var tmp = $('.team:gt(4)');
		tmp.css('display','none');
		$('.team:lt(5)').attr('class','all');
		return false;
	});
	
	$('.add_team').click(function(){
		$('.team:lt(5)').css('display','table-row');
		$('.team:lt(5)').attr('class','all');
		if(!$('.team').html()) {
			$(this).hide();
		}
		return false;
	});

	$('#descr_500').maxlength({maxChars: 800});
	$('#point').maxwords({maxWords: 20});
	$('#add_application').submit(function() {
		var error = false;
		var error_text = '';
		$('#errors').html('');
		$('.error').removeClass('error');

		$('.nado input').each(function() {
			if ($(this).attr('value') == '') {
				field_name = $(this).parent().parent().find('label').html();
				error_text += '<li>' + field_name + '</li>';
				$(this).addClass('error');
				errors = true;
			}
		});

		if ($('#descr_500').attr('value') == '') {
			$('#descr_500').addClass('error');
			error_text += '<li>Краткое описание проекта</li>';
			error = true;
		}





		var nom89 = document.getElementById('i89').checked;
		var nom90 = document.getElementById('i90').checked;

		//Тип проекта
		if (!(che('saas') || che('cloud_infrastructure') || che('virtualization_solution') || che('social_networking_service') || che('mobile_application') || che('online_game') || che('ecommerce') || che('web_portal') || val('drugoe_1'))) {
			error_text += '<li>Тип проекта</li>';
			error = true;
		}

		//Ссылку на сайт, демо/бета версию, или прикрепите скриншот прототипа
		if (!val('ssylka_link2')  && !val('prototip') && nom89) {
			error_text += '<li>Ссылку на демо/бета версию, или скриншот прототипа</li>';
			error = true;

			red(['ssylka_link', 'kolvo_ezhednevnyh_polzovatelej']);
			red(['ssylka_link2', 'user', 'password']);
		}
		if ((!val('ssylka_link') && nom90)) {
			error_text += '<li>Ссылку на сайт</li>';
			error = true;

			red(['ssylka_link', 'kolvo_ezhednevnyh_polzovatelej']);
			red(['ssylka_link2', 'user', 'password']);
		}

		/*
		if (!(val('ssylka_link') && val('kolvo_ezhednevnyh_polzovatelej'))) {
			red(['ssylka_link', 'kolvo_ezhednevnyh_polzovatelej']);
			error_text += '<li>Ссылку на сайт, демо/бета версию, или скриншот прототипа</li>';
			error = true;
		} else if (!(val('ssylka_link2') && val('user') && val('password'))) {
			red(['ssylka_link2', 'user', 'password']);
			error_text += '<li>Ссылку на сайт, демо/бета версию, или скриншот прототипа</li>';
			error = true;
		} else if (!val('prototip')) {
			error_text += '<li>Ссылку на сайт, демо/бета версию, или скриншот прототипа</li>';
			error = true;
		}
		*/


		//Ближайших конкурентов и аналоги
		if (!(val('rossijskie') && val('mirovye'))) {
			error_text += '<li>Ближайших конкурентов и аналоги</li>';
			error = true;
			red(['rossijskie', 'mirovye']);
		}

		//Уникальность вашего проекта
		if (!val('opishite_unikalnost_proekta')) {
			error_text += '<li>Уникальность вашего проекта</li>';
			error = true;
			red(['opishite_unikalnost_proekta']);
		}

		//Способ монетизации
		if (!(che('podpiska_na_uslugi_kontent') || che('prodazha_reklamy') || che('razovye_prodazhi_tovarov_uslug') || che('komissiya_so_sdelok_tretih_lic') || val('drugoe_2'))) {
			error_text += '<li>Способ монетизации</li>';
			error = true;
		}

		//Целевую аудиторию
		if (nom90) {
			if (!(val('portret') && val('kolichestvo_registriruyuwihsya_na_sajte_polzovatelej_v_mesyac') && val('kolvo_unikalnyh_ezhednevnyh_polzovatelej') && val('skorost_rosta_celevoj_auditorii_v_mesyac') && val('ocenite_potencialnyj_obem_auditorii_v_rossiimire'))) {
				error_text += '<li>Целевую аудиторию</li>';
				error = true;
				red(['portret', 'kolichestvo_registriruyuwihsya_na_sajte_polzovatelej_v_mesyac', 'kolvo_unikalnyh_ezhednevnyh_polzovatelej', 'skorost_rosta_celevoj_auditorii_v_mesyac', 'ocenite_potencialnyj_obem_auditorii_v_rossiimire']);
			}
		}
		if (nom89) {
			if (!(val('portret') && val('ocenite_potencialnyj_obem_auditorii_v_rossiimire'))) {
				error_text += '<li>Целевую аудиторию</li>';
				error = true;

				red(['portret', 'ocenite_potencialnyj_obem_auditorii_v_rossiimire']);
			}
		}

		//Подмножество целевой аудитории, приносящие доход
		if (nom90) {
			if (!(val('portret_1') && val('kolichestvo_zaregistrirovannyh_platnyh_akkauntov_za_mesyac_1') && val('skorost_rosta_auditorii_prinosyawej_dohod__v_mesyac_1') && val('ocenite_potencialnyj_obem_auditorii_prinosyawej_dohod_v_rossiimire'))) {
				error_text += '<li>Подмножество целевой аудитории, приносящие доход</li>';
				error = true;
				red(['portret_1', 'kolichestvo_zaregistrirovannyh_platnyh_akkauntov_za_mesyac_1', 'skorost_rosta_auditorii_prinosyawej_dohod__v_mesyac_1', 'ocenite_potencialnyj_obem_auditorii_prinosyawej_dohod_v_rossiimire']);
			}
		}
		if (nom89) {
			if (!(val('portret_1') && val('ocenite_potencialnyj_obem_auditorii_prinosyawej_dohod_v_rossiimire'))) {
				error_text += '<li>Подмножество целевой аудитории, приносящие доход</li>';
				error = true;
				red(['portret_1', 'ocenite_potencialnyj_obem_auditorii_prinosyawej_dohod_v_rossiimire']);
			}
		}

		//Основной продукт/услуга для целевой аудитории
		if (!val('osnovnoj_produktusluga_dlya_celevoj_auditorii')) {
			error_text += '<li>Основной продукт/услуга для целевой аудитории</li>';
			error = true;
			red(['osnovnoj_produktusluga_dlya_celevoj_auditorii']);
		}

		//Основные каналы привлечения трафика аудитории
		if (nom90 && !val('osnovnye_kanaly_privlecheniya_trafika_auditorii')) {
			error_text += '<li>Основные каналы привлечения трафика аудитории</li>';
			error = true;
			red(['osnovnye_kanaly_privlecheniya_trafika_auditorii']);
		}

		//Стратегия запуска стартапа (каналы привлечения критической массы пользователей)
		if (nom89 && !val('strategiya_zapuska_startapa_kanaly_privlecheniya_kriticheskoj_massy_polzovatelej')) {
			error_text += '<li>Стратегия запуска стартапа (каналы привлечения критической массы пользователей)</li>';
			error = true;
			red(['strategiya_zapuska_startapa_kanaly_privlecheniya_kriticheskoj_massy_polzovatelej']);
		}

		//Команда
		if (!val('roli_i_sostav')) {
			error_text += '<li>Команда</li>';
			error = true;
			red(['roli_i_sostav']);
		}


		//Доход проекта за год
		if (nom90 && !val('dohod_proekta_za_god_trub')) {
			error_text += '<li>Доход проекта за год</li>';
			error = true;
			red(['dohod_proekta_za_god_trub']);
		}

		//Полученное финансирование
		if (nom90 && !val('poluchennoe_finansirovanie')) {
			error_text += '<li>Полученное финансирование</li>';
			error = true;
			red(['poluchennoe_finansirovanie']);
		}

		//Оценочный объем финансирования, необходимого для реализации проекта
		if (!val('ukazhite_ocenochnyj_obem')) {
			error_text += '<li>Оценочный объем финансирования, необходимого для реализации проекта</li>';
			error = true;
			red(['ukazhite_ocenochnyj_obem']);
		}

		if(!$('#point').val()) {
			error = true;
			error_text += '<li>Необходимо описать суть Вашего проекта</li>';
			$('#point').attr('class','error');
		} else {
			var text = $('#point').val();
			var arr = text.split(' ');
			if(arr.length>20) {
				error = true;
				error_text += '<li>При описании сути Вашего проекта используйте не более 20 слов.</li>';
				$('#point').attr('class','error');
			}
		}
		
		if(!$('#model').val()) {
			error = true;
			error_text += '<li>Необходимо описать бизнес модель проекта</li>';
			$('#model').attr('class','error');
		}
		
		






		if (error) {
			$('#errors').html('Вы не заполнили поля:<ul>' + error_text + '</ul>');
			window.scroll(0,240);
		}

		if (!error && !$('#rule_true')[0].checked) {
			error = true;
			alert('Для подачи заявки, вам необходимо согласится с правилами.');
		}

		return !error;
	});





	country_id = $('#strana').attr('value');
	$('#city_input, #gorod').autocomplete('/get_city.php?city=' + country_id, {
		delay:10,
		minChars:1,
		matchSubset:1,
		autoFill:true,
		maxItemsToShow:10
	});
	$('#strana').change(function() {
		$('#city_input, #gorod').attr('value', '');
		if ($(this).attr('value') == '27754') {
			$('#drugai_strana input').attr('uminado', 'Другая страна');
			$('#drugai_strana').show();
			$('#drugai_strana input').focus();
			// убрать подстановку...
			tagtext = '';
		} else {
			country_id = $(this).attr('value');
			tagtext = '';

			$('#city_input, #gorod').autocomplete('/get_city.php?city=' + country_id, {
				delay:10,
				minChars:1,
				matchSubset:1,
				autoFill:true,
				maxItemsToShow:10
			});
		}
	});


	$('#reg_form').submit(function() {
		var error = false;
		var error_text = '';
		$('#errors').html('');
		$('.error').removeClass('error');

		$(this).find('[uminado]').each(function() {
			if ($(this).attr('type') == 'checkbox') {
				value = $(this)[0].checked;
			} else {
				value = $(this).attr('value');
			}

			if (!value) {
				$(this).addClass('error');
				error_text += '<li>' + $(this).attr('uminado') + '</li>';
				error = true;
			}

			if ($('[name=password_confirm]') && $(this).attr('name') == 'password_confirm' && $('[name=password]').attr('value') != '' && $('[name=password]').attr('value') != $('[name=password_confirm]').attr('value')) {
				$('[name=password_confirm]').addClass('error');
				error_text += '<li>Не совпадают пароли</li>';
				error = true;
			}
		});

		if (error) {
			$('#errors').html('Вы не заполнили поля:<ul>' + error_text + '</ul>');
			window.scroll(0,240);
		} else {
			if ($('#confirm_x')[0] && !$('#confirm_x')[0].checked) {
				alert('Для регистрации, вам необходимо согласится с правилами.');
				error = true;
			}
		}

		return !error;

	});

	$('.ajax_popup').click(function() {
		$.ajax({
			url: $(this).attr('href'),
			data: "mode=ajax",
			//cache: false,
			success: function(html){
				$.fancybox(
					html,
					{
						'width' : 520,
						'height': 520,
						'autoDimensions': false
					}
				);
			}
		});
		return false;
	});

	$('#widget_menu a').click(function() {
		if (!$(this).hasClass('active')) {
			var widget_id = $(this).attr('href').substr($(this).attr('href').lastIndexOf('#') + 1);
			$('#widget_menu a, #widget_block .item').removeClass('active');
			$(this).addClass('active');
			$('#widget_' + widget_id).addClass('active');
		}
		return false;
	});



	$('#comment_form').submit(function() {
		$html = $('.popup_content').html();
		$.fancybox(
			$html,
			{
				'width' : 520,
				'height': 520,
				'autoDimensions': false
			}
		);



		$('.comment_td_left li').click(function() {
			if (!$(this).hasClass('active')) {
				login_name = $(this).attr('class');
				$('.comment_td_left li').removeClass('active');
				$('.comments_td_right .item').removeClass('active');

				$(this).addClass('active');
				$('.' + login_name).addClass('active');
			}
		});


		$('#fancybox-inner .login_webready form').ajaxForm({
			data: {mode: 'ajax'},
			success: function(repsoneText) {
				if (repsoneText.indexOf('/users/login_do/') == -1) {
					$('#comment_form').ajaxSubmit(function() {
						document.location = document.location;
					});
				} else {
					alert('Не верные Email/пароль');
				}
			}
		});


		$('#fancybox-inner .login_loginza form').submit(function() {
			if ($('#fancybox-inner .login_loginza form :checked').length) {
				if (isIE) {
					var open_id_txt = $('#fancybox-inner .openid_login').attr('value');
					if (open_id_txt == '') {
						alert('Необходимо ввести OpenId');
					} else {
						$.ajax({
							method: 'post',
							url: '/users/openid',
							data: "openid_action=login&openid_url=" + open_id_txt,
							cache: false,
							success: function(repsoneText){
								if (repsoneText.indexOf('http://') == 0) {
									var strUrl = repsoneText;
									var newWin = window.open(strUrl, 'openid', 'width=880,height=450');
								} else {
									alert(repsoneText);
								}
							}
						});
					}
				} else {
					var w = window.open('/loginza/index.html', 'loginza_blank', 'width=420,height=330');
				}
			} else {
				alert('Необходимо согласиться с правилами');
			}
			return false;
		});



		return false;
	});

	if (isIE) {
		$('.for_all').hide();
		$('.openid_for_ie').show();
	}
	

});

