$(document).ready(function(){

//	if($.browser.msie) {
//		if($.browser.version != "8.0") {
//			data = {};
//			openOverlayBox("browser", data, "");
//		}
//	}
//	
	var timer = null;
	$('#friend-menu').mouseenter(function () {
		var menu = $('#friend-menu .fall');
		menu.css('display', 'block');
		clearTimeout(timer);
	}).mouseleave(function () {
		timer = setTimeout("var menu = $('#friend-menu .fall');menu.css('display', 'none');", 100);
	});
	$('.iconify').each(function(index) {
		var timer = null;
		$(this).mouseenter(function () {
			var menu = $(this).children('.fall');
			menu.css('display', 'block');
			clearTimeout(timer);
		}).mouseleave(function () {
			var $this = $(this);  
			timer = setTimeout( function() {  
                $this.children('.fall').css('display', 'none');
            }, 100 );  
		});
		
		
	});

	$('#logout_hr').click(function(){
		url = "/action/logout/";
		$.get(
			url,
			null,
			function(res) {
				redirect("index");
			}, 
			"html"
		);
	});
	
	$( "#dasacucak_datepicker" ).datepicker({
			showOn: "button",
			buttonImage: "/static/images/fe/oragir_date.gif",
			buttonImageOnly: true,
			dateFormat: 'yy-mm-dd',
			onSelect: function(dateText, inst) {
				window.location = "/weeklygrades/?dw="+dateText;
			}

	});
	
	$(".subj_item").click(function() {
		subject_id = $(this).attr("subj");
		data = {"subject_id":subject_id};
		openOverlayBox("monthlyreview", data, "initMonthlyOverview");
	});
	
	$("#saleinit").click(function() {
		data = {};
		openOverlayBox("sale", data, "");
	});
	
	
	$('select#ct').change(getSubjects);
	$('select#st').change(getGroups);
	
	$('select#school_id').change(getClassesForSchool);
	
	$('.add_friend').click(function() {
		$.post(
			"/addToFriend/ajax/",
			{"userid": $(this).attr("userid")},
			function(res) {
				if(res && res.length>3) {
					openalertpopup(res);
				}
			},
			"html"
		);
		
	})	
	
	$('.add_gift').click(function() {
                var nur = 0;
                var duel = $(this).attr("duel");
                if($(this).attr("giftid") == 19){
                    nur = 1;
                    if($('#nurcount').val() <= 0 || parseInt($('#nurcount').val()) != $('#nurcount').val()){
                            openalertpopup('Ներմուծեք ճիշտ թիվ');
                            return 'adasdas';
                        }
                }
		$.post(
			"/addGift/ajax/",
			{"userid": $(this).attr("userid"),"giftid": $(this).attr("giftid"),"private": $('#privatecheck')[0].checked?1:0,"nur": nur? $('#nurcount').val():0},
			function(res) {
				if(res && res.length>3) {
                                        if(duel == "gift")
                                            openalertpopup(res,"/duel_lobby");
                                        else
                                            openalertpopup(res,$('#backtolist').attr('href'));
				}
			},
			"html"
		);
		
	})	
	$('.rand_group_images').each(function(index) {
		var mem_id = $(this).attr('memb');
		$(this).parent().hover(     function(){
				$("#rand_"+ mem_id).css('display','block');
				$("#rand_"+ mem_id+"_s").css('display','block');
			},function  (){
				$("#rand_"+ mem_id).css('display','none');
				$("#rand_"+ mem_id+"_s").css('display','none');
		});
	});
	// banner click counter
        $('#banner1_0').click(function() {
		addbannerclick("ashtarak");
	})
        $('#banner1_1').click(function() {
		addbannerclick("nur");
	})
        $('#banner2_0').click(function() {
		addbannerclick("vivacell");
	})
        $('#banner2_1').click(function() {
		addbannerclick("dasaran");
	})
        $('.iradarc_late,.iradardz_inside,.message_content').hover(  function () {
            $(this).find('.deleteconfirm').css('visibility','visible');
        },   function () {
            $(this).find('.deleteconfirm').css('visibility','hidden');
        })
	$('.snd_msg_frd').click(function() {
		data = {toid:$(this).attr("userid")};
		openOverlayBox("snd_msg_frd", data, "");
	})
	
	$('.snd_msg_frd1').click(function() {
		if($("input[name='user_nickname']").val().length <=3) 
		{
			openalertpopup("Ընտրեք կեղծանուն");
			return false;
		}									  	
		data = {toid:$(this).attr("userid")};
		openOverlayBox("snd_msg_frd", data, "");
	})	
	
	
	$('.com_form').submit(function(){
		cb = $("textarea[name='combody']", $(this)).val();
		actitemid = $("input[name='itemid']", $(this)).val();
		actitemtype = $("input[name='itemtype']", $(this)).val();
		comcont = $("div[foritem='"+actitemid+"']");
		if(cb.length > 2) {
            $('.com_form textarea').val('');//#combodyarea
			act = $(this).attr("action");
			$.post(
				act,
				{"combody": cb},
				function(res) {
					if(res) {
						if(actitemtype == "topic") {
							window.location = document.location;
						} else {
                             $('.likes_n_stuff').before(res);
						}
						if(actitemtype != "topic") {
							$('#comformcont'+actitemid).toggle();
						}
					}
				},
				"html"
			);
			
		}
		
		
		return false;
	});
	
        /// confirm
        $('.iradardz_inside .deleteconfirm,.iradarc_late .deleteconfirm,.iradarc_late .deleteAlbumPhoto').click(function(){
		var elem = $(this).closest('.iradarc_late').length ? $(this).closest('.iradarc_late') : $(this).closest('.iradardz_inside');
                var delfunc = $(this).attr('todo');
                var args = $(this).attr('arg');
                var type = $(this).attr('type');
                var exploded = args.split(',');
                if(type == 1){
                    exploded = args;
                }
		$.confirm({
			'title'		: 'Ցանկանու՞մ եք ջնջել',
			'message'	: 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
			'buttons'	: {
				'Այո'	: {
					'class'	: 'blue',
					'action': function(){
						elem.slideUp();
                                                window[delfunc](exploded);
					}
				},
				'Ոչ'	: {
					'class'	: 'gray',
					'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
				}
			}
		});
		
	});
        $('.delAlbum,.delFriend').click(function(){
                var delfunc = $(this).attr('todo');
                var id = $(this).attr('id');
                var gid = $(this).attr('gid');
		$.confirm({
			'title'		: 'Ցանկանու՞մ եք ջնջել',
			'message'	: 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
			'buttons'	: {
				'Այո'	: {
					'class'	: 'blue',
					'action': function(){
                                                if(delfunc == 'delAlbum'){
                                                    delAlbum(id);
                                                }
                                                else if(delfunc == 'delGroupAlbum'){
                                                    delGroupAlbum(id,gid);
                                                }
                                                else{
                                                    delFriend(id);
                                                }
					}
				},
				'Ոչ'	: {
					'class'	: 'gray',
					'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
				}
			}
		});
	});
        $('.message_content .deleteconfirm').click(function(){
		var elem = $(this).closest('.message_content');
                var delfunc = $(this).attr('todo');
                var id = $(this).attr('arg');
		$.confirm({
			'title'		: 'Ցանկանու՞մ եք ջնջել',
			'message'	: 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
			'buttons'	: {
				'Այո'	: {
					'class'	: 'blue',
					'action': function(){
                                                  elem.slideUp();
                                                   deletemessage(id);
					}
				},
				'Ոչ'	: {
					'class'	: 'gray',
					'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
				}
			}
		});
	});        
	$('.comformconttoggle').click(function(){
		elid = $(this).attr("tgl");
		$('#'+elid).slideToggle();
	});
	
	$('.gnahatel_butt_post').click(function(){
		sid = $(this).attr('postid');
		voval = $(this).attr('voval');
		if(sid) {
			$.post(
				"/action/rateMpost/",
				{"sid": sid},
				function(res) {
					if(res) {
						eval(res);
						if(res.responsecode == "1.101") {
							$('#r_'+sid).text(parseInt($('#r_'+sid).text())+parseInt(voval));
						}
					}
				},
				"html" 
			);
			
		}
                $('.gnahatel_butt_post').remove();
	});
	

         
	$('.report_butt_post').click(function(){
		if(confirm("•Հայտնի ստեղծագործությունից հատվածներ •կրկնօրինակումներ •անհարիր արտահայտություններ")) {
			sid = $(this).attr('postid');
			if(sid) {
				$.post(
					"/action/reportMpost/",
					{"sid": sid},
					function(res) {
						if(res) {
							eval(res);
							if(res.responsecode == "1.101") {
								$('.report_butt_post').remove();
							}
						}
					},
					"html"
				);
			}
		}
	});
        
        if($('#hoverallgrakan')){
            $('#hoverallgrakan').click(function(){$('#toggleallgrakan').slideToggle()});
        }
	

	
});

        function imageCroping(img, box){
			$('#avatar_img').click(function() 
			{
			  document.getElementById('upLoadCropBox').style.height = '600px'; 
			  document.getElementById('avatarPanel').style.display = 'none';  
			  document.getElementById('upLoadCropBox').style.display = ''; 
			});
            crRunning = true;
            var locx = $('#x1').val();
            var locy = $('#y1').val();
            var locw = $('#w').val();
            var loch = $('#h').val(); 

            proceedAjaxCall("../engine/libs/img_resize.php", "avatar="+img+"&x="+locx+"&y="+locy+"&w="+locw+"&h="+loch, callBack, 1);

            function callBack(responseTxt){
                //alert(responseTxt);
                $("#avatarpicture").src = responseTxt;
                $("#avatar_img").src = responseTxt;
                $("#"+box).style.display = 'none';
                $("#avatarPanel").style.display = 'block';
            }

         };
         function closeCrop(id){
                $('#avatar_img').click(function() 
                {
                  document.getElementById('upLoadCropBox').style.height = '600px'; 
                  document.getElementById('avatarPanel').style.display = 'none';  
                  document.getElementById('upLoadCropBox').style.display = ''; 
                });
                 var randomnumber = Math.floor(Math.random()*11)
                 document.getElementById("avatar_img").src = "/files/avatar/150x150/"+id+".jpg?"+randomnumber;
                 document.getElementById('upLoadCropBox').style.height = '0'; 
                 document.getElementById('avatarPanel').style.display = '';  
                 document.getElementById('upLoadCropBox').style.display = 'none';return false;
         }
         
        function groupimageCroping(img, box,type){
            var locx = $('#x1').val();
            var locy = $('#y1').val();
            var locw = $('#w').val();
            var loch = $('#h').val(); 
			
            if(type){
                var extension = img.substring(img.lastIndexOf('.')+1);
				if(extension !=$('#closegrouplogoext').val()){
					extension = $('#closegrouplogoext').val();
					img = img+"."+$('#closegrouplogoext').val();
					$("#group_img_post").val(img);
				}
                proceedAjaxCall("../engine/libs/img_resize.php", "group="+img+"&x="+locx+"&y="+locy+"&w="+locw+"&h="+loch+"&type="+extension, callBack, 1);
            }
            else{
                var extension = $('#closegrouplogoext').val()
                proceedAjaxCall("../engine/libs/img_resize.php", "group="+img+"."+$('#closegrouplogoext').val()+"&x="+locx+"&y="+locy+"&w="+locw+"&h="+loch+"&type="+$('#closegrouplogoext').val(), callBack, 1);
            }
            function callBack(responseTxt){
                $("#group_img").attr('src',responseTxt);
                if(!type)
                    $("#group_img_post").val(img+"."+extension);
                $("#"+box).hide();
                $("#upload").hide();
                $('#group_img_cont').show();
            }

         };
         function closegroupCrop(id,type){
             var randomnumber = Math.floor(Math.random()*11)
            if(type){
                 document.getElementById("group_img").src = "/files/groups/logo/100x100/"+id+"?"+randomnumber;
            }
            else{
                 document.getElementById("group_img").src = "/files/groups/logo/100x100/"+id+"."+$('#closegrouplogoext').val()+"?"+randomnumber;
                 $("#group_img_post").val(id+"."+$('#closegrouplogoext').val());
            }
                 document.getElementById('upLoadCropBox').style.height = '0'; 
                 $('#upload').hide();
                 $('#group_img_cont').show();
                 document.getElementById('upLoadCropBox').style.display = 'none';return false;
         }

 function setUserEmailAddressForActivate(elm){
    var email = elm.value;

    $.post(
        "/action/setUserEmailAddressForActivate/",
        {"email": email},
        function(res) { 
            eval(res);
            if(res.returncode == "1.201") {
                document.getElementById("emailBlock").innerHTML = "Խնդրում ենք հաստատել Ձեր Էլ. հասցեին եկած հաղորդագրությունը:";
            }
        },
        "json"
    );
        
 };

