var	fc_name,
	fc_adress,
	fc_phone,
	fc_k_name,
	fc_k_phone,
	fc_k_email,
	fc_sotr, //1,2,3
	u_family,
	u_name,
	u_otch,
	u_phone,
	u_email,
	u_date,
	u_opit,
	u_obraz,
	u_vozm,
	u_instr,
	u_spec
	
var error=0
function validFile() 
{
	var ext = document.form_zayavka.u_file.value;
	ext = ext.substring(ext.length-3,ext.length);
	ext = ext.toLowerCase();

	if(ext=='bmp' || ext=='jpg' || ext=='png' || ext=='gif' || ext=='peg')
	{
		return true;
	}
	else
	{
    	return false;
	}
}

function validEmail (mail) { //Проверяем корректность адреса почты
  return (new RegExp ("^[_.0-9A-Za-z-]+@([0-9A-Za-z][0-9A-Za-z_-]+.)+[A-Za-z]{2,4}$").test(mail) ? 1 : 0);
}

function validPhone (phone) { //Проверяем корректность номера телефона
  return (new RegExp ("^[^a-zA-Zа-яА-Я]+$").test(phone) ? 1 : 0);
}
function reset_err(id)
{
	document.getElementById(id).style.border='2px solid #afff15';
	document.getElementById(id+'Error').innerHTML='';
}
function reset_norm_err(id)
{
	document.getElementById(id).style.border='1px solid #a9cbf0';
	document.getElementById(id+'Error').innerHTML='';
}
function reset_def_err(id)
{
	//document.getElementById(id).style.border='1px solid #a9cbf0';
	document.getElementById(id+'Error').innerHTML='';
}
function reset_err_text_block(id)
{
	var buf_id
		buf_id=id+"_text"
	document.getElementById(buf_id).style.border='2px solid #afff15';
	document.getElementById(id+'Error').innerHTML='';
}
function err_right(id,info)
{
	document.getElementById(id+'Error').innerHTML=info;
}
function err(id,info)
{
	document.getElementById(id).style.border='2px solid #ff496f';
    document.getElementById(id).style.margin=' 0 ';
    document.getElementById(id+'Error').innerHTML='Введите '+info;
}
function err_text_block(id,info)
{
	var buf_id
		buf_id=id+"_text"
	document.getElementById(buf_id).style.border='2px solid #ff496f';
    document.getElementById(buf_id).style.margin=' 0 ';
	err_right(id,info);
}
function check(id,mode,info)
{
	switch(mode)
	{
		case "email":
			if(!validEmail(document.getElementById(id).value))
			{
				err(id,info);
			    error++;
			}
			else
			{
				reset_err(id)
			}
			break;
		case "phone":
			if(document.getElementById(id).value=='' || !validPhone(document.getElementById(id).value))
       		{
    	        err(id,info);
    	        error++;
    	    }
			else
			{
				reset_err(id)
			}
			break;
		case "text":
			if(document.getElementById(id).value=='')
       		{             
            	err(id,info);
           		error++;
      	    }
			else
			{
				reset_err(id)
			}
			break;
		case "radio":
			i=0
			$(":radio:checked").each(function(data,n)
			{
				i++;
			})
			if(!i)
			{
				err_right(id,info);
				error++;
			}
			else
			{
				reset_def_err(id)
			}
			break;
		case "file":
			if(!validFile())
       		{             
            	err_right(id,info);
           		error++;
      	    }
			else
			{
				reset_def_err(id)
			}
			break;
		//		case "checkbox":
//			i=0;
//			$.each($(":checkbox:checked"),function(data)
//			{
//				i++;
//			})
//			if(!i)
//			{
//				err_text_block(id,info);
//				error++;
//			}
//			else
//				reset_err_text_block(id);
//			break;
	}
}

