$(document).ready(function(){

function buttonDisAbleAfterClick(){
       var name = "submited";
       $("."+name ).click(function(){
           $(this).attr("disabled","disabled");
           return true;
       });
}

function linksDisAbleAfterClick(){
       var name = "linked";
       $("."+name ).click(function(){
             if($(this).hasClass('wasPushed')){
               return false;
             }else{
                 $(this).addClass('wasPushed');
                 return true;
             }


       });
}

function checkingEmail(){
    var formId = "ad_datas";
    $("#ad_datas  button" ).click(function(){
     // $(this).remove();
     var result = checkingValidation();

        return result;

    });
    
}

function checkingValidation(){
    var formId = "ad_datas";
    var classInput = ".new_email";
    //var validEmail ;
    var result = true;
    $(".new_email").each(function(index, domElement){

var validEmail = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($(domElement).attr('value'));
//alert(validEmail);
if(validEmail == false){
    if($(domElement).next("a").next("span").length){
        
    }else{
            $(domElement).next("a").after('<span style="color:red; padding: 0px  0 5px 6px">Вы ввели не валидный Email</span>');
    }

    result = false;
}
       // alert($(domElement).attr('value'));
       // alert('sdfsdf');
    });
 //  alert (result);
 return result;
}

function prevDomDelete(){
    
    $("a.prev_dom_delete").live("click",function(){
        //alert('sdfsdf');
       $(this).parent().parent().remove();
        return false;
     });
   
}

//Запуск функций
checkingEmail();
prevDomDelete();
buttonDisAbleAfterClick();
linksDisAbleAfterClick();

$(function(){
  $("#dialog").dialog({
	 modal: ["true"], 
   buttons: {
      "ОК": function() {
        $(this).dialog("close");
      }
    }
  }
);
  
  
   
});


	$(function(){
	  $("#dialog2").dialog({
		modal: ["true"],
		width: 350,
		height: 160,
		autoOpen: false,
   buttons: {

      "ОК": function() {
        $(this).dialog("close");
      }
   }
	  });
	  $("a.noaccess").click(function(){
		$("#dialog2").dialog("open");
		return false;
	  });
	  $(this).click(function(){
		$(this).dialog("close");
	  });
	});	
				
// Для обработки фотографий				
	$(function(){
	  $("#block_edit_photos").dialog({
		modal: ["true"],
		width: 900,
		height: 'auto',
		autoOpen: false,
		resizable: false,
   buttons: {


   }
	  });
	  
	  //Обрабатываем нажатие на кнопку *Отказать*
	  $("a.btn5").live('click',function(){
								 
		var user_about = jQuery(this).parent("p").parent("div").parent("div").next("div").html();
		var user_img = jQuery(this).parent("p").parent("div").prev("div").html();
		//alert(user_img);
		jQuery("#user_about").html(user_about);
		jQuery("#photos_user").html(user_img);
		jQuery("#description").attr("value","");

//Перекрашиваем ячейку в нужный цвет

$("#photos_yes").attr('title', jQuery(this).attr('title'));
$("#photos_yes").attr('rel', jQuery(this).attr('rel'));

		$("#block_edit_photos").dialog("open");
		return false;
	  });
	  $("#photos_no").click(function(){
			$("#block_edit_photos").dialog("close");
			return false;		
	  });
	  
	// Отсылаем сообщение пользователю
	 $("#photos_yes").live('click',function(){
             if(!$("[@title='reasons']:input:checked").length){
                $("div.warningv3").show('normal');
                return false;
             }else{
                 $("div.warningv3").hide('fast');
 			var title_error = getListReasons();// jQuery("#towns").attr("value");
			//var title_error_type = getListReasons();
			var description_error = jQuery("#description").attr("value");
			var student_name_error = jQuery("#user_about p.ppp b").text();
			var obj = jQuery(this);

			$.post('/editphotos/ajax_denial',{card_id:obj.attr("rel"), student_id:obj.attr("title"),title:title_error, description:description_error, student_name:student_name_error},function(dataArray) {
				//alert(dataArray);
				if(dataArray == "yes"){
                                            //Меняем цвет ячейки - фото прошло утверждение
                                            jQuery("#user_" + obj.attr("title") + "").removeClass("back_for_arguably").removeClass("back_for_spisok").removeClass("back_for_success").addClass("back_for_denial");
                                            //Убираем постраничную навигацию
                                            jQuery("div.pagination").html("<a href='/editphotos/index' >Обновить</a>");
					}
			}, "json");

			$("#block_edit_photos").dialog("close");                
             }
             

			return false;
	  });  
	  
	});	

function getListReasons(){
    var values = '';
    var i = 0;
    jQuery("#block_edit_photos input:checked").each(function(){
      i++;
      if(i == jQuery("#block_edit_photos input:checked").length){
          values = values + $(this).val();
      }else{
          values = values + $(this).val()+ ':';
      }
      
    });

    return values;
}

//Обрабатываем клик на кнопке *Утвердить*
$("a.btn3").live('click',function(){
var obj = jQuery(this);
	$.post('/editphotos/ajax_accept',{student_id:obj.attr("title"), card_id:obj.attr("rel")},function(dataArray) {
		//alert(dataArray);
		if(dataArray == "yes"){
			obj.parent("p").parent("div").parent("div").parent("div").removeClass("back_for_denial").removeClass("back_for_spisok").removeClass("back_for_arguably").addClass("back_for_success"); //Меняем цвет ячейки - фото прошло утверждение
//Убираем постраничную навигацию
jQuery("div.pagination").html("<a href='/editphotos/index' >Обновить</a>");

			}
	}, "json");
return false;
});

//Обрабатываем клик на кнопке *Спорно*
$("a.btn4").live('click',function(){
var obj = jQuery(this);
	$.post('/editphotos/ajax_sporno',{student_id:obj.attr("title")},function(dataArray) {
		//alert(dataArray);
		if(dataArray == "yes"){
			obj.parent("p").parent("div").parent("div").parent("div").removeClass("back_for_denial").removeClass("back_for_spisok").removeClass("back_for_success").addClass("back_for_arguably"); //Меняем цвет ячейки - фото спорно - не прошло :-(
			}
	}, "json");
return false;
});


//// Обрабатываем нажатие на кнопку *Отказать*
//$("a.btn5").live('click',function(){
//		
//
//	return false;
//										   
//});			
				
			 



if($("#user_img").length){

}
else{


}

$("a.x, a.close").click(function(){
$(this).parents("div.one_message").empty();

return false;

});

	$(function(){
	  $("#dialog_find").dialog({
		modal: ["true"],
		width: 690,
		height: 500,
		autoOpen: false,
		resizable: false
	  });
	  $("#whome").click(function(){
		$("#dialog_find").dialog("open");
	  });
	  $("#search_over").click(function(){
		$("#dialog_find").dialog("close");
	  });
	});		
	
	
$("#dialog_find td").live('click',function(){
					   
var id = $(this).attr("id");
$("#recepient_id").attr("value", id); 
var name = $(this).children("div").children("p").children("span").children("b").html();
$("#whome").text(name);
$("#dialog_find td").removeClass("selecteduser"); 
$("#dialog_find td").addClass("bg"); 
$(this).removeClass("bg");
$(this).addClass("selecteduser");
});


$("#word").keyup(function (e) {


var my_word = $("#word").val();

if(my_word.length > 2){
	
$.post('/mymessage/json',{word:my_word},function(dataArray) { 
var searchDiv = $("#table_result");
searchDiv.text("");

$.each(dataArray,function(index,data){
data.grey2 = ' ';
if(data.avatar == null){data.avatar = 'little_avatar.jpg';}
if(data.login == null){data.grey2 = 'grey2';}
var text2="<tr><td  id=" + data.student_id + " class='bg poiskname border_bottom' style='width:600px' ><div class='left avatar_little'   ><img alt='' border='0' src='/image/get/crop/4:4/width/40/height/40/quality/90/nocache/true/type/avatar/file/" + data.avatar + "' /></div><div class='left width195px' ><p><span class='fromwho noline " + data.grey2 + "'><b>" + data.surname + " " + data.name + " " + data.otch + "</b><br/>Группа " + data.GR_GR_CODE + "</span></p></div><div class='right_block'><p class='grey'>Курс: <b>" + data.GR_KURS_CODE + "</b> Факультет: <b>" + data.GR_NAME_FACULT + "</b><br/>Специальность: <b>" + data.UPL_SPEC_NAME + "</b></p></div></td></tr>";

searchDiv.append(text2);
						 
});

}, "json");

 }

}).keypress();


$("#search_ajax").click(search_ajax);

function search_ajax(e) {

	var my_word = $("#word").val();
	
	
	$.post('/mymessage/json',{word:my_word},function(dataArray) { 
		var searchDiv = $("#table_result");
		searchDiv.text("");
		$.each(dataArray,function(index,data){
			//data.grey2 = ' ';
			if(data.avatar == null){data.avatar = 'little_avatar.jpg';}
			if(data.login == null){data.grey2 = 'grey2';}
			var text2="<tr><td  id=" + data.student_id + " class='bg poiskname border_bottom' style='width:600px' ><div class='left avatar_little'   ><img alt='' border='0' src='/image/get/crop/4:4/width/40/height/40/quality/90/nocache/true/type/avatar/file/" + data.avatar + "' /></div><div class='left width195px' ><p><span class='fromwho noline " + data.grey2 + "'><b>" + data.surname + " " + data.name + " " + data.otch + "</b><br/>Группа " + data.GR_GR_CODE + "</span></p></div><div class='right_block'><p class='grey'>Курс: <b>" + data.GR_KURS_CODE + "</b> Факультет: <b>" + data.GR_NAME_FACULT + "</b><br/>Специальность: <b>" + data.UPL_SPEC_NAME + "</b></p></div></td></tr>";
			
			searchDiv.append(text2);
		
		});

	}, "json");

}

$("#word").keydown(function(event) {
	if (event.which == 13) search_ajax();
});



$("a.hideblock").click(function(){

if($(this).prev("p").hasClass("message_docs")){
		$(this).prev("p").removeClass("message_docs").addClass("prevu");
		var p = $(this).prev("p");
		p.prev("p").removeClass("prevu").addClass("message_docs");
		$(this).text("Подробнее >>");
		p.prev("p").prev("div").prev("img").attr("src", "/img/little_papka.jpg");
	}else{
			
		$(this).prev("p").removeClass("prevu").addClass("message_docs");
		var p = $(this).prev("p");
		p.prev("p").removeClass("message_docs").addClass("prevu");	
		$(this).text("Свернуть <<");
		p.prev("p").prev("div").prev("img").attr("src", "/img/big_papka.jpg");
		}

return false;
});


$("img.docs").click(function(){
    var parentDiv = $(this).parent('div').parent('div');
    parentDiv.hide();
    parentDiv.next('div').show("normal");
    return false;
});

$("img.docs2").click(function(){
    var parentDiv = $(this).parent('div').parent('div').parent('div');
    parentDiv.hide();
    parentDiv.prev('div').show("normal");
    return false;
});

$("a.hideblock3").click(function(){

if($(this).prev("p").hasClass("message_docs2")){
		$(this).prev("p").removeClass("message_docs2").addClass("prevu");
		var p = $(this).prev("p");
		p.prev("p").removeClass("prevu").addClass("message_docs2");
		$(this).text("Подробнее >>");
		p.prev("p").prev("img").attr("src", "/img/stec_small_icon.png");
	}else{
			
		$(this).prev("p").removeClass("prevu").addClass("message_docs2");
		var p = $(this).prev("p");
		p.prev("p").removeClass("message_docs2").addClass("prevu");	
		$(this).text("Свернуть <<");
		p.prev("p").prev("img").attr("src", "/img/no_mailme.jpg");
		}

return false;
});


if($("#activation_acount").length){

 $.validator.addMethod("mydigitsnew", function(value, element) {
			if(/^[a-zA-Z0-9@_\.\-]+$/.test(value)){var antidigit = true;}else{antidigit = false;}
			//alert(element.value);
                        jQuery('#new_login_error').text('');
		return this.optional(element) || antidigit;
	}, 'Логин должен содержать только буквы латинского алфавита, цифры или символы "-", "_", "@", "."');

	$.validator.addMethod("mydigits", function(value, element) {
				if(/^\d+$/.test(value)){var antidigit = false;}else{antidigit = true;}	
				//alert(element.value);
                                jQuery('#new_login_error').text('');
			return this.optional(element) || antidigit;
		}, 'В этом поле должны быть  не только цифры, но и буквы.');

$.validator.addMethod("checklogin", function(value, element) {
$.post('/welcome/checklogin',{login:element.value},
		   function(data){ 

							if(data==1){$("#val").attr("value", "1");}else{$("#val").attr("value", "0");}
							

						 }, "text");
if($("#val").attr("value")==1){return true;}else{return false;}
}, 'Данный логин уже используется ... выберите другой.');


  jQuery("#activation_acount").validate({
	focusInvalid: false,
    focusCleanup: false,
 submitHandler: function(form){

                $.post('/data/ajax_validateemail_login_activation',{
                    new_login:jQuery("#login").attr('value'),new_email:jQuery("#email").attr('value')
                    },function(dataArray) {
                    //alert(dataArray);
                    //console.log(dataArray.new_email_error);
                    if(dataArray.new_login_error || dataArray.new_email_error){
                       jQuery('#new_login_error').text('');
                       jQuery('#new_email_error').text('');

                       if(dataArray.new_login_error)jQuery('#new_login_error').text(dataArray.new_login_error);
                       if(dataArray.new_email_error)jQuery('#new_email_error').text(dataArray.new_email_error);
                     
                    }else{

                        form.submit();
                        //console.log('submit');
                    }
                }, "json");

},
   
    rules: {		
      login: {
		required: true,
      	minlength: 5,
      	maxlength: 20,
		mydigits:true,
                mydigitsnew:true//,
		//checklogin:true
		
      },
      passw: {
      	required: true,
      	minlength: 3,
      	maxlength: 50,
        mydigits:true//,
        //mydigitsnew:true
      },
      passwagain: {
      	required: true,
      	minlength: 3,
      	maxlength: 50,
	equalTo: "#passw"

      },
       email: {
      	required: true,
	email:true
      }
},
    messages: {
      login: {
		required: "Укажите желаемый логин, пожалуйста.",
        minlength: "Не менее 5 символов",
        maxlength: "Не более 20 символов"
      },
      passw: {
        required: "Введите пароль",
        minlength: "Слишком короткий пароль (менее 3-х символов)",
        maxlength: "Слишком длинный пароль (более 50-х символов)"
      },
	  passwagain: {
        required: "Введите пароль",
        minlength: "Слишком короткий пароль (менее 3-х символов)",
        maxlength: "Слишком длинный пароль (более 50-х символов)",
		equalTo: "Введенные пароли не совпадают"
      },
       email: { 
        required: "Вы не ввели E-mail",
		email: "E-Mail введен некорректно"
      }
},	
    errorPlacement: function(error, element) {
      var er = element.attr("name");
      error.appendTo( element.parent("td").next("td").children("label[@for='" + er + "']"));
	  
    }	
});
  
}

if($("#plus_info").length){
  jQuery("#plus_info").validate({
	focusInvalid: false,
    focusCleanup: false,
 submitHandler: function(form) {
	 
				jQuery(form).ajaxSubmit({
					target: "#changenamedialog",
					dataType: "json",
					success: function(data) {
$("#tr_newname").remove();		
$("#tr_newname").live('remove', function(){$(this).remove()});						  
$("#changename").parent("td").parent("tr").after("<tr><td align='right' valign='middle'>Подана заявка на новую фамилию:</td><td align='left' valign='middle'><b>" + data + "</b>(проверяется админом)</td></tr>");
					  }

				});
				


	 $("#changenamedialog").dialog("close");
	 
	
	 },
   
    rules: {		
      newname: {
		required: true,
      	minlength: 3,
      	maxlength: 40,
		mydigits:true
		
      }
},
    messages: {
      newname: {
		required: "Укажите желаемый логин, пожалуйста!",
        minlength: "Не менее 5 символов",
        maxlength: "Не более 20 символов"
      }
      
},	
    errorPlacement: function(error, element) {
      var er = element.attr("name");
      error.appendTo( element.next("label[@for='" + er + "']"));
	  
    }	
}); 
 
	$(function(){
	  $("#changenamedialog").dialog({
		modal: ["true"],
		width: 610,

		autoOpen: false
	  });
	  $("#changename").click(function(){
		$("#changenamedialog").dialog("open");
		return false;
	  });
	  $("#nochangename").click(function(){
		$("#changenamedialog").dialog("close");
	  });
	  $(this).click(function(){
		$(this).dialog("close");
	  });

	});	
	
}

	$(function(){
	  $("#uploadavatar").dialog({
		modal: ["true"],
		width: 610,

		autoOpen: false
	  });
	  $("#addavatar").click(function(){
		$("#uploadavatar").dialog("open");
		return false;
	  });
	  $("#noavatar").click(function(){
		$("#uploadavatar").dialog("close");
	  });
	  $(this).click(function(){
		$(this).dialog("close");
	  });

	});	

	$(function(){
	  $("#goawaygroup").dialog({
		modal: ["true"],
		width: 610,

		autoOpen: false
	  });
	  $("div.one_group a.x2").live("click",function(){
	  $("span.good_type_id").attr("id", $(this).attr("id"));
	  //alert($("span.good_type_id").attr("id"));
		$("#goawaygroup").dialog("open");
		return false;
	  });
	  $("#no").click(function(){
		$("#goawaygroup").dialog("close");
	  });
	  $("#yes").click(function(){
		//alert($("span.good_type_id").attr("id"));
		
		$.post('/data/goawaygroup',{group_id:$("span.good_type_id").attr("id")},
		function(dataArray) { 
			if(dataArray =='yes'){
						
                                                    $("#"+$("span.good_type_id").attr("id")).parent("div").parent("div").remove(); //Удаляем данные из списка(заявку)
                                                      if($("div.spisokmygroups div").length ==0){ //Если был удалена последняя заявка, то скрываем надпись  -- Поданы заявки на вступление в группы: --
                                                         $("#zayavka_group span.mygroops").hide();
                                                     }
					      }
			}, "json");
		$("#goawaygroup").dialog("close");
	  });
	  $(this).click(function(){
		$(this).dialog("close");
	  });

	});	

	$(function(){
	  $("#goawaygroupminus").dialog({
		modal: ["true"],
		width: 610,

		autoOpen: false
	  });
	  $("div.one_group a.x3").live("click",function(){
	  $("span.good_type_id_minus").attr("id", $(this).attr("id"));
	  //alert($("span.good_type_id").attr("id"));
		$("#goawaygroupminus").dialog("open");
		return false;
	  });
	  $("#nominus").click(function(){
		$("#goawaygroupminus").dialog("close");
	  });
	  $("#yesminus").click(function(){
		//alert($("span.good_type_id").attr("id"));
		
		$.post('/data/goawaygroupminus',{group_id:$("span.good_type_id_minus").attr("id")},
		function(dataArray) { 
			if(dataArray =='yes'){
									//alert("EEEEE");
									$("#"+$("span.good_type_id_minus").attr("id")).parent("div").parent("div").remove(); //Удаляем данные из списка(заявку)
								}  
			}, "json");
		$("#goawaygroupminus").dialog("close");
	  });
	  $(this).click(function(){
		$(this).dialog("close");
	  });

	});	
	
	$(function(){
	  $("#plusgroupconteyner").dialog({
		modal: ["true"],
		width: 610,
		resizable: false,
		autoOpen: false
	  });
	  $("#plusgroup").click(function(){

var my_word = "hello";
$.post('/data/addgroupinfo',{word:my_word},function(dataArray) { 
var searchDiv = $("div.spisokmygroups_ajax");
searchDiv.text("");
$.each(dataArray,function(index,data){
if(data.count == null){var count = 0;}else{var count = data.count;}						  
var text2 = "<div class='one_group_ajax border'  id='" + data.id + "'><div class='left namegroup'><p><b>" + data.name + " </b><br/>участников: <b>" + count + "</b></p></div><div class='right titlegroup'><p class='left'>" + data.description + "</p><a class='block_style right x2' href='#' id='"+data.id+"'><img src='/img/x2.jpg' /></a></div><div class='ff_gluck'></div> <div class='input_val'><div class='left comment'>Комментарий:</div><div class='right titlegroup'><textarea  id='user_comment_"  + data.id +  "' name='user_comment_"  + data.id +  "' cols='' rows=''></textarea></div><div class='ff_gluck'></div></div>  </div>";
searchDiv.append(text2);

});

}, "json");

						 
									 
		$("#plusgroupconteyner").dialog("open");
		return false;
	  });
	  $("#goplusgroup").click(function(){
		if($("div.selected_group").length){
				var object = $("div.selected_group").children("div.namegroup").children("p").children("b").next("br").next("b");
				var count = parseInt(object.text())+1;
				object.text(count);
				var html = "<div class='one_group border'>" + $("div.selected_group").html() + "</div>";

                                if($("span.mygroops").is(":hidden")) {
					$("span.mygroops").show();
				}
                                
                                $("div.spisokmygroups").append(html);
				var id = $("div.selected_group").attr("id");
				// Вытаскиваем значение текста комментария
				var text_comment = $("div.selected_group").children("div.input_val").children("div.titlegroup").children("textarea").val();
				//alert(text_comment);
$.post('/data/addtogroup',{group_id:id, comment:text_comment},function(dataArray) {}, "json");
			}else{return false;}							   
			
		$("#plusgroupconteyner").dialog("close");
	  });
	  $("#noplusgroup").click(function(){
		$("#plusgroupconteyner").dialog("close");
	  });
	  $(this).click(function(){
		$(this).dialog("close");
	  });

	});	

$("div.one_group_ajax").live('click',function(){

$("div.one_group_ajax").removeClass("selected_group");

$(this).addClass("selected_group");	

});


	
$("#plusphone").click(function(){
	var n = $(this).attr("title");
	var number = parseInt($(this).attr("title")) + 1;
	$(this).attr("title", number);
	$(this).parent("td").parent("tr").after("<tr><td width='140' align='right' valign='middle'>Мобильный телефон:</td><td width='450' align='left' valign='middle'><input type='text'  class='new_phone'  name='phone[" + number + "]' id='phone' /><a href='#' class='prev_dom_delete'><img src='/img/x3.jpg' alt='' /></a></td></tr>\n");
	return false;						  
});

$("#plusemail").click(function(){
	var n = $(this).attr("title");
	var number = parseInt($(this).attr("title")) + 1;
	$(this).attr("title", number);
	$(this).parent("td").parent("tr").after("<tr><td width='140'  align='right' valign='middle'>E-mail:</td><td width='450' align='left' valign='middle'><input type='text' class='new_email'   name='emailplus[" + number + "]' id='emailplus' /><a href='#' class='prev_dom_delete'><img src='/img/x3.jpg' alt=''  /></a></td></tr>\n");
	return false;						  
});

//$("#last_scitata").click(function(){
////var scitata = $("div.hidden_val").html();
//////$("#text").empty().append(scitata + "\n \n");
//////$("#text").append(scitata);
////$("#text").val($("#text").val() + scitata );
//
//return false;
//});

if($("#ajax_history").length){

	$("div.ajax_head a, div.ajax_bottom a").live('click', function(){
	
	var k = $(this).attr("href");
	var page_id = k.replace(/\/mymessage\/onemessagerespond\//g, "");
	page_id = page_id.replace(/http:\/\/localhost/g, "");
	page_id = page_id.replace(/http:\/\/univer1.coav.ru/g, "");
	var recepient_id = $("#recepient_id").attr("value");
        var action_name = $("#action_id").text();
	//alert(page_id);
	
	$.post('/mymessage/history_json/' + page_id ,{page_id:page_id, respond_id:recepient_id, action_id: action_name},function(dataArray) { 
	var searchDiv = $("#ajax_history");
	searchDiv.text("");
	searchDiv.empty().append(dataArray);
	}, "html");										 
	
	
	return false;
	
	});
}

$("#hidden_history").click(function(){
	if($("#ajax_history").hasClass("hidden_val")){
                        
			$("#ajax_history").removeClass("hidden_val");
                        $(this).text('[ Скрыть историю сообщений ]');
		}else{
					$("#ajax_history").addClass("hidden_val");
                                        $(this).text('[ Показать историю сообщений ]');
			}							
	return false;
});

//$("div.ajax_left_block a").live("click", function(){
//	var scitata	= $(this).next("div").html();
//	$("#text").empty().append(scitata + "\n <br>");
//	return false;
//});


	$(function(){
	  $("#avatar_error").dialog({
		modal: ["true"],
		width: 220,
		height: 40,
		autoOpen: false,
   buttons: {

      "ОК": function() {
        $(this).dialog("close");
      }
   }
	  });
	  $("#frameavatar, #socavatar").click(function(){
		$("#avatar_error").dialog("open");
		return false;
	  });
	  $(this).click(function(){
		$(this).dialog("close");
	  });
	});	
	
	
	$(function(){
	  $("#avatar_dialog").dialog({
		modal: ["true"],
		width: 300,
		height: "auto",
		autoOpen: true,
   buttons: {

      "ОК": function() {
        $(this).dialog("close");
      }
   }
	  });
	  $(this).click(function(){
		$(this).dialog("close");
	  });
	});	
	
	
	$(function(){
	  $("#fromphoto_to_avatar_error").dialog({
		modal: ["true"],
		width: 300,
		height: "auto",
		autoOpen: false,
   buttons: {

      "ОК": function() {
        $(this).dialog("close");
      }
   }
	  });
	  $("#fromphoto_to_avatar").click(function(){
		if($(this).attr("href")=="#"){
				$("#fromphoto_to_avatar_error").dialog("open");
				return false;			
			}

	  });
	  $(this).click(function(){
		$(this).dialog("close");
	  });
	});	
	
	
$("a.hideblock4").live("click",function(){
		
		var p = $(this).parent("div").parent("div");
		p.hide();
		p.next("div").show("normal");
		return false;
									 
});


$("a.hideblock5").live("click",function(){
		
		var p = $(this).parent("div").parent("div").parent("div");
		//p.css("display:none");
		p.hide();
		p.prev("div").show("normal");
		return false;
									 
});	


$("a.hideblock7").live("click",function(){
		//alert("fsdfsd");
		var p = $(this).parent("div").parent("div").parent("div");
		//p.css("display:none");
		p.hide();
		p.prev("div").show("normal");
		return false;
									 
});

if($("#error_report").length){

    var k=0;
    var input = $("#error_report button").parent("div.text_align_center").prev("input");
          $("span.error_report_span").each(function () {

              if(!$(this).hasClass('was')){
                   input.attr("value", input.attr("value") + $(this).attr('title') );
                  $(this).addClass('was');
              }

          });

}

	$(function(){
	  $("#idontneedthisgood").dialog({
		modal: ["true"],
		width: 610,

		autoOpen: false
	  });
	  $("a.yes_no_dialog").live("click",function(){
	  $("#idontneedthisgoodyes").attr("href", $(this).attr("href"));
	  //alert($(this).html());
	  //alert($("#idontneedthisgoodyes").attr("href"));
	  //alert($("span.good_type_id").attr("id"));
		$("#idontneedthisgood").dialog("open");
		return false;
	  });
	  $("#idontneedthisgoodno").click(function(){
		$("#idontneedthisgood").dialog("close");
	  });
	  $("#idontneedthisgoodyes").click(function(){

		$("#idontneedthisgood").dialog("close");
		return true;
	  });
	  $(this).click(function(){
		$(this).dialog("close");
		
	  });

	});	


       	$(function(){
	  $("#icantgetthisgood").dialog({
		modal: ["true"],
		width: 610,
                autoOpen: true
	  });

	  $("#icantgetthisgoodyes").click(function(){

		$("#icantgetthisgood").dialog("close");
		return true;
	  });
	  $(this).click(function(){
		$(this).dialog("close");

	  });

	});
 
        

if($("#form_pespond").length){
	
  jQuery("#form_pespond").validate({
	focusInvalid: false,
    focusCleanup: false,
	errorElement: "span",
 submitHandler: function(form) {form.submit();},
   
    rules: {		
       text: {
      	required: true,
      	minlength: 2,
      	maxlength: 2500

		}		
		
},
    messages: {

       text: { 
        required: "Введите текст сообщения",
        minlength: "Слишком короткое сообщение (менее 2-х символов)",
        maxlength: "Слишком длинное текстовое сообщение (более 2500-х символов)"
     }	  
}	
});
  
  }

if($("#respond").length){

  jQuery("#respond").validate({
	focusInvalid: false,
    focusCleanup: false,
	errorElement: "span",
 submitHandler: function(form) {form.submit();},

    rules: {
       text: {
      	required: true,
      	minlength: 2,
      	maxlength: 2500

		}

},
    messages: {

       text: {
        required: "Введите текст сообщения",
        minlength: "Слишком короткое сообщение (менее 2-х символов)",
        maxlength: "Слишком длинное текстовое сообщение (более 2500-х символов)"
     }
}
});

  }

  
if(jQuery("#arhive").length){

//ПОлучаем данные через ajax
$.post('/mypossib/archive',{id:10},function(dataArray) {
        //alert(dataArray);
jQuery("#arhive").append(dataArray);

}, "html");

 }
  
if(jQuery("#arhive").length){
    
    jQuery("#arhive div.pagination a").live('click',function(){

   var url = jQuery(this).attr("href");
//ПОлучаем данные через ajax
$.post(url,{id:10},function(dataArray) {
        //alert(dataArray);
jQuery("#arhive").empty().append(dataArray);

}, "html");
        return false;

    });
    
}



if(jQuery("#login_password").length){
    

	$.validator.addMethod("mydigits", function(value, element) {
				if(/^\d+$/.test(value)){var antidigit = false;}else{antidigit = true;}
				//alert(element.value);
			return this.optional(element) || antidigit;
		}, 'В этом поле должны быть  не только цифры, но и буквы !');
    
$.validator.addMethod("mydigitsnew", function(value, element) {
			if(/^[a-zA-Z0-9]+$/.test(value)){var antidigit = true;}else{antidigit = false;}
			//alert(element.value);
		return this.optional(element) || antidigit;
	}, 'В этом поле должны быть  только цифры и латинские буквы!');

//Обрабатываем работу со сменой логина и пароля
 jQuery("#login_password").validate({
	focusInvalid: false,
    focusCleanup: false,
	errorElement: "span",
 submitHandler: function(form) {
 
 	$.post('/data/ajax_validatepassword',{new_login:jQuery("#new_login").attr('value')},function(dataArray) {
		//alert(dataArray);
		if(dataArray == "yes"){
                    jQuery('#new_login_error').text('');
                    form.submit();
                    // alert("Yes");
			}else{
                            jQuery('#new_login_error').text('Данный логин уже занят. Попробуйте другой.');
                           // alert("Error");

                        }
	}, "json");
     

},

    rules: {

      new_login: {
	required: true,
      	minlength: 5,
      	maxlength: 20,
        mydigits: true,
        mydigitsnew: true
        },

      new_password: {
      	required: true,
      	minlength: 3,
      	maxlength: 20,
        mydigits: true,
        mydigitsnew: true
	},
      again_password: {
      	required: true,
      	minlength: 3,
      	maxlength: 20,
        equalTo: "#new_password",
        mydigits: true,
        mydigitsnew: true
	}
},
    messages: {

      new_login: {
	required: "Это поле является обязательным.",
        minlength: "Не менее 5 символов",
        maxlength: "Не более 20 символов"
      },
      new_password: {
        required: "Введите пароль",
        minlength: "Слишком короткий пароль (менее 3-х символов)",
        maxlength: "Слишком длинный пароль (более 20-х символов)"
      },
      again_password: {
        required: "Введите пароль",
        minlength: "Слишком короткий пароль (менее 3-х символов)",
        maxlength: "Слишком длинный пароль (более 20-х символов)",
        equalTo: "Пароли не совпадают"
      }      
      
}
});

}


if(jQuery("#fogetpassword").length){



//Обрабатываем работу со сменой логина и пароля
 jQuery("#fogetpassword").validate({
	focusInvalid: false,
        focusCleanup: false,
	errorElement: "span",
 submitHandler: function(form) { form.submit(); },

    rules: {

      user_email: {
	required: true,
        email: true
        }
},
    messages: {

      user_email: {
        required: "Вы не ввели E-mail<br/><br/>",
	email: "E-Mail введен некорректно<br/><br/>"
      }

}
});

}

//errorArray = new Array();

});