function getClassesForSchool() {
	sid = $('select#school_id').val();
	if(sid) {
		$.post(
			"/classesList/ajax/",
			{"school_id": sid},
			function(res) {
				if(res) {
					$('select#class_id').html(res);
//                                        if($'.grp_inv_class')
				}
			},
			"html"
		);
		
	}
}
function getUsersForClass() {
	cid = $('select#class_id').val();
	if(cid) {
		$.post(
			"/classUsersList/ajax/",
			{"class_id": cid},
			function(res) {
				if(res) {
					$('#class_users_cont').html(res);
//                                        if($'.grp_inv_class')
				}
			},
			"html"
		);
		
	}
}
function openWarningForNotUpdateUser() {
	$('#grades_warning').css("display", "block");
}
function guestAlert() {
	openalertpopup("Ներողություն, Դուք գտնվում եք հյուրի կարգավիճակում:");
	return false;
}
function groupguestAlert() {
	openalertpopup("Այս ֆունկցիան հասանելի է միայն խմբի անդամների համար:");
	return false;
}
/*
function checkMargeUser()
{
	schollId = $("#school_id").val();
	classId = $("#class_id").val();
	
		if(!schollId || schollId == 0){
			alert("Ընտրեք Ձեր դպրոցը");
			return false;
		}
		if(!classId || classId == 0){
			alert("Ընտրեք Ձեր դասարանտը");
			return false;
		}
		
	$.post(
		"/checkMargeUser/ajax/",
		{"schollId": schollId, "classId":classId},
		function(res) {
			if(res) {
				//res = res.substr(2);
				if(res == "wrong")
				{
					alert("Դուք ընտրել եք սխալ դպրոց / դասարան, կամ Ձեր դպրոցի թարմացված տվյալները դեռ չեն մուտքագրվել համակարգ:\n\rԽնդրում ենք վերստին փորձել Ձեզ տրամադրվելիք նոր քարտերը ստանալուց հետո:");
					return false;
				}
				else
				{
					alert("Փոփոխությունները կատարված են\n\r Խնդրում ենք այսուհետ օգտվել է dasaran.am -ի կողմից տրամադրված նոր ծածկանուն և ծածկագրերով:");
					window.location.reload();
				}
			}
		},
		"html"
	);
}*/
function checkMargeUser()
{
	oldUsername = $("#oldUsername").val();
	oldPassword = $("#oldPassword").val();
	old_user = $("#old_user").length? $("#old_user").val() : 0;
	$("#mergeSubmit").attr('onClick','javascript:void(0);');
		if(!oldUsername){
			openalertpopup("Նշեք Ձեր հին ծածկանունը");
			return false;
		}
		if(!oldPassword){
			openalertpopup("Նշեք Ձեր հին ծածկագիրը");
			return false;
		}
	$.post(
		"/action/checkMargeUser/",
		{"oldUsername": oldUsername, "oldPassword":oldPassword, "old_user":old_user},
		function(res) {
            eval(res);
			if(res) {
				//res = res.substr(2);
				if(res.responsecode == '2.201')
				{
					openalertpopup("Դուք նշել եք  սխալ ծածկանուն / ծածկագիր:");
					$("#mergeSubmit").attr('onClick','checkMargeUser();');
					return false;
				}
				else
				{
                                        if(res.responsecode == '1.102'){
                                            url = "/action/logout/";
                                            $.get(
                                                    url,
                                                    null,
                                                    function(res) {
                                                            openalertpopup("Հարգելի՛ Բաժանորդ, Ձեր տվյալները հաջողությամբ զուգակցված են: Խնդրում ենք նորից մուտք գործել համակարգ` հավագելով Ձեր նոր քարտի տվյալները: Հարգանքով`Dasaran.am","/index");
                                                    }, 
                                                    "html"
                                            
                                            );
                                        }
                                        else
                                        {
                                            
                                            url = "/action/logout/";
                                            $.get(
                                                    url,
                                                    null,
                                                    function(res) {
						    	    openalertpopup("Փոփոխությունները կատարված են:\n\r Խնդրում ենք այսուհետ օգտվել dasaran.am -ի կողմից տրամադրված նոր ծածկանուն և ծածկագրերով:","/index");
                                                    }, 
                                                    "html"
                                            );
                                        }

				}
			}
		},
		"html"
	);
}
function initStatusUploads() {
	var uploader1 = new qq.FileUploader({
	    element: document.getElementById('stbrowse1'),
	    action: '/uploadPostPhoto/ajax/',
	    allowedExtensions: ['jpg', 'png', 'gif'],
	    sizeLimit: 2097152,
	    debug: false,
	    onComplete: function(id, fileName, responseJSON){
	    	if(responseJSON.success == true) {
	    		if(responseJSON.photo_id) {
	    			$("input[name='post_image_id']").val(responseJSON.photo_id);
	    			$("#stbrowse1").remove();
	    			$("input.add_photo_dropd02").remove(); // height='100'
	    			$(".images_sect").css("margin", "0").append("<img src='/files/posts/100x100/"+responseJSON.filename+"' width='100' id='"+responseJSON.fn+"' /><br /><a href='javascript:void(0);' class='' id='a_"+responseJSON.fn+"' onclick='deletePostPhoto(\""+responseJSON.fn+"\")'>Ջնջել</a>");
	    		}
	    	}
	    }
	});
}

function initAlbumPhotoUploads() {
	var photofile = new qq.FileUploader({
	    element: document.getElementById('photoup1'),
	    action: '/uploadAlbumPhoto/ajax/',
	    allowedExtensions: ['jpg', 'png', 'gif'],
	    sizeLimit: 2097152,
	    debug: false,
	    onComplete: function(id, fileName, responseJSON){
	    	if(responseJSON.success == true) {
	    		if(responseJSON.photo_id) {
	    			$("ul.qq-upload-list").html(" "); //height='100'
	    			$("#uploaded_photos").css("margin-top", "15px").append("<div id='item_"+responseJSON.fn+"' class='album_photo_item_cnt'><div class='album_photo_item_cnt_img'><img src='/files/albums/100x100/"+responseJSON.filename+"' width='100' id='"+responseJSON.fn+"' /></div><a href='javascript:void(0);' class='' id='a_"+responseJSON.fn+"' onclick='deleteAlbumPhoto(\""+responseJSON.photo_id+"\", \"item_"+responseJSON.fn+"\")'>Ջնջել</a></div>");
	    		}
	    	}
	    }
	});
	return photofile;
}


function initHistoryPhotoUploads() {
	var photofile = new qq.FileUploader({
	    element: document.getElementById('photoup_his'),
	    action: '/uploadHistoryPhoto/ajax/',
	    allowedExtensions: ['jpg', 'png', 'gif'],
	    sizeLimit: 2097152,
	    debug: false,
	    onComplete: function(id, fileName, responseJSON){
	    	if(responseJSON.success == true) {
	    		if(responseJSON.photo_id) {
//	    			$("input[name='up_history_pic']").val(responseJSON.filename);
                                $("input[name='up_history_pic']").css("display", "none");
                                $("#photoup_his").css("display", "none");
	    			$("ul.qq-upload-list").html(" ");//height='100'
	    			$("#uploaded_photos").css("margin-top", "15px").append("<div id='item_"+responseJSON.fn+"' class='album_photo_item_cnt'><img src='/files/photos/100x100/"+responseJSON.filename+"' width='100' id='"+responseJSON.fn+"' /><input name='up_file_name' type='hidden' value='"+responseJSON.filename+"'></div>");
	    		}
	    	}
	    }
	});
	return photofile;
}

//KAREN
function initPhotoContestUploads() {
	var photofile = new qq.FileUploader({
	    element: document.getElementById('photoup2'),
	    action: '/uploadPhotoContest/ajax/',
	    allowedExtensions: ['jpg', 'png', 'gif'],
	    sizeLimit: 2097152,
	    debug: false,
	    onComplete: function(id, fileName, responseJSON){
	    	if(responseJSON.success == true) {
	    		if(responseJSON.photo_id) {
	    			//$("input[name='post_image_id']").val(responseJSON.photo_id);
	    			$("ul.qq-upload-list").html(" ");//height='100'
	    			$("#uploaded_photos").css("margin-top", "15px").append("<div id='item_"+responseJSON.fn+"' class='album_photo_item_cnt'><img src='/files/albums/100x100/"+responseJSON.filename+"' width='100'  id='"+responseJSON.fn+"' /><br /><a href='javascript:void(0);' class='' id='a_"+responseJSON.fn+"' onclick='deleteAlbumPhoto(\""+responseJSON.photo_id+"\", \"item_"+responseJSON.fn+"\")'>Ջնջել</a></div>");
	    		}
	    	}
	    }
	});
	return photofile;
}