function checkFields(id)
{
	error=0;
	switch(id)
	{
		case "all":
		//case "u_vozm":
		//	check("u_vozm","checkbox","Поставьте отметку, что Вы сможете присутствовать на финале премии");
		
		case "fc_phone":
			check("fc_phone","phone","телефон");
		case "fc_adress":
			check("fc_adress","text","адрес");
		case "fc_name":
			check("fc_name","text","название");
		case "u_file":
			check("u_file","file","выберите файл *.jpeg, *.jpg, *.bmp, *.gif или *.png");
		case "u_video_info":
			if(check_video)
			{
				check("u_video_info","text","информацию к видео");
			}
		case "u_video":
			if(check_video)
			{
				check("u_video","text","ссылку на файл видео с тренировки");
			}
	
		case "u_instr":
		case "u_obraz":
			check("u_obraz","text","образование");
		case "u_spec":
			check("u_spec","text","должность");
		case "u_opit":
			check("u_opit","text","опыт");
		case "u_date":
			check("u_date","text","дату рождения");
		
		case "u_email":
			check("u_email","email","электронный адрес");
		case "u_phone":
			check("u_phone","phone","телефон");
		case "u_otch":
			check("u_otch","text","отчество");
		case "u_name":
			check("u_name","text","имя");
		case "u_family":
			check("u_family","text","фамилию");
		case "u_city":
			check("u_city","text","город");
		case "fc_sotr":
			check("fc_sotr","radio","Выберите номинацию");
	}
	if(error)
		return false;
	else
		return true;
}
function ref()
{
	location.reload()
}
function go_to(url)
{
	document.location.href = url;
}
function awards_sort(srt)
{
	$.post(
		   //"/ajax/ajaxAwards.php",
		   "/awards/change_sort.html",
		   {
			   "sort":srt
		   },
		   function(data)
		   {
			   //alert(data)
			 ref()
		   }
		   )
}
function awards_sort_count(srt)
{
	var adr=document.location.href;
	var preg=/([0-9]+)/;
	var user_id=adr.match(preg);
	$.post(
		   //"/ajax/ajaxAwards.php",
		   "/awards/change_sort_count.html?user="+user_id[1],
		   {
			   "sort":srt
		   },
		   function(data)
		   {
			   //alert(data)
			 //ref()
			 go_to(data);
		   }
		   )
}
function awards_add_voice(id)
{
	$.post("/awards/verify.html",function(data){
										  if(data=="1")
										  	$.post(
			   	"/awards/add_voice.html",
				{
					nomin:id
				},
				function()
				{
					//ref();
					go_to('/awards/user'+id+'.html?anchor=user');
				}
			   )
										else
											authority(id)
										  })
}
function awards_verify_login()
{
	$.post("/awards/verify.html",function(data){if(data=="1") return 1
												   else return 0})
}
function authority(id)
{
	window.location="http://onfit.ru/people_test/index.php?next_url=http://onfit.ru/awards/user"+id+".html";	
}

function awards_authorization(path)
{
	window.location="http://onfit.ru/people_test/index.php?next_url=http://onfit.ru/awards_2011/"+path;
}

function awards_add_comment(id)
{
	var msg
	msg=$("#new_comment").val();
	
	$.post(
		"/awards/verify.html",
		function(data){
										  if(data=="1")
										  {
	if(msg)
	{
					$.post(
						"/ajax/ajaxComments.php",
						{
							mode:"comments_timeout"
						},
						function(comments_timeout)
															 {
																if(comments_timeout=="0")
		$.post(
			   	"/awards/add_comment.html",
				{
					mode:"new",
					nomin:id,
					comment:msg
				},
				function(data)
				{
					go_to(data);
				}
			   )
																else
																	{
																	$('#comments_error').html("Вы сможете добавить следующий комментарий через "+comments_timeout+" сек");
																	go_to(window.location+"#comments");
																	//alert("Вы сможете добавить следующий комментарий через "+comments_timeout+" сек")
																	}
															 })
	}
										  }
	else
											authority(id)
										  })
}
function awards_delete_comment(id,mode)
{
	if(confirm("Удалить комментарий?"))
	{
		$.post("/awards/delete_comment.html",{id:id},function(){
															  $("#comment"+mode+id).html("Комментарий удален")
															  })
	}
}
function awards_edit_comment(id)
{
	var msg,edit,buff
	msg=$('#comment_area'+id).html();
	//buff=$('#editing'+id).html();
	$('#comment_area'+id).html("<textarea rows='5' id='textarea_buff"+id+"'>"+msg+"</textarea>");
	//$('#editing'+id).html("Сохранить");
	$('#editing_edit'+id).css('display','none');
	$('#editing_save'+id).css('display','');
	$('#editing'+id).attr("onclick","awards_send_editted_comment('"+id+"');");
}
function awards_send_editted_comment(id)
{
	var msg
	msg=$('#textarea_buff'+id).val();
	$.post("/awards/edit_comment.html",{id:id,comment:msg},
		   function(){
			  // $('#editing'+id).html(buff);
			  // $('#editing'+id).attr("onclick","awards_edit_comment('"+id+"')");
			   $('#comment_area'+id).html(msg);
			   $('#editing_edit'+id).css('display','');
			   $('#editing_save'+id).css('display','none');
			   })
}
function answer_show(id,nomin_id)
{
	$.post("/awards/verify.html",function(data){
										  if(data=="1")
										  {
	if(id)
	{
		$('#show_answer'+id).css('display','none');
		$('#hidden_answer'+id).css('display','');
	}
										  }
	else
											authority(nomin_id)})
}
function awards_answer_post(id)
{
	var msg
	msg=$("#answer"+id).val()
	if(msg)
	{
		$.post("/ajax/ajaxComments.php",{mode:"comments_timeout"},function(comments_timeout)
															 {
																if(comments_timeout=="0")
		$.post(
			   	"/awards/add_comment.html",
				{
					mode:"answer",
					id:id,
					comment:msg
				},
				function(data)
				{
					$('#show_answer'+id).css('display','');
					$('#hidden_answer'+id).css('display','none');
					go_to(data);
				}
			   )
		else
		{
																	$('#comments_error').html("Вы сможете добавить следующий комментарий через "+comments_timeout+" сек");
																	go_to(window.location+"#comments");
																	//alert("Вы сможете добавить следующий комментарий через "+comments_timeout+" сек")
		}
															 })
	}
}
function awards_delete_voice(id,nomin)
{
	if(confirm("Удалить голос?"))
	{
		$.post("/awards/delete_voice.html",{id:id,nomin_id:nomin},function(){
															  $("#count"+id).html("Голос удален")
															  })
	}
}