function likeit(itemtype, itemid, el) {
			$.post(
				"/action/likeit/",
				{"itemtype": itemtype, "itemid":itemid},
				function(res) {
					if(res) {
						eval(res);
						code = res.responsecode.split("\.");
						if(code[0]==1 && (code[1]==101)) {
							cntr = $("b#"+itemtype+"_"+itemid+"_lc");
							cntr.html(parseInt(cntr.html())+1);
							$("span#"+itemtype+"_"+itemid+"_lb").remove();
							
						}
						if(code[0]==1 && (code[1]==103)) {
                                                    window.location = document.location;
                                                }
					}
				},
				"html"
			);
	
}
function likeitHog(itemtype, itemid, el) {
			$.post(
				"/action/likeit/",
				{"itemtype": itemtype, "itemid":itemid},
				function(res) {
					if(res) {
						eval(res);
						code = res.responsecode.split("\.");
						if(code[0]==1 && (code[1]==101)) {
							cntr = $("b#"+itemtype+"_"+itemid+"_lc");
							cntr.html(parseInt(cntr.html())+1);
							$("span#"+itemtype+"_"+itemid+"_lb").removeClass("hogeban_harc_like").addClass("hogeban_harc_like_i");
							
						}
					}
				},
				"html"
			);
}
function redirecttolist(month,day){
    location.href = '/patmakan/'+month+'/'+day;
}
function getSubjects(){
	ct = $('select#ct').val();
	data = {
		"class_id" : $('select#ct').val()
	};
	$.post(
		"/subjectTeacher/ajax/"+ct,
		data,
		function(res) {
			if(res) {
				$('select#st').html(res);
			}
		},
		"html"
	);
}

function getGroups(){
	st = $('select#st').val().split("-");
	data = {
		"class_id" : $('select#ct').val(),
		"subject_id" : st[0],
		"teacher_id" : st[1]
	};
	$.post(
		"/subjectGroup/ajax/",
		data,
		function(res) {
			if(res) {
				$('select#grouplist').html(res);
				if($('#grouplist option').size()>1) {
					$('#group_block').show();
				}
			}
		},
		"html"
	);
}






function openGradeForMonth(dt) {
	data = {"fordate":dt};
	openOverlayBox("grade", data, "initSingleGrade('"+dt+"');");
}
function validatematyanparams(f) {
	err = 0;
	$("label").css('color', '#000');
	if(parseInt($("select[name='ct']").val()) < 1) {
		$("label[forelem='ct']").css('color', '#F00');
		err = 1
	}
	if(parseInt($("select[name='st']").val()) < 1) {
		$("label[forelem='st']").css('color', '#F00');
		err = 1;
	}
	if(parseInt($("select[name='fordate']").val()) < 1) {
		$("label[forelem='fordate']").css('color', '#F00');
		err = 1;
	}
	if(!err) {
		data = {
			"class_id":$("select[name='ct']").val(),
			"st":$("select[name='st']").val(),
			"group_name":$("#grouplist").val(),
			"fordate":$("select[name='fordate']").val()
		}
		return data;
	}
	return !err;
}

function aftersubmitmatyanparams(f, res) {
	code = res.responsecode.split("\.");
	if(code[0] > 1) {
		$('div.output').html(res.message);
	}
	if(code[0]==1 && (code[1]==101 || code[1]==103)) {
		redirect("progress");
	}
}

function validatgroupparams(){
	err = 0;
	if($("input[name='group_name']").val().length <=3 || $("input[name='group_name']").val().length >=30) {
		$("label[forelem='act_code']").css('color', '#F00');
		err = 1
	}
	if(!err) {
		document['create_group_form'].submit();
	}
}

function validateActivation(f) {
	err = 0;
	if($("input[name='act_code']").val().length <=3) {
		$("label[forelem='act_code']").css('color', '#F00');
		err = 1
	}
	if($("select[name='month']").val().length<1) {
		$("label[forelem='month']").css('color', '#F00');
		err = 1;
	}
	if(!err) {
		data = {
			"act_code":$("input[name='act_code']").val(),
			"month":$("select[name='month']").val()
		}
		return data;
	}
	return !err;
}

function afterActivation(f, res) {
	code = res.responsecode.split("\.");
	if(code[0] > 1) {
		$('div.output').html(res.message);
	}
	if(code[0]==1 && (code[1]==101 || code[1]==103)) {
		redirect("progress");
	}
}

function validateProfile(f) {
	err = 0;
	if($("input[name='first_name']").val().length <1) {
		err = 1
	}
        // check me
//	if($("input[name='middle_name']").val().length <1) {
//		err = 1
//	}
	if($("input[name='last_name']").val().length <=1) {
		err = 1
	}
	if(!$("select[name='gender']").val()) {
		err = 1;
	}
	if(!parseInt($("select[name='b_month']").val())) {
		err = 1;
	}
	if(!parseInt($("select[name='b_day']").val())) {
		err = 1;
	}
	if(!parseInt($("input[name='b_year']").val()) || parseInt($("input[name='b_year']").val())>2007) { /* || parseInt($("input[name='b_year']").val()) < 1990 */
		err = 1;
	}
	if(err) {
		$('.err').css("display", "block");
		return false;
	} else {
		$('#profileform').submit();
		//data = $(f).serialize();
		return data;
	}
}
function validateNewPassword(f) {
	err = 0;
	if($("input[name='old_password']").val().length <=3) {
		openalertpopup("Մինիմալը 4 նիշ");
		err = 1
		return false;
	}
	if($("input[name='new_password']").val().length <=3) {
		openalertpopup("Մինիմալը 4 նիշ");
		err = 1
		return false;
	}
	if($("input[name='re_new_password']").val().length <=3) {
		openalertpopup("Մինիմալը 4 նիշ");
		err = 1
		return false;
	}
	if($("input[name='re_new_password']").val() != $("input[name='new_password']").val()) {
		openalertpopup("Մուտքագրեք նույն ծածկագիրը"); 
		err = 1
		return false;
	}
	
	if(err) {
		$('.err').css("display", "block");
		return false;
	} else {
		$('#userNewPassword').submit();
		return true;
	}
}
function validateNewUsername(f) {
	err = 0;
	if($("input[name='new_username']").val().length <=3) {
		openalertpopup("Մինիմալը 4 նիշ");
		err = 1
		return false;
	}
	if($("input[name='re_new_username']").val().length <=3) {
		openalertpopup("Մինիմալը 4 նիշ");
		err = 1
		return false;
	}
	if($("input[name='new_username']").val() != $("input[name='re_new_username']").val()) {
		openalertpopup("Մուտքագրեք նույն ծածկանունը");
		err = 1
		return false;
	}
	
	if(err) {
		$('.err').css("display", "block");
		return false;
	} else {
		$('#newUsername').submit();
		return true;
	}
}
function validateForgetForm() {
	err = 0;
	if($("input[name='usernameF']").val().length <=3) {
		openalertpopup("Մինիմալը 4 նիշ");
		err = 1
		return false;
	}
	if($("input[name='emailF']").val().length <=3) {
		openalertpopup("Մինիմալը 4 նիշ");
		err = 1
		return false;
	}
	$.post(
		"/action/sendPassword/",
		{"emailF": $("input[name='emailF']").val(),"usernameF": $("input[name='usernameF']").val()},
		function(res) {
			eval(res);
			if(res.message == "wrong") {
				openalertpopup("Սխալ ծածկանուն կամ էլ.փոստ.");
			}
			else
			{
				openalertpopup("Ձեր նոր ծածկագիրն ուղարկված է նշված էլ. հասցեին.");
				window.location.reload();
				//window.location = "index";
			}
		},
		"html"
	);
}


function afterSaveProfile(f, res) {
	code = res.responsecode.split("\.");
	if(code[0] > 1) {
		$('div.err').html(res.message);
		$('div.err').css("display", "block");
	}
	if(code[0]==1 && code[1]==101) {
		//window.location = document.location;
	}
}




function openOverlayBox(pagename, data, callAfter) {
	genhtml = '<div class="overlay"></div>';
	$('BODY').append(genhtml);
	$('.overlay').click(function(){
		//close_box();
	})
	genhtml = '<div id="dasBoxWrapper" class="dasboxwrapper"><div class="dasbox"><div class="dasboxtitle" style="text-align:center;"><span class="obtitle" style="margin-left:0 ! important; display:inline; float:none;"></span>';
   	genhtml += '<a href="javascript:close_box()"><img src="/static/images/be/close.jpg" id="close_btn" \></a>';
	genhtml += '</div><div style="clear:both"></div><div class="dasboxcont"></div></div></div>';
    $('body').append(genhtml);
    w = $(window).scrollTop();
    if(pagename == "grade") {
    	ws = $(window).width();
    	if(ws>1300) {
    		leftalg = (ws-1300)/2;
    	} else {
    		leftalg = 0;
    	}
    	$("#dasBoxWrapper").css("width", "1300px").css("left", leftalg+"px").css("top", w+20+"px");
    	//$("#dasBoxWrapper span.obtitle").css("margin-left", "457px");
    } else if (pagename == "monthlyreview") {
    	ws = $(window).width();
    	if(ws>300) {
    		leftalg = (ws-300)/2;
    	} else {
    		leftalg = 0;
    	}
    	$("#dasBoxWrapper").css("position", "absolute").css("width", "500px").css("left", leftalg+"px").css("top", w+20+"px");
    } else if (pagename == "sale") {
    	ws = $(window).width();
    	if(ws>420) {
    		leftalg = (ws-420)/2;
    	} else {
    		leftalg = 0;
    	}
    	$("#dasBoxWrapper").css("position", "absolute").css("width", "420px").css("left", leftalg+"px").css("top", w+20+"px");
    } else if (pagename == "browser") {
    	ws = $(window).width();
    	if(ws>420) {
    		leftalg = (ws-420)/2;
    	} else {
    		leftalg = 0;
    	}
    	$("#dasBoxWrapper").css("position", "absolute").css("width", "420px").css("left", leftalg+"px").css("top", w+20+"px");
    } else if(pagename == "grade_d") {
    	ws = $(window).width();
    	if(ws>1400) {
    		leftalg = (ws-1400)/2;
    	} else {
    		leftalg = 0;
    	}
    	$("#dasBoxWrapper").css("width", "1400px").css("left", leftalg+"px").css("top", w+20+"px");
    	$("#dasBoxWrapper span.obtitle").css("margin-left", "457px");
    } else if(pagename == "snd_msg_frd") {
    	ws = $(window).width();
    	if(ws>605) {
    		leftalg = (ws-605)/2;
    	} else {
    		leftalg = 0;
    	}
    	$("#dasBoxWrapper").css("width", "465px").css("left", leftalg+"px").css("top", w+250+"px");
    	$("#dasBoxWrapper span.obtitle").css("margin-left", "470px");
    	$("#dasBoxWrapper div.dasboxcont").css("padding", "0px").css("background", "transparent");
    	$("#dasBoxWrapper div.dasboxtitle").css("display", "none");
    }
    url = '/popups/ajax/?pagename='+pagename;
    $.post(
		url,
		data,
		function(res) {
			$('.dasboxcont').append(res);
			if(callAfter.length) {
				if(callAfter.indexOf(";") == -1) {
					callAfter += "(res);";
				}
				eval(callAfter);
			}
		}, 
		"html"
	);
}

function close_box() {
	$('.overlay').remove();
	$('#dasBoxWrapper').remove();
}

function initSingleGrade(dt) {
	dt = dt+'-01';
	t = dt.split("-");
	d = new Date(t[0],t[1],t[2]);
	var mn = new Array();
	mn[1] = "Հունվար";
	mn[2] = "Փետրվար";
	mn[3] = "Մարտ";
	mn[4] = "Ապրիլ";
	mn[5] = "Մայիս";
	mn[6] = "Հունիս";
	mn[7] = "Հուլիս";
	mn[8] = "Օգոստոս";
	mn[9] = "Սեպտեմբեր";
	mn[10] = "Հոկտեմբեր";
	mn[11] = "Նոյեմբեր";
	mn[12] = "Դեկտեմբեր";
	mn[0] = "Դեկտեմբեր";
	ind = parseInt(d.getMonth());
	$("#dasBoxWrapper span.obtitle").html(mn[ind]+" ամսվա դասամատյան");
}

function initMonthlyOverview() {}

function validatefrdmsg(f) {
	err = 0;
	/*if($("textarea[name='msgbody']").val().length <=3) {
		$("label[forelem='msgbody']").css('color', '#F00');
		err = 1;
	}
	if($("input[name='msgsbj']").val().length<1) {
		$("label[forelem='msgbody']").css('color', '#F00');
		err = 1;
	}*/
    if($("textarea[name='msgbody']").val().length<1) {
        $("label[forelem='msgbody']").css('color', '#F00');
        err = 1;
    }
	if(!err) {
		data = {
			//"msgbody":$("textarea[name='msgbody']").val(),
			//"msgsbj":$("input[name='msgsbj']").val(),
            "msgbody":$("textarea[name='msgbody']").val(),
			"to":$("input[name='to']").val()
		}
        if(document.getElementById('loadIndicator'))
            document.getElementById('loadIndicator').style.display = "";
        //$('div.outputSent').html("Loading...");
		return data;
	}
	return !err;
}

function afterSendfrdmsg (f, res) {
	code = res.responsecode.split("\.");
   // $('div.outputSent').html("");
   // document.getElementById('loadIndicator').style.display = "";
    
    $('div.output').html(""); 
    if(code[0] == 1) {
       $('div.outputSent').html(res.message);
        $('div.outputSent').className = "";
         if(document.getElementById('outputSent')){
           document.getElementById('outputSent').className = ""; 
           document.getElementById('outputSent').id = ""; 
        }
        //document.getElementById('msgsbj').value = "";
        if(document.getElementById('msgbody'))
        document.getElementById('msgbody').value = "";
	close_box();
    } else
	if(code[0] > 1) {
		$('div.output').html(res.message);
	}
	if(code[0]==1 && code[1]==101) {
		close_box();
	}
}

function validatePost(f) {
	err = 0;
	if(($("input[name='post_title']").val().length <=3) && ($("textarea[name='post_body']").val() < 3)) {
		//$("label[forelem='post_title']").css('color', '#F00');
		err = 1
	}
	if(!err) {
		data = {
			"post_title":$("input[name='post_title']").val(),
			"post_body":$("textarea[name='post_body']").val(),
			"post_image_id":$("input[name='post_image_id']").val(),
			"privacy":$("input[name='privacy']").val()
		}
		return data;
	}
	return !err;
}

function validateGroupPost(f) {
	err = 0;
	if(($("input[name='post_title']").val().length <=3) && ($("textarea[name='post_body']").val() < 3)) {
		//$("label[forelem='post_title']").css('color', '#F00');
		err = 1
	}
	if(!err) {
		data = {
			"post_title":$("input[name='post_title']").val(),
			"post_body":$("textarea[name='post_body']").val(),
			"group_id":$("input[name='group_id']").val(),
			"post_image_id":$("input[name='post_image_id']").val(),
			"post_image_id":$("input[name='post_image_id']").val()
		}
		return data;
	}
	return !err;
}

function afterSavePost (f, res) {
	code = res.responsecode.split("\.");
	if(code[0] > 1) {
		$('div.output').html(res.message);
	}
	if(code[0]==1 && code[1]==101) {
		redirect("wall");
	}
}

function afterSaveGroupPost (f, res) {
	code = res.responsecode.split("\.");
	if(code[0] > 1) {
		$('div.output').html(res.message);
	}
	if(code[0]==1 && code[1]==101) {
        	window.location = document.location;
	}
}

function validateMPost(f) {
	err = 0;
	if(($("textarea[name='mpost_body']").val() < 3)) {
		//$("label[forelem='post_title']").css('color', '#F00');
		err = 1
	}
	if(!err) {
		data = {
			"post_body":$("textarea[name='mpost_body']").val(),
			"posttype":$("input[name='mposttype']").val()
		}
                if($("input[name='mposttype']").val() == 'dickens'){
                    data = {
                            "post_body":$("textarea[name='mpost_body']").val(),
                            "posttype":$("input[name='mposttype']").val(),
                            "post_title":$("input[name='mposttitle']").val(),
                            "post_mobile":$("input[name='mpostmobile']").val()
                    }
                }
		return data;
	}
	return !err;
}

function afterSaveMPost (f, res) {
	code = res.responsecode.split("\.");
	if(code[0] > 1) {
		$('div.output').html(res.message);
	}
	if(code[0]==1 && code[1]==101) {
                if($("input[name='mposttype']").val() == 'dickens')
                    redirect($("input[name='mposttype']").val()+"/");
                else
                    redirect("grakan/"+$("input[name='mposttype']").val()+"/");
	}
	if(code[0]==1 && code[1]==111) {
                $('#add_new_mpost').slideToggle();
        	openalertpopup("Շնորհակալություն, Ձեր աշխատանքը մուտքագրված է:\r\n Dasaran.am-ի պատասխանատու անձնակազմի կողմից վերանայվելուց հետո այն կտեղադրվի կայքում:",'/dickens/');
	}
}

function validateFPost(f) {
	err = 0;
	if(($("textarea[name='fpost_body']").val() < 3) || ($("input[name='fpost_title']").val() < 3)) {
		$("label[forelem='fpost_title']").css('color', '#F00');
		err = 1
	}
	if(!err) {
		data = {
			"post_title":$("input[name='fpost_title']").val(),
			"post_body":$("textarea[name='fpost_body']").val(),
			"posttype":"ftopic"
		}
		return data;
	}
	return !err;
}

function afterSaveFPost (f, res) {
	code = res.responsecode.split("\.");
	if(code[0] > 1) {
		$('div.output').html(res.message);
	}
	if(code[0]==1 && code[1]==101) {
		redirect("forum");
	}
}


function validateAlbum(f) {
	err = 0;
	if($("input[name='album_title']").val().length <=3) {
		$("label[forelem='album_title']").css('color', '#F00');
		err = 1
	}
	if(!err) {
		data = {
			"album_title":$("input[name='album_title']").val()
		}
		return data;
	}
	return !err;
}

function afterSaveAlbum (f, res) {
	code = res.responsecode.split("\.");
	if(code[0] > 1) {
		$('div.output').html(res.message);
	}
	if(code[0]==1 && code[1]==101) {
		redirect("photoalbum");
	}
}
     
function delAlbum(id) {
            $.post(
                    "/action/deleteAlbum/",
                    {"album_id":id},
                    function(res) {
                            eval(res);
                            code = res.responsecode.split("\.");
                            if(code[0] > 1) {
                                    $('div.output').html(res.message);
                            }
                            if(code[0]==1 && code[1]==101) {
                                    redirect("photoalbum");
                            }
                    }, 
                    "html"
            );	
}
function delGroupAlbum(id,gid) {
            $.post(
                    "/action/deleteGroupAlbum/",
                    {"album_id":id,"group_id":gid},
                    function(res) {
                            eval(res);
                            code = res.responsecode.split("\.");
                            if(code[0] > 1) {
                                    $('div.output').html(res.message);
                            }
                            if(code[0]==1 && code[1]==101) {
                                    window.location = document.location;
                            }
                    }, 
                    "html"
            );	
}
function deletemessage(id) {
            $.post(
                    "/action/deleteMessage/",
                    {"message_id":id},
                    function(res) {
                            eval(res);
                            code = res.responsecode.split("\.");
                            if(code[0] > 1) {
                                    $('div.output').html(res.message);
                            }
                            if(code[0]==1 && code[1]==101) {
                                    openalertpopup(res.message);
                            }
                    }, 
                    "html"
            );	
}

function delFriend(id) {
            $.post(
                    "/action/deleteFriend/",
                    {"friend_id":id},
                    function(res) {
                            eval(res);
                            code = res.responsecode.split("\.");
                            if(code[0] > 1) {
                                    $('div.output').html(res.message);
                            }
                            if(code[0]==1 && code[1]==101) {
                                    redirect("friends");
                            }
                    }, 
                    "html"
            );	
}

function confirmhis() {
    var yearval = $("input[name='year0']").val();
    if(!is_int(parseInt($("input[name='year0']").val())))
        yearval = 3000;
	$.post(
		"/userinputhistory/ajax/",
		{"user_name":$("input[name='user_name']").val(),"user_password":$("input[name='user_password']").val()
                    ,"day":$("input[name='day']").val(),"months":$("#monthssel").val(),"body0":$("#body0").val(),"year0":yearval,'source':$("input[name='source']").val(),'up_file_name':$("input[name='up_file_name']").val()},
		function(res) {
                    eval(res)
        		openalertpopup("Շնորհակալություն, Ձեր տեղեկատվությունը մուտքագրված է:\r\n Dasaran.am-ի պատասխանատու անձնակազմի կողմից վերանայվելուց հետո այն կտեղադրվի կայքում:");
                    if(res.type == 1 ){
                        $('#add_new_history').slideToggle();
                    }
		}, 
		"json"
	);	
    $('#previewhis').hide();
    $('#previewhisbg').hide();
}

function stilledit() {
    $('#previewhis').hide();
    $('#previewhisbg').hide();
}
 function is_int(input){
    return typeof(input)=='number'&&parseInt(input)==input;
  }

function validhistoryparams(f) {
	err = 0;
	$("label").css('color', '#000');
	if(!is_int(parseInt($("input[name='day']").val())) || parseInt($("input[name='day']").val()) < 1) {
		$("label[forelem='day']").css('color', '#F00');
		err = 1;
	}
	if($("#body0").val() < 1) {
		$("label[forelem='body0']").css('color', '#F00');
		err = 1;
	}
	if($("#user_password").val() < 1) {
		$("label[forelem='user_password']").css('color', '#F00');
		err = 1;
	}
	if($("#user_name").val() < 1) {
		$("label[forelem='user_name']").css('color', '#F00');
		err = 1;
	}
	if(!err) {
		data = {
			"class_id":$("input[name='day']").html(),
			"st":$("#body0").val()
		}
		return data;
	}
	return !err;
}