/////////////////////////////////////////////////
function awards_vote(nom_id,user_id)
{
	$.post(
		"/ajax/ajaxAwards2.php",{
			mode: "add_voice",
			instructor_id: user_id,
			nomination_id: nom_id
		},
		function(data){
			var temp = $.evalJSON(data);
			switch (temp[0])
			{
				case 1:
					//alert('Ваш голос принят');
					//$('.mark_votes').html(temp[1]);
					//$('#all_votes').html(temp[1]);
					awards_count_votes(nom_id, user_id);
					//$('#voting_button').css("display","none");
					$('#voting_button').replaceWith('<span style="display: inline-block;height: 29px;margin-top: 10px;">Ваш голос принят</span>');
					break;
				case 2:
					alert('Вы уже голосовали');
					$('.mark_votes').html(temp[1]);
					$('#all_votes').html(temp[1]);
					break;
				case 3:
					alert('Вы не авторизованы');
					awards_authorization("nomination"+nom_id+"/instructor"+user_id+".html");
					break;
				case 5:
					alert('Голосование не началось');
					$('.mark_votes').html(temp[1]);
					$('#all_votes').html(temp[1]);
					break;
				case 6:
					alert('Голосование завершилось');
					$('.mark_votes').html(temp[1]);
					$('#all_votes').html(temp[1]);
					break;
				default:
					alert('Произошла ошибка');
					break;
			}
		});
}

function awards_delete_vote(vote_id,user_id,ins_id,nom_id)
{
	if(confirm("Удалить голос?"))
	{
		$.post(
			"/ajax/ajaxAwards2.php",
			{
				mode: "delete_voice",
				user_id: user_id,
				vote_id: vote_id
			},
			function(data){
				$("#count"+vote_id).html("Голос удален");
				awards_count_votes(nom_id, ins_id);
			})
	}
}

function awards_list_votes(nom_id, user_id, mode, sort, page)
{
	$.post(
		"/ajax/ajaxAwards2.php",
		{
			mode:			(mode == 0)? "list_votes": "list_votes_deleted",
			instructor_id:	user_id,
			nomination_id:	nom_id,
			sort:			sort,
			page:			page
		},
		function(data){
			//alert(data);
			if (data)
				$('#hide_votes_list').css('display','inline');
			$('#list_votes').html(data);
			awards_count_votes(nom_id, user_id);
		}
	);
}

function awards_hide_votes()
{
	$('#list_votes').html('');
	$('#hide_votes_list').css('display','none');
}

function awards_count_votes(nom_id, user_id)
{
	$.post(
		"/ajax/ajaxAwards2.php",{
			mode: "count_vote",
			instructor_id: user_id,
			nomination_id: nom_id
		},
		function(data){
			var temp = $.evalJSON(data);
			$('.mark_votes').html(temp[0]);
			$('#all_votes').html(temp[0]);
			$('#deleted_votes').html(temp[1]);
		}
	);
}

function awards_banUser(user_id,count_id,comment_id)
{
	if(confirm("Забанить юзера номер "+user_id+" ?"))
	{
		$.post('http://onfit.ru/people_test/ajax/ajaxBanUser.php', 
				{    user_id:user_id},
				function(data){ 
						$("#count"+count_id).html('Пользователь забанен');
						$("#comment"+comment_id).html('Пользователь забанен');
				});
	}
}

function click_photo_upload(id)
{
	checkFields(id);
	error = 0;
	check("u_file","file","выберите файл *.jpeg, *.jpg, *.bmp, *.gif или *.png");
	if (error == 0)
	{
		JsHttpRequest.query(
            '/ajax/ajaxAwards2.php',
            {               
                'mode':		'upload_photo',
                'photo': document.getElementById("u_file")
            },
            function(result, errors) {
				if (result['error'] == 0)
				{
					$('#u_file_img').css("display", "block");
					$("#u_file_img").attr("src",result['msg']);
				}
            },
            false  // do not disable caching
        );
	}
}