function saveHistory(form) {
    if(validhistoryparams(form)){
        $('#previewhis').show();
        $('#previewhisbg').show();
        if($("input[name='up_file_name']").val())
            $('#previmage').attr('src',"/files/photos/100x100/"+$("input[name='up_file_name']").val()+"");
        else{
            $('#previmage').attr('src','/files/photos/100x100/default_patmakan.jpg');
        }
    //    {if $event.year|string_format:"%d" < 2999}{$event.year} թիվ {/if} {$sendmonth} {$day}
        var months = ["Հունվարի","Փետրվարի","Մարտի","Ապրիլի","Մայիսի","Հունիսի","Հուլիսի","Օգոստոսի","Սեպտեմբերի","Հոկտեմբերի","Նոյեմբերի","Դեկտեմբերի","Դեկտեմբերի"];
        var yearstr = '';
        if(is_int(parseInt($("input[name='year0']").val())))
            yearstr = $("input[name='year0']").val()+" թիվ ";
        $('#eventheader').html(yearstr+months[$("#monthssel").val()]+" "+$("input[name='day']").val())
        $('#eventbody').html($("#body0").val())
    }
 }

function deletePostPhoto(id) {
	$('#'+id).remove();
	$('#a_'+id).remove();
	window.location = document.location;
	
}
function makeProfilePicture(id, fn){
	$.post(
		"/action/makeProfilePicture/",
		{"photo_id":id},
		function(res) {
			eval(res);
			code = res.responsecode.split("\.");
			if(code[0] > 1) {
				$('div.output').html(res.message);
			}
			if(code[0]==1 && code[1]==101) {
                                $("#avatarpicture").parent().html('<img width="150" height="150" id="avatarpicture" style="float:left" src="'+res.message+'?rid=' + Math.random()+'">');
//                             location.reload();

			}
		}, 
		"html"
	);	
}

function makeGiftPicture(id, fn){
    console.log(id);
    console.log(fn);
//	$.post(
//		"/action/makeProfilePicture/",
//		{"photo_id":id},
//		function(res) {
//		}, 
//		"html"
//	);	
}

function clickday(obj){
    if(obj.value=='Նշեք իրադարձության օրը')
    {
        obj.value='';
        obj.style.color='#000';
    }
}

function blurday(obj){
    if(obj.value=='')
    {
        obj.value='Նշեք իրադարձության օրը';
        obj.style.color='rgb(150, 150, 150)';
    }
}

function clickyear(obj){
    obj.style.color='#000';
    if(obj.value=='Նշեք իրադարձության տարին')
    {
        obj.value='';
        obj.style.color='#000';
    }
}

function bluryear(obj){
    if(obj.value=='')
    {
        obj.value='Նշեք իրադարձության տարին';
        obj.style.color='rgb(150, 150, 150)';
    }
}

function clicksource(obj){
    if(obj.value=='Նշեք ինֆորմացիայի աղբյուրը')
    {
        obj.value='';
        obj.style.color='#000';
    }
}

function blursource(obj){
    if(obj.value=='')
    {
        obj.value='Նշեք ինֆորմացիայի աղբյուրը';
        obj.style.color='rgb(150, 150, 150)';
    }
}

function deleteAlbumPhoto(id, fn,usrid) {
	$.post(
		"/action/deleteAlbumPhoto/",
		{"photo_id":id,'usrid':usrid},
		function(res) {
			eval(res);
			code = res.responsecode.split("\.");
			if(code[0] > 1) {
				$('div.output').html(res.message);
			}
			if(code[0]==1 && code[1]==101) {
				$("#"+fn).remove();
			}
		}, 
		"html"
	);	
}


function deleteItem(itemarray) {
        var itemtype = itemarray[0];
        var itemid = itemarray[1];
        $.post(
                "/action/delItem/",
                {"itemtype":itemtype, "itemid":itemid},
                function(res) {
                        eval(res);
                        code = res.responsecode.split("\.");
                        if(code[0] > 1) {
                                openalertpopup(res.message);
                        }
                        if(code[0]==1 && code[1]==101) {
                                $("div#"+itemtype+"_"+itemid).remove();
                        }
                }, 
                "html"
        );	
}

function addphotocomment(form){
    var action = form.action;
    var text = form.combody.value;
    $('.com_form textarea').val('');//#combodyarea
		$.post(
			action,
			{'combody':text},
			function(res) {
                                $('.likes_n_stuff').before(res);
			}, 
			"html"
		);	
}

function comet() {
	$.ajax({
		type : 'Get',
		url  : '/read.php?timestamp=' + timestamp,
		async : true,
		cache : false,
		
		success : function(data) {
					var json = eval('(' + data + ')');
					if(json['msg'] == ''){
						$('#msg').html('No msg');					
					}else { 
						$('#msg').html(json['msg']);
						$('#msg').animate({scrollTop: $('#msg').get(0).scrollHeight},200);
					}
					timestamp  = json['timestamp'];
					setTimeout('comet()', 1000);
		},
		error : function(XMLHttpRequest, textstatus, error) { 
					openalertpopup(error);
					setTimeout('comet()', 15000);
		}		
	});
}
function validateNickname(f) {
	if($("input[name='user_nickname']").val().length <=3) {
		$("label[forelem='user_nickname']").css('color', '#F00');
		openalertpopup("Մինիմալը 4 նիշ");
		return false;
	}
        if($("input[name='user_nickname']").val().length > 20) {
		$("label[forelem='user_nickname']").css('color', '#F00');
		openalertpopup("Մաքսիմում 20 նիշ");
		return false;
	}
	$.post(
		"/action/checkNickname/",
		{"nickname": $("input[name='user_nickname']").val()},
		function(res) {
			eval(res);
			if(res.message == "wrong") {
				openalertpopup("Այդպիսի կեղծանուն գոյություն ունի");
			}
			else
			{
				$.post(
					"/action/changeNickname/",
					{"user_nickname": $("input[name='user_nickname']").val()},
					function(res) {
						window.location.reload()	
					},
					"html"
				);
			}
		},
		"html"
	);
}
function openChatWin(id){
	$("#cometchat_userlist_"+id).click();	
}
function validateNicknameFotAddTopic() {
	$('#addforumbutt').attr('onClick','javascript:void(0);');
	if($("input[name='user_nicknameG']").val().length <=3) 
	{
        	$('#addforumbutt').attr('onClick','validateNicknameFotAddTopic();');
		openalertpopup("Ընտրեք կեղծանուն");
		return false;
	}
	else
	{
		document.newtopic.submit();
	}
}
function validateNicknameFotTopicComment() {
	if($("input[name='user_nicknameG']").val().length <=3) 
	{
		openalertpopup("Ընտրեք կեղծանուն");
		return false;
	}
	else
	{
		document.topicComment.submit();
		cb = $("textarea[name='combody']");
		cb.val('');
		return true;
	}
}

/*
function afterSaveNickname (f, res) {
	code = res.responsecode.split("\.");
	if($("input[name='type']").val() == "psyforum")
	{
			hoqeban_id = $("input[name='hoqeban_id']").val()
			if(code[0] > 1) {
				$('div.output').html(res.message);
			}
			if(code[0]==1 && code[1]==101) {
				redirect("psyforum/"+hoqeban_id);
			}
	}
	if($("input[name='type']").val() == "pystopic")
	{
			topic_id = $("input[name='topic_id']").val()
			if(code[0] > 1) {
				$('div.output').html(res.message);
			}
			if(code[0]==1 && code[1]==101) {
				redirect("psytopic/"+topic_id);
			}
	}
}
*/

function strpos (haystack, needle, offset) {
  var i = (haystack+'').indexOf(needle, (offset || 0));
  return i === -1 ? false : i;
}

function getmorepsycomments(){
   var page = $('.topic_comments_block').attr('val');
   var topic_id = $('.topic_comments_block').attr('foritem');
   var moder_id = $('.topic_comments_block').attr('moder');
   var reply = $('.topic_comments_block').attr('reply');
   $('#morepsycom').attr('onclick','javascript:void(0);');
   var action = '/action/psymorecomment/';
   $(".loadingduelIndicator").css("visibility", "visible");
   $.post(
           action,
           {'page':page,'topic_id':topic_id,'moder_id':moder_id,'reply':reply},
           function(res) {
               res = res.replace(/^\s+|\s+$/g, '') ;
               if(res){
                   var innerhtml = $(".topic_comments_block").html();
                   $(".topic_comments_block").html(res+innerhtml); 
                   $('#morepsycom').click(function() {getmorepsycomments();});
               }
               else{
                    $('#morepsycom').attr('onclick','javascript:void(0);');
               }
               $(".loadingduelIndicator").css("visibility", "hidden");
           },
           "html"
   );
}
function getmoreplayers(pagename){
   $('#duel_lobby_users').unbind('scroll',chk_scroll);
   var page = $('.lobby_list').attr('val');
   var action = '/getmoreusers/ajax/';
   $(".loadingduelIndicator").css("visibility", "visible");
   $.post(
           action,
           {'page':page,'pagename':pagename},
           function(res) {
               res = res.replace(/^\s+|\s+$/g, '') ;
               if(res){
                   
                var innerhtml = $("#duelplayerstable").html();
               $("#duelplayerstable").html(innerhtml+res); 
                  $('#duel_lobby_users').bind('scroll',chk_scroll);
               }
               $(".loadingduelIndicator").css("visibility", "hidden");
           },
           "html"
   );
    
}

function getmoreposts(obj){
   var page = obj.getAttribute('val');
   var user = obj.getAttribute('usr');
   var wall = obj.getAttribute('wall');
   var action = '/getmoreposts/ajax/';
   $(".loadingIndicator").css("visibility", "visible");
   $.post(
           action,
           {'page':page,'user':user,'wall':wall},
           function(res) {
                   eval(res);
                   obj.setAttribute('val',res[1]);
                    if (res[0]){
                        $('.divgetmorepost').before(res[0]);
                        $("#piccontainer a").lightBox();
                        //$('.comformconttoggle').click(function(){return false;});//// ?
                        $('.comformconttoggle').click(function(){
                                elid = $(this).attr("tgl");
                                if(res[2]){
                                    for(var k in res[2]){
                                        if('comformcont'+res[2][k] ==  elid)
                                            $('#'+elid).slideToggle();
                                    }
                                }
                        });
                        $('.com_form').submit(function(){
                                cb = $("textarea[name='combody']", $(this)).val();
                                actitemid = $("input[name='itemid']", $(this)).val();
                                actitemtype = $("input[name='itemtype']", $(this)).val();
                                comcont = $("div[foritem='"+actitemid+"']");
                                if(cb.length > 2) {
                                        $('.com_form textarea').val('');//#combodyarea
                                        act = $(this).attr("action");
                                        $.post(
                                                act,
                                                {"combody": cb},
                                                function(res) {
                                                        if(res) {
                                                                if(actitemtype == "topic") {
                                                                        window.location = document.location;
                                                                } else {
                                                                        comcont.prepend(res);
                                                                }
                                                                if(actitemtype != "topic") {
                                                                        $('#comformcont'+actitemid).toggle();
                                                                }
                                                                cb.text(" ");
                                                        }
                                                },
                                                "html"
                                        );

                                }


                                return false;
                        });
                      ;
                       var innerhtml = $(".morepost").html();
                       if(strpos($(".morepost").html(),'Դիտել ավելին') !== false)
                            var innerhtml = $(".morepost").html().substr(12);
                       $(".morepost").html('Դիտել ավելին'+innerhtml); 
                       $(".loadingIndicator").css("visibility", "hidden");
                       $('.iradardz_inside .deleteconfirm,.iradarc_late .deleteconfirm').click(function(){
			        var elem = $(this).closest('.iradarc_late').length ? $(this).closest('.iradarc_late') : $(this).closest('.iradardz_inside');
			        var delfunc = $(this).attr('todo');
			        var args = $(this).attr('arg');
			        var exploded = args.split(',');
			        $.confirm({
			                'title'		: 'Ցանկանու՞մ եք ջնջել',
			                'message'	: 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
			                'buttons'	: {
			                        'Այո'	: {
			                                'class'	: 'blue',
			                                'action': function(){
			                                        elem.slideUp();
			                                        window[delfunc](exploded);
			                                }
			                        },
			                        'Ոչ'	: {
			                                'class'	: 'gray',
			                                'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
			                        }
			                }
			        });

			});
                        $('.iradarc_late,.iradardz_inside').hover(  function () {
                            $(this).find('.deleteconfirm').css('visibility','visible');
                        },   function () {
                            $(this).find('.deleteconfirm').css('visibility','hidden');
                        })

                        }
                    else{
                        $('.morepost').html('');
                        $('.morepost').each(function () {
                            this.onclick = undefined;
                        });
                    }
           },
           "json"
   );
}

function getgroups(obj){
   var page = obj.getAttribute('val');
   var action = '/mygroups/ajax/';
   $(".loadingIndicator").css("visibility", "visible");
   $.post(
           action,
           {'page':page},
           function(res) {
                   $('.divgetmorepost').before(res);
                    $(".loadingIndicator").css("visibility", "hidden");
                    var innerhtml = $(".moregroups").html();
					if(strpos($(".moregroups").html(),'Դիտել ավելին') !== false)
						var innerhtml = $(".moregroups").html().substr(12);
					$(".moregroups").html('Դիտել ավելին'+innerhtml); 
           },
           "html"
   );
	
}

function getgroupmoreposts(obj){
   var page = obj.getAttribute('val');
   var user = obj.getAttribute('usr');
   var wall = obj.getAttribute('wall');
   var group_id = obj.getAttribute('group_id');
   var action = '/action/getmoregroupposts/';
   $(".loadingIndicator").css("visibility", "visible");
   $.post(
           action,
           {'page':page,'user':user,'wall':wall,'group_id':group_id},
           function(res) {
                   $('.divgetmorepost').before(res);
					$('.comformconttogglenew').click(function(){
							elid = $(this).attr("tgl");
							$('#'+elid).slideToggle();
					});
					$('.comformconttogglenew').attr('class','comformconttoggle');
                    $(".loadingIndicator").css("visibility", "hidden");
                    var innerhtml = $(".moregrouppost").html();
					if(strpos($(".moregrouppost").html(),'Դիտել ավելին') !== false)
						var innerhtml = $(".moregrouppost").html().substr(12);
					$(".moregrouppost").html('Դիտել ավելին'+innerhtml); 
           },
           "html"
   );
}

function guestlogin(){
   var action = '/action/login/';
   $.post(
           action,
           {'guest':'guest'},
           function(res) {
               location.href = location.href;
            },
           "html"
   );
}
function sendinviteconfirm(user,username){
   var action = '/action/checkusernumber/';
   $.post(
           action,
           {'user':user},
           function(res) {
               eval(res);
               if(res.returncode == '1.201'){
                    $('#duel_player_name').html(username+'ի');
                    $(".pom_con").hide();
                    $(".hidennurcount").show();
                    $(".hidennurcount").html(res.message);
                    }
            },
           "json"
   );
    $('.fade').show();
    $('#duel_player_name').html(username+'ի');
    $('.inviteconfirmbutton').attr('user',user);
}
function sendDuelInviteMessage(userid){
   var action = '/action/sendDuelInviteMessage/';
    $.post(
           action,
           {'userid':userid},
           function(res) {
			   eval(res);
				if(res.responsecode == "1.101") {
					 $('#inv_'+userid).css("display", "none");
					 openalertpopup(res.message);
				}	
            },
           "html"
    );
}
function sendinvite(elem){
    var sum = $(".pom_con").val();
    var user = elem.getAttribute('user');
    var invite = $("a[value=\""+user+"\"]")[0];
    var type = $(".comp_coutn").val();
    var action = '/action/sendinvite/';
    $.post(
           action,
           {'usr':user,'type':type,'sum':sum},
           function(res) {
                eval(res);
                    if(res){
                        if(res.returncode == "1.101"){
                                openalertpopup(res.message);
                        }
                        else if(res.returncode == "1.121"){
                                $(".comp_coutn").attr('disabled', 'disabled');
                                $(".comp_coutn").attr('unselectable','on').css('MozUserSelect','none');
                                var invite = $("a[value=\""+user+"\"]")[0];
                                invite.childNodes[0].setAttribute('src','/static/images/fe/duel_images/ico_chose_in.png');
                                invite.setAttribute('onclick','null');
                        }
                        else if(res.returncode == "1.131"){
                                openalertpopup(res.message);
                                var invite = $("a[value=\""+user+"\"]")[0];
                                invite.childNodes[0].setAttribute('src','/static/images/fe/duel_images/ico_chose_in.png');
                                invite.setAttribute('onclick','null');
                        }
                        else if(res.returncode == "1.141"){
                                openalertpopup(res.message);
                                var invite = $("a[value=\""+user+"\"]")[0];
                                invite.childNodes[0].setAttribute('src','/static/images/fe/duel_images/ico_chose_in.png');
                                invite.setAttribute('onclick','null');
                        }
                        else if(res.returncode == "1.151"){
                                openalertpopup(res.message);
                        }
                        else{
                            $(".inviteuser img").attr('src','/static/images/fe/duel_images/ico_chose_in.png');
                            $(".inviteuser").attr('onClick','javascript:joid(0);');
                            $(".comp_coutn").attr('disabled', 'disabled');
                            $(".comp_coutn").attr('unselectable','on').css('MozUserSelect','none');
                            var invite = $("a[value=\""+user+"\"]")[0];
                            invite.childNodes[0].setAttribute('src','/static/images/fe/duel_images/ico_chose_in.png');
                            invite.setAttribute('onclick','null');
                        }
                    }
                },
           "json"
    );
    $('.fade').hide();
}

function confirmduelinv(type){
    $('.duel_confirmation').attr('onclick','javascript:void(0);')
    var action = '/action/confirmduelinv/';
    $.post(
           action,
           {'type':type},
           function(res) {
               if(type)
                   window.location = "/duel_lobby";
               else
                   document.location.reload();
            },
           "html"
    );
}

function answerduel(id,gid){
    var action = '/action/answerduel/';
    //
    $.post(
           action,
           {'id':id},
           function(res) {
                eval(res);
               if(res.returncode == "1.101"){
                   $("#color_"+id).attr('class','answer_right');
                    $('.choseduelanswer').attr('onclick','javascript:void(0);')
               }
            },
           "json"
    );
}
   
//function endgame(type){
//   var action = '/action/endduelgame/';
//    $.post(
//           action,
//           {'type':type},
//           function(res) {
//               console.log('sdasda');
//            },
//           "html"
//    );
//   
//}
//




function dueltimeout(gid){
    $.post(
            "/gamequestion/ajax/",
            {"id": gid},
             function(res) {
                if(res.length>10 && res.length<40 && res.indexOf("showresults")>=0){
                      window.location = "/duel_results";
                }
                if(res.length>10 && res.length<40 && res.indexOf("showplayers")>=0){
                      window.location = document.location;
                }
                if(res.length>3 && res.length<10){

                }
                if(res.length>100){
                    $('.middle_block_main').html(res);
                }
            },
             "html"
    );
}

function minduelinv(name){
    if(name == '«ԴՈՒԵԼ»')
        $('.duel_close_icon').hide();
        
    $('.middle_block_duel').hide();
    $('.middle_block_duel_minimized').show();
    $('.duel_minimized_name').html(name);
    $('.middle_block_duel').attr('min','1');
}

function maxduelinv(){
    $('.middle_block_duel').show();
    $('.middle_block_duel_minimized').hide();
    $('.middle_block_duel').attr('min','0');
}

function closealertpopup(url){
    $('.alertpopup').hide();
    $('.alertpopup_background').hide();
    if(undefined !== url)
        window.location = url;
}

function openalertpopup(content,url){
    $('.alerttext').html(content);
    $('.alertpopup_background').show();
    $('.alertpopup').show();
    $('.popup_big_button_res').css('margin-left',$('.alert_fade_popup').width()-80+'px');
//    $('.duel_close_icon').attr('onclick','closealertpopup('+url+')');
//    $('.popup_big_button_res').attr('onclick','closealertpopup('+url+')');
    if(undefined !== url){
        $('.duel_close_icon').click(function() {closealertpopup(url);});
        $('.popup_big_button_res').click(function() {closealertpopup(url);});
    }

    
}
function closevideopopup(){
    $('.videopopup').hide();
    $('.alertpopup_background').hide();
}

function openchartpage(id){
//    $('a.chartpage').css('color','#6B7100');
//    $('a#chartpage'+id).css('color','red');
    $('a.chartpage').css('background-color','#E66700');
    $('a#chartpage'+id).css('background-color','#FA994A');
    $('div.chartdiv').hide();
    $('div#chart'+id).show();
}

function openschoolpage(id){
//    $('a.chartpage').css('color','#6B7100');
//    $('a#chartpage'+id).css('color','red');
    $('a.schoolpage').css('background-color','#9BA50A');
    $('a#schoolpage'+id).css('background-color','#E35959');//E8A444  
    $('div.schooldiv').hide();
    $('div#school'+id).show();
}

function openvideopopup(id){
    $('.alertpopup_background').show();
    $('#videopopoup_'+id).show();
}

function duel_enter(type){
    if(type)
         window.location = "/duel_rules/new";
     else
         window.location = "/duel_lobby";
     $('#duel_enter').attr('onclick','javascript:void(0);');
}

function duel_lobby(type){
     window.location = "/duel_lobby/"+type;
     $('#duel_room_'+type).attr('onclick','javascript:void(0);');
}


function numbersonly(e,elem) {
    var unicode=e.charCode? e.charCode : e.keyCode;
    if (unicode != 8 && unicode != 46 && unicode != 9){  
        if (unicode < 48 || unicode > 57) {
            return false;
        }
    }
    if(unicode == 8 || unicode == 46 || unicode == 9)
        return true;
    var str = String.fromCharCode(unicode);
    var mystr = (elem+str).toString();
//     if(parseInt(elem+str) > 10 )
//         return false;
     if(mystr.length > 9 ){
         return false;
         }
}
function photoFocus(id){
	$('#text_'+id).css("height","50px");
	$('#save_'+id).css("display","block");
}
function photoBlur(id){
	$('#text_'+id).css("height","18px");
	$('#save_'+id).css("display","none");
}
function savePhotoName(id){
	photoName =  $('#text_'+id).val();
	var action = '/savePhotoName/ajax/';
    $.post(
           action,
           {'id':id,'photoName':photoName},
           function(res) {
				$('#text_'+id).css("height","18px");
				$('#save_'+id).css("display","none");		   
            },
           "html"
    );		
}

function closelikebox(){
    $('#likes_cont').hide();
    $('#likes_cont').html('');
}

function addbannerclick(name){
     url = "/action/addbannerclick/";
     $.post(
           url,
           {'name':name},
           function(res) {
            },
           "html"
    );		
}

function makegroupadmin(gid,uid,type){
		if(type)
			var title = 'Ցանկանո՞ւմ եք տվյալ օգտագործողին դարձնել խմբի անդամն:';
		else
			var title = 'Ցանկանո՞ւմ եք տվյալ օգտագործողին դարձնել խմբի ադմինիստրատոր:';
		$.confirm({
			'title'		: title,
			'message'	: 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
			'buttons'	: {
				'Այո'	: {
					'class'	: 'blue',
					'action': function(){
						 var action = '/action/makegroupadmin/';
						 $.post(
							   action,
							   {'gid':gid,'uid':uid,'type':type},
							   function(res){
									if(type) {
												$('#member_box'+uid).insertAfter($('.member_label'));
												$('#member_box'+uid+' .join_grp_mem').attr('onclick','makegroupadmin('+gid+','+uid+',0);');
												$('#member_box'+uid+' .join_grp_mem').html('Դարձնել ադմին');
									}
									else{
												if(!$('.admin_label').length){
													$('.group_members').prepend("<div class='admin_label'>Ադմիններ</div>");
												}
												$('#member_box'+uid).insertAfter($('.admin_label'));
												$('#member_box'+uid+' .join_grp_mem').attr('onclick','makegroupadmin('+gid+','+uid+',1);');
												$('#member_box'+uid+' .join_grp_mem').html('Դարձնել անդամ');
									}
							},
							"html"
						);
					}
				},
				'Ոչ'	: {
					'class'	: 'gray',
					'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
				}
			}
		});
}

function removegroupmember(gid,uid){
		var title = 'Ցանկանո՞ւմ եք տվյալ օգտագործողին հեռացնել սև ցուցակից:';
		$.confirm({
			'title'		: title,
			'message'	: 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
			'buttons'	: {
				'Այո'	: {
					'class'	: 'blue',
					'action': function(){
						 var action = "/action/removegroupmember/";
					     $('.supernote-hover-tooltip'+uid).parent().parent().remove();
						 $.post(
							   action,
							   {'gid':gid,'uid':uid},
							   function(res) {
									if(res && res.length>3) {
											if(duel == "gift")
												openalertpopup(res);
											else
												openalertpopup(res);
									}
								},
							   "json"
						);		
					}
				},
				'Ոչ'	: {
					'class'	: 'gray',
					'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
				}
			}
		});
}

function bangroupmember(gid,uid){
		var title = 'Ցանկանո՞ւմ եք տվյալ օգտագործողին ավելացնել խմբի սև ցուցակում: ';
		$.confirm({
			'title'		: title,
			'message'	: 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
			'buttons'	: {
				'Այո'	: {
					'class'	: 'blue',
					'action': function(){
						 var action = "/action/bangroupmember/";
					     $('.supernote-hover-tooltip'+uid).parent().parent().remove();
						 $.post(
							   action,
							   {'gid':gid,'uid':uid},
							   function(res) {
									if(res && res.length>3) {
											if(duel == "gift")
												openalertpopup(res);
											else
												openalertpopup(res);
									}
								},
							   "json"
						);		
					}
				},
				'Ոչ'	: {
					'class'	: 'gray',
					'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
				}
			}
		});
}


function opengroupdesc(){
    var type = $('#opendesc').attr('type');
    if(type == 1){
        $('.group_desc').css('height','auto');
        $('#opendesc').attr('type','0');
    }
    else{
        $('.group_desc').css('height','32px');
        $('#opendesc').attr('type','1');
    }
    
}

function likegroup(gid){
     var action = "/action/likegroup/";
     $.post(
           action,
           {'gid':gid},
           function(res) {
                eval(res);
                if(res.responsecode == "1.101") {
                    var i = parseInt($('#group_like_'+gid+' b').html());
                    $('#group_like_'+gid+' b').html(i+1);
					$('#group_like_'+gid+' a').remove();
                }
            },
           "html"
    );
}

function likegroupitem(itemtype, itemid, el) {
			$.post(
				"/action/likegroupit/",
				{"itemtype": itemtype, "itemid":itemid},
				function(res) {
					if(res) {
						eval(res);
						code = res.responsecode.split("\.");
						if(code[0]==1 && (code[1]==101)) {
							if(!itemtype){
								itemstrtype= 'post';
							}
							else{
								itemstrtype= 'image';
							}
							cntr = $("b#"+itemstrtype+"_"+itemid+"_lc");
							cntr.html(parseInt(cntr.html())+1);
							$("span#"+itemstrtype+"_"+itemid+"_lb").remove();
							
						}
						if(code[0]==1 && (code[1]==103)) {
							window.location = document.location;
						}
					}
				},
				"html"
			);
	
}


function crategroupdivfriend(uid,elem){
	elem.find("input").attr('checked', true);
	crategroupfriend(uid,elem.find("input"));
}
function crategroupfriend(uid,elem){
	if(!$('#invited_friend_'+uid).length){
		var divchecked = $('<div class="invited_friends_item" id="invited_friend_'+uid+'"></div>');
		divchecked.append('<div class="ico_remove"><img src="/static/images/fe/group_img/ico_remove.png" onclick="uncheckgroupfriend($(this))" uid="'+uid+'"></div>');
		divchecked.append(elem.parent().next().clone());
		divchecked.append(elem.parent().next().next().clone());
		divchecked.append('<input type="hidden" value="'+uid+'"  name="friend_list[]"/>');
		$('#invited_friends').append(divchecked)
		$('#friend_box_'+uid).fadeOut('slow');
	}
}

function uncheckgroupfriend(elem){
	$('#friend_box_'+elem.attr('uid') + ' input').attr('checked', false);
	$('#friend_box_'+elem.attr('uid')).fadeIn();
	elem.parent().parent().remove();;
}

function opengrouplist(user_id){
	$.post(
		"/opengrouplist/ajax/",
		{"user_id": user_id},
		function(res) {
			$('#group_cont').show();
			$('#group_cont').html(res);
		},
		'html'
	);
}
function closegrouplist(){
    $('#group_cont').hide();
    $('#group_cont').html('');
}

function searchgroup(elem){
	window.location = '/mygroups/search/'+$('.search_grp_inp').val();
}

function deletegrouplogo(id){
	$.post(
		"/deletegrouplogo/ajax/",
		{"group_id": id},
		function(res) {
			$('#group_img').attr('src','/static/images/fe/avatar.jpg');
			$('#avatarPanel').hide();
		},
		'html'
	);
	
}

function jointogroup(id,elem){
	$.post(
		"/jointologo/ajax/",
		{"group_id": id},
		function(res) {
			eval(res);
			if(res.success ==  true)
				openalertpopup('Ձեր հայտը ուղարկված է:');
				elem.parent().hide();
		},
		'json'
	);
	
}

function declainnot(note_id){
	$.post(
		"/acceptnot/ajax/",
		{"note_id": note_id,"type":0},
		function(res) {
			eval(res);
			if(res.success ==  true)
				openalertpopup('Հայտը մերժված է:');
				$('#note_'+note_id).remove();
		},
		'json'
	);
	
	
}

function acceptnot(note_id){
	$.post(
		"/acceptnot/ajax/",
		{"note_id": note_id,"type":1},
		function(res) {
			eval(res);
			if(res.success ==  true)
				openalertpopup('Հայտը ընդունված է:');
				$('#note_'+note_id).remove();
		},
		'json'
	);
	

}

function add_to_group(group_id,user_id){
	$.post(
		"/addtogroup/ajax/",
		{"group_id": group_id,"user_id":user_id},
		function(res) {
			eval(res);
			if(res.success ==  true)
				openalertpopup('Ձեր հայտը ուղարկված է:');
				$('#gr_'+group_id).remove();
		},
		'json'
	);
}
var doc_click_handler = function(event) {
	var target = $(event.target);
	
	if (target.parents('.open_notif').length == 0) {
		$('.open_notif').css("display","none");
		remove_doc_click_handler();
	}
};

function add_doc_click_handler() {
	$(document).click(doc_click_handler);
}

function remove_doc_click_handler() {
	$(document).unbind('click', doc_click_handler);
}
function friendRequsetNot(){
	url = "/friendRequestNot/";
	var status = $('#friendRequest').css("display");
	if(status == "block")
	{
		return false;
	}
	$.post(
		   url,
		   function(res){
				$('#friendRequest').html(res);
				//$('#friendRequest').css("opacity","0");
				$('#friendRequest').css("display","block");
				add_doc_click_handler();
				//$('#friendRequest').fadeIn('slow');
			},
		   "json"
	);		
}
function notificationNot(){
	url = "/notificationNot/";
	var status = $('#notificationNot').css("display");
	if(status == "block")
	{
		return false;
	}
	$.post(
		   url,
		   function(res){
				$('#notificationNot').html(res);
				$('#notificationNot').css("display","block");
				add_doc_click_handler();
				url1 = "/updateNotNewCount/";
					$.post(
						   url1,
						   function(res){
							   
								$('#notCount').html(res);
								$(".notLight a.notPhoto").lightBox();
								$(".notLight a.notPhoto").click(function() {
 									$('.open_notif').css("display","none");
								});
							},
						   "html"
					);	
			},
		   "json"
	);		
}
function messageNot(){
	url = "/messageNot/";
	var status = $('#messageNot').css("display");
	if(status == "block")
	{
		return false;
	}
	$.post(
		   url,
		   function(res){
				$('#messageNot').html(res);
				$('#messageNot').css("display","block");
				add_doc_click_handler();
			},
		   "json"
	);		
}
function confirmFriendRequest(requestId,type){
	//type 1 = menu, type 2 = allNotification
	url = "/confirmFriendRequest/";
	$.post(
		   url,
		   {'requestId':requestId},
		   function(res){
			    eval(res);
			   	if(res['status'] == 1)
				{
					frCount = $('#frCount').html();
					frCount = frCount - 1;
					if(frCount == 0)
					{
						$('#frCount').html("");	
					}
					else
					{
						$('#frCount').html(frCount);
					}
					if(type == 1)
					{
						if($('#friendRequest .top_notifications_box').length > 1)
						{
							$('#f_'+res['idr']).fadeOut('slow');
							$('#f_'+res['idr']).remove();	
						}
						else
						{
							$('#friendRequest').css("display","none");
							$('#f_'+res['idr']).remove();
						}
					}
					if(type == 2)
					{
						if($('#friendAllNotification .notification_list_item').length > 1)
						{
							$('#fra_'+res['idr']).fadeOut('slow');
							$('#fra_'+res['idr']).remove();		
						}
						else
						{
							$('#fra_'+res['idr']).fadeOut('slow');
							$('#fra_'+res['idr']).remove();
							$('#friendAllNotification').html('<div>Նոր հարցումներ չկան:</div>');
						}
					}
				}
			},
		   "json"
	);		
}
function rejectFriendRequest(requestId,type){
	//type 1 = menu, type 2 = allNotification
	url = "/rejectFriendRequest/";
	$.post(
		   url,
		   {'requestId':requestId},
		   function(res){
			    eval(res);
			   	if(res['status'] == 1)
				{
					frCount = $('#frCount').html();
					frCount = frCount - 1;
					if(frCount == 0)
					{
						$('#frCount').html("");	
					}
					else
					{
						$('#frCount').html(frCount);
					}
					if(type == 1)
					{
						if($('#friendRequest .top_notifications_box').length > 1)
						{
							$('#f_'+res['idr']).fadeOut('slow');
							$('#f_'+res['idr']).remove();	
						}
						else
						{
							$('#friendRequest').css("display","none");
							$('#f_'+res['idr']).remove();
						}
					}
					if(type == 2)
					{
						if($('#friendAllNotification .notification_list_item').length > 1)
						{
							$('#fra_'+res['idr']).fadeOut('slow');
							$('#fra_'+res['idr']).remove();		
						}
						else
						{
							$('#fra_'+res['idr']).fadeOut('slow');
							$('#fra_'+res['idr']).remove();
							$('#friendAllNotification').html('<div>Նոր հարցումներ չկան:</div>');
						}
					}
				}
			},
		   "json"
	);		
}
function confirmGift(requestId,type,notId)
{
	//type 1 = menu, type 2 = allNotification
	url = "/confirmGift/";
	$.post(
		   url,
		   {'requestId':requestId,'notId':notId},
		   function(res){
			    eval(res);
			   	if(res['status'] == 1)
				{
					/*
					frCount = $('#notCount').html();
					frCount = frCount - 1;
					if(frCount == 0)
					{
						$('#notCount').html("");	
					}
					else
					{
						$('#notCount').html(frCount);
					}*/
					if(type == 1)
					{
						if($('#notificationNot .top_notifications_box').length > 1)
						{
							$('#not_'+res['idr']).fadeOut('slow');
							$('#not_'+res['idr']).remove();	
						}
						else
						{
							$('#notificationNot').css("display","none");
							$('#not_'+res['idr']).remove();
						}
					}
					if(type == 2)
					{
						if($('#notificationAllNot .notification_list_item').length > 1)
						{
							$('#nota_'+res['idr']).fadeOut('slow');
							$('#nota_'+res['idr']).remove();		
						}
						else
						{
							$('#nota_'+res['idr']).fadeOut('slow');
							$('#nota_'+res['idr']).remove();
							$('#notificationAllNot').html('<div>Նոր հարցումներ չկան:</div>');
						}
					}
				}
			},
		   "json"
	);		
}
function rejectGift(requestId,type,notId){
	//type 1 = menu, type 2 = allNotification
	url = "/rejectGift/";
	$.post(
		   url,
		   {'requestId':requestId,'notId':notId},
		   function(res){
			    eval(res);
			   	if(res['status'] == 1)
				{
					/*
					frCount = $('#notCount').html();
					frCount = frCount - 1;
					if(frCount == 0)
					{
						$('#notCount').html("");	
					}
					else
					{
						$('#notCount').html(frCount);
					}*/
					if(type == 1)
					{
						if($('#notificationNot .top_notifications_box').length > 1)
						{
							$('#not_'+res['idr']).fadeOut('slow');
							$('#not_'+res['idr']).remove();	
						}
						else
						{
							$('#notificationNot').css("display","none");
							$('#not_'+res['idr']).remove();
						}
					}
					if(type == 2)
					{
						if($('#notificationAllNot .notification_list_item').length > 1)
						{
							$('#nota_'+res['idr']).fadeOut('slow');
							$('#nota_'+res['idr']).remove();		
						}
						else
						{
							$('#nota_'+res['idr']).fadeOut('slow');
							$('#nota_'+res['idr']).remove();
							$('#notificationAllNot').html('<div>Նոր հարցումներ չկան:</div>');
						}
					}
				}
			},
		   "json"
	);
}
function confirmGroup(requestId,type,notId)
{
	//type 1 = menu, type 2 = allNotification
	url = "/confirmGroup/";
	$.post(
		   url,
		   {'requestId':requestId,'notId':notId},
		   function(res){
			    eval(res);
			   	if(res['status'] == 1)
				{
					/*
					frCount = $('#notCount').html();
					frCount = frCount - 1;
					if(frCount == 0)
					{
						$('#notCount').html("");	
					}
					else
					{
						$('#notCount').html(frCount);
					}*/
					if(type == 1)
					{
						if($('#notificationNot .top_notifications_box').length > 1)
						{
							$('#not_'+res['idr']).fadeOut('slow');
							$('#not_'+res['idr']).remove();	
						}
						else
						{
							$('#notificationNot').css("display","none");
							$('#not_'+res['idr']).remove();
						}
					}
					if(type == 2)
					{
						if($('#notificationAllNot .notification_list_item').length > 1)
						{
							$('#nota_'+res['idr']).fadeOut('slow');
							$('#nota_'+res['idr']).remove();		
						}
						else
						{
							$('#nota_'+res['idr']).fadeOut('slow');
							$('#nota_'+res['idr']).remove();
							$('#notificationAllNot').html('<div>Նոր հարցումներ չկան:</div>');
						}
					}
				}
			},
		   "json"
	);		
}
function rejectGroup(requestId,type,notId){
	//type 1 = menu, type 2 = allNotification
	url = "/rejectGroup/";
	$.post(
		   url,
		   {'requestId':requestId,'notId':notId},
		   function(res){
			    eval(res);
			   	if(res['status'] == 1)
				{
					/*
					frCount = $('#notCount').html();
					frCount = frCount - 1;
					if(frCount == 0)
					{
						$('#notCount').html("");	
					}
					else
					{
						$('#notCount').html(frCount);
					}*/
					if(type == 1)
					{
						if($('#notificationNot .top_notifications_box').length > 1)
						{
							$('#not_'+res['idr']).fadeOut('slow');
							$('#not_'+res['idr']).remove();	
						}
						else
						{
							$('#notificationNot').css("display","none");
							$('#not_'+res['idr']).remove();
						}
					}
					if(type == 2)
					{
						if($('#notificationAllNot .notification_list_item').length > 1)
						{
							$('#nota_'+res['idr']).fadeOut('slow');
							$('#nota_'+res['idr']).remove();		
						}
						else
						{
							$('#nota_'+res['idr']).fadeOut('slow');
							$('#nota_'+res['idr']).remove();
							$('#notificationAllNot').html('<div>Նոր հարցումներ չկան:</div>');
						}
					}
				}
			},
		   "json"
	);
}
function message_deleteWholeConversation(user_id) {
	var remove_handler = function (user_id) {
		$.post(
			"/action/deleteMessagethread/",
			{"user_id":user_id},
			function(res) {
				eval(res);
				code = res.responsecode.split("\.");
				if(code[0] > 1) {
					$('div.output').html(res.message);
				}
				if(code[0]==1 && code[1]==101) {
					openalertpopup(res.message, '/inbox/1/');
				}
			},
			"html"
		);
	};
	
	$.confirm({
		'title'		: 'Ցանկանու՞մ եք ջնջել',
		'message'	: 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
		'buttons'	: {
			'Այո'	: {
				'class'	: 'blue',
				'action': function(){
					remove_handler(user_id);
				}
			},
			'Ոչ'	: {
				'class'	: 'gray',
				'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
			}
		}
	});
	
	return false;
}

function quick_group_jump(){
	window.location = '/groupwall/'+$('.quick_jump_sel :selected').val();
}

function deletegroup(group_id){
	$.confirm({
		'title'		: 'Ցանկանու՞մ եք ջնջել',
		'message'	: 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
		'buttons'	: {
			'Այո'	: {
				'class'	: 'blue',
				'action': function(){
					$.post(
						"/action/detelegroup/",
						{"group_id":group_id},
						function(res) {
								window.location = '/mygroups/';
						},
						"html"
					);
				}
			},
			'Ոչ'	: {
				'class'	: 'gray',
				'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
			}
		}
	});
	
	return false;
	
}

function user_addToBlacklist(user_id, name, restore) {
	restore = restore === undefined ? false : true;
	
	var add_to_blacklist = function (user_id) {
		$.post(
			"/action/addToBlacklist/",
			{"user_id":user_id},
			function(res) {
				eval(res);
				code = res.responsecode.split("\.");
				if(code[0] > 1) {
					$('div.output').html(res.message);
				}
				if(code[0]==1 && code[1]==101) {
					openalertpopup(res.message, '');
				}
			},
			"html"
		);
	};
	
	$.confirm({
		'title'		: ! restore ? 'Արդյո՞ք վստահ եք, որ ցանկանում եք այս օգտագործողին (' + name + ') ավելացնել սև ցուցակում' : 'Արդյո՞ք վստահ եք, որ ցանկանում եք այս օգտագործողին (' + name + ') հեռացնել սև ցուցակից',
		'message'	: 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
		'buttons'	: {
			'Այո'	: {
				'class'	: 'blue',
				'action': function () {
					add_to_blacklist(user_id);
				}
			},
			'Ոչ'	: {
				'class'	: 'gray',
				'action': function(){}	// Nothing to do in this case. You can as well omit the action property.
			}
		}
	});
	
	return false;
}
