var handlerShowFormErrors = function (req) {
    jSonObj = getJSon(req);
    if (jSonObj.err_is_error) {
        showFormErorrs(jSonObj, jSonObj.formname);
        if($('btnSave')) $('btnSave').disabled = false;
    } else {
        window.location = jSonObj.location ? jSonObj.location : req.responseText;
    }
}

var voidHandler = function (req) {
}

var handlerReload = function (req) {
	window.location.reload();
}

var handlerChangeCaptcha = function (req) {
	$('captcha_img').src='?session='+req.responseText;
}

var handlerAuth = function(req) {
    jSonObj = getJSon(req);
    if (jSonObj) {
        showFormErorrs(jSonObj, 'auth');
        document.getElementById("turnstile").style.background = "url(/img/turnstile2.jpg) no-repeat top center;";
        document.getElementById("turnstile").className = "off";
    } else {
        window.location = req.responseText;
    }
}

var handlerRecoverPassword = function(req) {
	jSonObj = getJSon(req);
	if(jSonObj.err_is_error) {
		showFormErorrs(jSonObj, 'recoverypassword');
	} else {
		$('passrec').style.display = 'none';
		$('passrec_ok').style.display = 'block';
	}
}

var handlerCheckLogin = function(req) {
    obj = $("in").innerHTML = req.responseText;
}

var handlerUserInfo = function(req) {
   if (jSonObj = getJSon(req)) {
        showFormErorrs(jSonObj, 'user_info');
    } else {
        window.location = req.responseText;//'/user.html?reg=1';
    }
}

var handlerUserPasswordChange = function(req) {
   if (jSonObj = getJSon(req)) {
        showFormErorrs(jSonObj, 'pass_change');
    } else {
    	document.getElementById("passrec_ok").style = "display: block";
        window.location = req.responseText;//'/user.html?reg=1';
    }
}

var handlerRegister = function(req) {
	jSonObj = getJSon(req);
    if (jSonObj.err_is_error) {
    	$('captcha_img').src = '/app/controllers/show_captcha.php?randomshit=' + Math.random();
    	//$('captcha_img').src = '?session=' + jSonObj.captcha_img;
        showFormErorrs(jSonObj, 'register');        
    } else {
        window.location = req.responseText;//'/user.html?reg=1';
    }
}
var handlerRecoveryPassword = function(req) {
	jSonObj = getJSon(req);
    if (jSonObj.err_is_error) {
        showFormErorrs(jSonObj, 'register');        
    } else {
    	document.getElementById("passrec_ok").style.display = "block";
        window.location = req.responseText;//'/user.html?reg=1';
    }
}

var handlerLostPassword = function(req) {
    if (jSonObj = getJSon(req)) {
        showFormErorrs(jSonObj, 'lost_password');
    } else {
        window.location = req.responseText;//'/user.html?reg=1';
    }
}

var handlerLostPasswordPopup = function(req) {
    if (jSonObj = getJSon(req)) {
        showFormErorrs(jSonObj, 'lost_password_popup');
    } else {
        window.location = req.responseText;//'/user.html?reg=1';
    }
}

var handlerWriteInvites = function(req) {
	$('community_posts').innerHTML = req.responseText; 
}

var handlerInviteFriendPopup = function(req) {
    if (jSonObj = getJSon(req)) {
        showFormErorrs(jSonObj, 'invite_friend_popup');
    } else {
        window.location = req.responseText;//'/user.html?reg=1';
    }
}

var handlerUserNewComment = function(req) {
	$('add_comment_button').disabled = false;
	if (jSonObj = getJSon(req)) {
        showFormErorrs(jSonObj, 'newcomment');
    } else {
    	$('msgs').value = '';
        $('comments_list').innerHTML = req.responseText;   
    }
	
}

var handlerDelComment = function(req) {
	jSonObj = getJSon(req);
	if(jSonObj.id) {
		$('cmnt_text'+jSonObj.id).innerHTML = "Комментарий удалён";
		$('comdiv_'+jSonObj.id).childNodes[1].style.background = "";
		$('comdiv_'+jSonObj.id).childNodes[1].className = "";
		$('comdiv_'+jSonObj.id).nextSibling.nextSibling.innerHTML = '';
	}
}

var handlerPaging = function(req) {
    if (req.responseText == '0' || globalPagingObjId == null) { // Error
        globalPagingObjId = null;
    } else {
        pgObjId = globalPagingObjId;
        globalPagingObjId = null;
        $(pgObjId).innerHTML = req.responseText;
        tmphash = window.location.hash; 
        window.location.hash = 'top';
        if(tmphash.length > 2) {
        	window.location.hash = tmphash;
        }
    }
}

var handlerGroupInviteUsersSearch = function(req) {
    if (req.responseText != '' && req.responseText != '0') {
        $("replace_contents").innerHTML = req.responseText;
    } else {
        $("replace_contents").innerHTML = 'не найдено ни одного пользователя';
    }
}

var handlerGroupInviteUsers = function(req) {
    if(req.responseText) {
        var idsArray = req.responseText.split(',');
        for(i=0; i<idsArray.length; i++) {
            $('invuser_'+idsArray[i]).innerHTML = 'Приглашение отправлено';
        } 
    }
}

var handlerWriteGroups = function(req) {
	jSonObj = getJSon(req);
	if(jSonObj.select.length > 1) {
		$(jSonObj.linkId).style.display = 'none';
		$(jSonObj.linkId).parentNode.innerHTML += jSonObj.select;
	}
}

var handlerInviteUser = function(req) {
	jSonObj = getJSon(req);
    if(jSonObj.userId) {
        alert('Приглашения высланы');
        removeSelect(jSonObj.userId, jSonObj.fix);
    }
}

var handlerGroupDelFriends = function(req) {
    document.location.reload();
}

var handlerGroupConfirmFriend = function(req) {
    if(req.responseText) {
        alert('Приглашение принято');
        document.location = req.responseText;
    }
}

var handlerGroupFriendsSearch = function(req) {
    if (req.responseText != '' && req.responseText != '0') {
        $("groups_search_list").innerHTML = req.responseText;
        changeClassName('invite_link', 'reg');
    } else {
        $("groups_search_list").innerHTML = 'не найдено ни одной группы';
        changeClassName('invite_link', 'hide');
    }
}

var handlerMessages = function(req) {
	jSonObj = getJSon(req);
	switch(jSonObj.action) {
		case 'sendmessage':
			$('sendButton').disabled = false;
			$('new_msg_text').value='';
		case 'loadmessage':
			if(jSonObj.users) {
				$('users_list').innerHTML = jSonObj.users;
			}
			if(jSonObj.message) {
				$('msg_list').innerHTML += jSonObj.message;
				if(changeTitle == 1 && jSonObj.action != 'sendmessage') {			
					chTitleInt = setInterval("changeTitleFunct('" + docTitle + "')", 1000);
				}
				if(jSonObj.lastId && $('last_id')) {
					$('last_id').value = jSonObj.lastId;
				}
				$('msg_list').scrollTop = $('msg_list').scrollHeight + 30; 
			}
			break;
		case 'delcontact':
			if(jSonObj.objId) {
				var id = jSonObj.objId;
				$('contacts_list').removeChild($('contact_'+id));
			}		
	}
}

var handlerUserPopupSettings = function(req) {
	jSonObj = getJSon(req);
    if (jSonObj.err_is_error) {
        showFormErorrs(jSonObj, jSonObj.formname);
    } else {
    	switch(jSonObj.formname){
    		case 'load_avatar':
    			var time = new Date();
    			$('loadedImage').src = '';
    			$('user_card_avatar').style.background = 'url(/files/avatars/user/big/'+jSonObj.objId+'.jpg?'+time.getTime() + ') no-repeat scroll left top';
    			hidePopup('loadedPicture');
				break;
    		case 'change_name':
    			var username = $('nickname').value;
    			/*
    			var old_nickname = $('breadUserName').innerHTML.replace(/\&shy\;/g, '');    			
    			if($('nickname').value != old_nickname) { 
    				$('nickname').disabled = true;
    				$('nickname').title = 'Никнейм можно менять только 1 раз за месяц';
    			}
    			*/
    			if(username == '') {
    				username = $('name').value + ' ' + $('surname').value;
    			}
    			$('breadUserName').innerHTML = username;
    			$('headerUserName').innerHTML = username;
    			$('pageUserName').innerHTML = username;
    			hidePopup();
				break;
			case 'change_age':
				now = new Date();
				if(jSonObj.birthday) {
					age = jSonObj.birthday;
	            	$('user_age').innerHTML = age;
	            }
            	$('sex_age').className = "userage " + ($('sex').value==1 ? 'male' : ($('sex').value==2 ? 'female' : 'bi'));
            	$('sex_age').title = ($('sex').value==1 ? 'Парень' : ($('sex').value==2 ? 'Девушка' : 'Ещё не определился'));
            	hidePopup();
            	break;
			case 'change_station':
            	$('metroname').innerHTML = jSonObj.city;
            	$('branch').style.backgroundColor = '#'+jSonObj.color;
            	$('station').innerHTML = jSonObj.station;
            	$('station').title = 'Перейти на страницу ст. ' + jSonObj.station;
            	$('station').href = '/station/' + jSonObj.station_id + '.html' 
            	$('change_station').innerHTML = '';
            	hidePopup();
            	break;
            case 'change_buble':
            	$('buble_text_container').onmouseover = function () {showBuble(jSonObj.buble)};
            	$('buble_text_info').innerHTML = jSonObj.buble;
            	hidePopup();
            	break;
    	} 
        
    }
}

var handlerUserAddFriend = function (req) {
	jSonObj = getJSon(req);
	if(jSonObj.err_is_error) {
		alert ('Ошибка при добавлении в друзья');
	} else {
		$(jSonObj.contId).innerHTML = '[ ожидается ответ ]';
		hidePopup('invitefriendpopup');
		$('invitemsg').value = '';
	}
}

var handlerNewAlbum = function(req) {
	jSonObj = getJSon(req);
	if (jSonObj.err_is_error) {
        showFormErorrs(jSonObj, jSonObj.formname);
    } else {
        if (jSonObj.objId && $('album_title_'+jSonObj.objId)) {
            $('album_title_'+jSonObj.objId).innerHTML = jSonObj.album_title;
			$('album_desc_'+jSonObj.objId).innerHTML = jSonObj.album_desc;
			var time = new Date();
			if($('album_cover_'+jSonObj.objId).className == 'round210x140') {
				$('album_cover_'+jSonObj.objId).style.background = 'url(/files/foto/albums/big/'+jSonObj.objId+'.jpg?'+time.getTime() + ') no-repeat scroll left top';
			} else {
				$('album_cover_'+jSonObj.objId).style.background = 'url(/files/foto/albums/small/'+jSonObj.objId+'.jpg?'+time.getTime() + ') no-repeat scroll left top';
			}
			hidePopup('add_album');
        } else {
            window.location = jSonObj.location;
        }
    }
}

var handlerLoadCover = function (req) {
	jSonObj = getJSon(req);
	var time = new Date();
	if($('loadedCover')) {
		objId = 'loadedCover';
		width = '210px';
		height = '140px'; 
	} else if($('loadedAvatar')) {
		objId = 'loadedAvatar';
		width = height = '150px';
	} else if($('object_id').name=='album_id') {
		objId = 'album_cover_'+$('object_id').value;
		width = '160px';
		height = '120px';
	}
	if($('object_id').value > 0) {
		if($('object_id').name!='group_id' && $('object_id').name!='place_id' && $('object_id').name!='event_id') {
			var file = $('object_id').value+'.jpg?'+time.getTime();
			if($('object_id').name!='album_id') {
				$(objId).style.background = 'url(/files/foto/albums/big/'+file+') no-repeat scroll left top';
			} else {
				$(objId).style.background = 'url(/files/foto/albums/small/'+file+') no-repeat scroll left top';
			}
		} else {
			var file = $('loadedFileName').value+'_big.jpg?'+time.getTime();
			$(objId).style.background = 'url(/files/upload/'+file+') no-repeat scroll left top';
		}
	} else {
		var file = $('loadedFileName').value+'_big.jpg?'+time.getTime();
		$(objId).style.background = 'url(/files/upload/'+file+') no-repeat scroll left top';
	}
	if($('object_id').name!='album_id') {
		$(objId).style.width = $(objId+'1').style.width = width; //$(objId+'2').style.width
		$(objId).style.height = $(objId+'1').style.height = height; // = $(objId+'2').style.height
	}
	hidePopup('loadedPicture');
	if($('covercontainer')) {
		$('covercontainer').style.display = "block";
	}
	if(jSonObj.album_id) {
		$('loadedFileName').value = '';
	}
}

var handlerLoadPreview = function (req) {
	jSonObj = getJSon(req);
	$('preview_'+jSonObj.objId).innerHTML = '<img width="160" src="'+'/files/upload/'+jSonObj.filename+'_big.jpg" alt="" />';
	$('previewFileName_'+jSonObj.objId).value = jSonObj.filename;
	hidePopup('loadedPicture');
}

var handlerChangePhoto = function (req) {
	var jSon = getJSon(req);
	if(jSon.image) {
		$('img_preview_'+jSon.objId).className='active';
		$('img_preview_link_'+jSon.objId).onclick=function(){return false;};
		if($('img_preview_link_'+$('pid').value)) {
			$('img_preview_link_'+$('pid').value).pid=$('pid').value;
			$('img_preview_link_'+$('pid').value).onclick=function(){return sendRequest('POST', 'ajax/changePhoto.php', 'pid='+this.pid, handlerChangePhoto)};
			$('img_preview_'+$('pid').value).className='nonactive';
		}
		$('imagecontainer').innerHTML = jSon.image;
		$('comments_list').innerHTML = jSon.comments_text;
		$('item_id').value = jSon.objId;
		$('pid').value = jSon.objId;
		if($('insert_code')) {
			$('links').removeChild($('insert_code'));
		}
//		$('show_friends_link').pid = $('send_email_link').pid = $('insert_code_link').pid = jSon.objId;		
		
		$('photo_title').innerHTML = jSon.photo_title;
		if(jSonObj.photo_rights == 0) {
			$('del_photo_link').style.display = 'none';
			$('change_p_title').style.display = 'none';
			$('ch_p_title_cont').style.display = 'none';
		} else if(jSonObj.photo_rights == 1) {
			$('del_photo_link').style.display = 'block';
			if($('change_p_title')) {
				$('change_p_title').style.display = 'block';
				$('ch_p_title_cont').style.display = 'none';
				$('change_title_input').value = jSon.photo_title;
			}			
		}	
		$('photo_rating').innerHTML = jSonObj.rating;		
		$('photo_view_count').innerHTML = jSonObj.views;		
		if($('org_img')) {
			$('originalimageinner').innerHTML = '';
		}
		if($('photo_author')) {
			$('photo_author').innerHTML = 'Загрузил: ' + jSon.photo_author;
		}
		sendRequest('POST', 'ajax/setCookie.php', 'name=pid&value=' + jSon.objId, voidHandler);
		aid = document.URL.substr(document.URL.lastIndexOf('/')+1, document.URL.lastIndexOf('.') - document.URL.lastIndexOf('/') - 1);
		sendRequest('POST', 'ajax/setCookie.php', 'name=aid&value=' + aid, voidHandler);
	}
	delete(jSon);
}

var handlerChangePhotoTitle = function (req) {
	jSonObj = getJSon(req);
	if(jSonObj.objId) {
		$('photo_title').innerHTML = jSonObj.title;
		$('change_p_title').style.display = 'block';
		$('ch_p_title_cont').style.display = 'none';
		$('change_title_input').value = jSonObj.title;
	}
}

var handlerDelPhoto = function (req) {
	var jSon = getJSon(req);
	if(jSon.objId) {		
		var obj = $('img_preview_link_'+jSon.objId).nextSibling;
		if(obj) {
			while(obj.nodeType == 3 ){
				obj = obj.nextSibling;
				if(obj==null) break;
			}
		}
		if(obj==null) {
			var obj = $('img_preview_link_'+jSon.objId).previousSibling;
			if(obj) {
				while(obj.nodeType == 3){
					obj = obj.previousSibling;
					if(obj==null) break;
				}
			}
		}		
		if(obj!=null) {
			var nextPhotoId = obj.id;
			var nextPId = parseInt(nextPhotoId.substr(nextPhotoId.lastIndexOf('_') + 1));
			sendRequest('POST', 'ajax/changePhoto.php', 'pid='+nextPId, handlerChangePhoto);
			if ($('img_preview_link_'+jSon.objId).offsetWidth && $('preview_photos_container') && $('preview_photos_container').style.width) {
				containerWidth =$('preview_photos_container').style.width;
				containerWidth = containerWidth.replace("px","");
				containerWidth-= $('img_preview_link_'+jSon.objId).offsetWidth;
				$('preview_photos_container').style.width = containerWidth + "px";
			}
			$('img_preview_link_'+jSon.objId).parentNode.removeChild($('img_preview_link_'+jSon.objId));
		} else {
			$('photos').innerHTML = '';
			$('comments').innerHTML = '';
			$('links').innerHTML = '';
		}
	}
	if(jSonObj.act) {
		if(jSonObj.act == 'move') {
			hidePopup('movePhotoPopup');
		}
	}
}
var handlerManageTags = function(req) {
	var jSonObj = getJSon(req);
 	if (jSonObj.err_is_error) {
        showFormErorrs(jSonObj, 'selectTags');
    } else {
        $("tags_interests_list").innerHTML = req.responseText;
        $("tag_input").value="";
        $("tag_input").focus();
    }	
}

var handlerSelectTags = function(req) {
    var jSonObj = getJSon(req);
    if (jSonObj) {
        $("tags_list").jSonObj = jSonObj;
        var str = '';
        numFields = 0;
        selectedField = 0; //1;
        for (key1 in jSonObj) {
            if (key1.length > 0 && jSonObj[key1] && !isNaN(parseInt(key1))) {
            	numFields++;  
            	str += '<a href="#" class="selectOff" id="field_'+numFields+'" onclick="return saveTag(\'' + jSonObj[key1]['name'] + '\', '+jSonObj[key1]['id']+');" onMouseOver="selectTag('+numFields+', true);" onMouseMove="mouseSelect = 1;" onMouseOut="deselectTag('+numFields+');" name="' + jSonObj[key1]['id'] + '">' + jSonObj[key1]['name'] + '</a>';
        	}
        }  
        $("tags_list").style.height = numFields*20;
        $("tags_list").innerHTML = '<ul id="tag_select">' + str + '</ul>';
        $("tags_list").style.display = 'block';
        whiteRequest = 0;
    } else {
    	hideSelectTagsList ();
    }
}

var handlerSelectStations = function(req) {
    var jSonObj = getJSon(req);
    if (jSonObj) {
        var str = '';
        numStationsFields = 0;
        selectedStationsField = 0; //1;
        for (key1 in jSonObj) {
            if (key1.length > 0 && jSonObj[key1] && !isNaN(parseInt(key1))) {
            	numStationsFields++;  
            	str += '<a href="#" class="selectOff" id="station_'+numStationsFields+'" onclick="return saveStation(\'' + jSonObj[key1]['name'] + '\', '+jSonObj[key1]['id']+');" onMouseOver="selectStation('+numStationsFields+');" onMouseOut="deselectStation('+numStationsFields+');" name="' + jSonObj[key1]['id'] + '" style="color: #' + jSonObj[key1]['color'] + '">' + jSonObj[key1]['name'] + '</a>';
        	}
        }  
        $("stations_list").style.height = numStationsFields*20;
        $("stations_list").innerHTML = '<ul id="station_select">' + str + '</ul>';
        $("stations_list").style.display = 'block';
        whiteRequest = 0;
    } else {
    	hideSelectStationList ();
    }
}

var handlerSelectMetropoliten = function(req) {
	var jSonObj = getJSon(req);
	if (jSonObj.main) {
		if(jSonObj.add == 'multi') {
			var add = '_1';
		} else {
			var add = '';
		}			
		$('home_station'+add).innerHTML = jSonObj.main;
		if(jSonObj.add && jSonObj.add !== 'multi') {
			$('add_stations').innerHTML = jSonObj.add;
			$('add_station_link_container').innerHTML = '<a href="#" class="dynamic" onclick="return changeClassName(\'add_station_2\')">Дополнительные домашние станции</a>'; 
		}
	}
}

var handlerSelectBranch = function(req) {
	if (jSonObj = getJSon(req)) {
		var num = '';
		if(jSonObj.num.length > 0) {
			num = '_' + jSonObj.num;
		}
		var str = '';
		for (key in jSonObj) {
			if (key.length > 0 && jSonObj[key] && !isNaN(parseInt(key))) {
				if(!firstId) {var firstId = key;}
				str += '<option value="'+jSonObj[key]['id']+'">'+jSonObj[key]['name']+'</option>';
			}
		}
		if(jSonObj.num > 1) {
			str = '<option value="0">Не указывать</option>' + str;
		}
		str = '<select name="station' + num + '" id="station' + num + '">' + str + '</select>'; 
		$('inp_station' + num).innerHTML = str;
		$('inp_color' + num).value = jSonObj.color;
	}
}

var handlerProfile = function(req) {
	jSonObj = getJSon(req);
 	if (jSonObj.err_is_error) {
        showFormErorrs(jSonObj, 'profile'+jSonObj.formname);
	    $(jSonObj.formname+'_status').style.display = 'none';
    } else {    	
    	hideFormErrors(jSonObj.formname);
    	if(jSonObj.formname == 'changepassword') {
    		$('profile'+jSonObj.formname).reset();
    	}
    	if(jSonObj.formname == 'metroskop' && jSonObj.objId) {    		
    		newDiv = document.createElement('div');
			newDiv.id = 'contact_' + jSonObj.objId;
			newDiv.innerHTML = '<a href="' + $('metroskop').value + '" target="_blank">'+ ($('metroskop_title').value.length?$('metroskop_title').value:$('metroskop').value) + '</a> <sup class="del"><a href="#" onclick="return sendRequest(' + "'post', 'ajax/delContact.php', 'id="+jSonObj.objId+"', handlerDelContact)" + '">x</a></sup>';
			$('contact_metroskop').style.display = 'block';
			$('contact_metroskop').appendChild(newDiv);
			hideContact('metroskop');
    	}
    	changeClassName(jSonObj.formname+'_status');        
        setTimeout("changeClassName('"+jSonObj.formname+'_status'+"')", 3000);
    }	
}

var handlerShowStationsPopup = function(req) {
	$('change_station').innerHTML = req.responseText + $('change_station').innerHTML; 
	showPopup('changestationformcontainer');
}

var handlerUpdateRating = function (req) {
	jSonObj = getJSon(req);
	if(jSonObj.rating) {
		$('rating').innerHTML = jSonObj.rating;
		$('rating_img').src = '/img/rating_'+jSonObj.img+'.gif';
		$('plus_rating_img').src = '/img/r_up_dis.gif';
	} else {
		alert('Вы уже проголосовали');
	}
}

var handlerAddInterest = function (req) {
	jSonObj = getJSon(req);
	if(jSonObj.id) {
		var sup = false;
		var parentElement = $(jSonObj.linkId).parentNode;
		parentElement.removeChild($(jSonObj.linkId));
		for (key in parentElement.childNodes) {
			if(parentElement.childNodes[key].nodeName == 'SPAN') {
				childElement = parentElement.childNodes[key].firstChild; 
				if(childElement.nodeType == 3) {
					text = childElement.nodeValue;
				} else if (childElement.nodeType == 1) {
					text = childElement.innerHTML;
				}
				parentElement.childNodes[key].innerHTML = '<a href="/user.html?interests=' + jSonObj.id + '" class="match" onclick="interestOnClick(' + jSonObj.id + ')">' + text + '</a>';
			}
			if(parentElement.childNodes[key].nodeName == 'SUP') {
				parentElement.childNodes[key].innerHTML = parseInt(parentElement.childNodes[key].innerHTML) + 1;
				sup = true;
			}
		}
		if(!sup) {
			sup = document.createElement('sup');
			sup.innerHTML = '2';
			parentElement.appendChild(sup);
		} 
	}
}

var handlerDelInterest = function (req) {
	jSonObj = getJSon(req);
	if(jSonObj.id) {
		//$('tags_interests_list').removeChild($('interest_'+jSonObj.id));
		$('interest_'+jSonObj.id).innerHTML = "";
	}
}

var handlerDelPath = function (req) {
	jSonObj = getJSon(req);
	if(jSonObj.id) {
		if($('paths_count')) {
			$('paths_count').innerHTML = parseInt($('paths_count').innerHTML) - 1;
		} 
		$('paths').removeChild($('path_'+jSonObj.id));
	}
}

var handlerSearchUsers = function (req) {
	$('peoples').innerHTML = req.responseText;
	if($('interestsList')) {
		$('interestsList').innerHTML = makeInterestsList();
	} else if($('pathTitleCont')) {
		if($('pathname').innerHTML.length > 0){
			$('pathTitleCont').innerHTML = $('pathname').innerHTML;
		} else {
			$('pathTitleCont').innerHTML = $('inp_paths').options[$('inp_paths').selectedIndex].text;
		}
	}
	var type = $('type').value;
	switch(type) {
	case '':
		$('all').className = 'on'
		$('all').innerHTML = '<div class="left"></div><div class="middle">Все</div><div class="right"></div>';
		$('online').className = 'off';
		$('online').innerHTML = '<a href=" ' + window.location.pathname + '&type=online" onclick="return changeSearchUsersType(\'online\')">Сейчас на сайте</a>';
		$('new').className = 'off';
		$('new').innerHTML = '<a href=" ' + window.location.pathname + '&type=new" onclick="return changeSearchUsersType(\'new\')">Новые</a>';
		break;
	case 'online':
		$('all').className = 'off'
		$('all').innerHTML = '<a href=" ' + window.location.pathname + '" onclick="return changeSearchUsersType(\'\')">Все</a>';
		$('online').className = 'on';
		$('online').innerHTML = '<div class="left"></div><div class="middle">Сейчас на сайте</div><div class="right"></div>';
		$('new').className = 'off';
		$('new').innerHTML = '<a href=" ' + window.location.pathname + '&type=new" onclick="return changeSearchUsersType(\'new\')">Новые</a>';
		break;
	case 'new':
		$('all').className = 'off';
		$('all').innerHTML = '<a href=" ' + window.location.pathname + '" onclick="return changeSearchUsersType(\'\')">Все</a>';
		$('online').className = 'off';
		$('online').innerHTML = '<a href=" ' + window.location.pathname + '&type=online" onclick="return changeSearchUsersType(\'online\')">Сейчас на сайте</a>';
		$('new').className = 'on';
		$('new').innerHTML = '<div class="left"></div><div class="middle">Новые</div><div class="right"></div>';
		break;
	}
} 

var handlerOpenMapPopup = function (req) {
	if(!$('map')) {
		$('mappopupcont').innerHTML = req.responseText;
		$('mappopup').style.top = '50px';
		if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 )
		{
			$('inp_paths').style.visibility = "hidden";
			$('inp_sex').style.visibility = "hidden";
			$('inp_metro').style.visibility = "hidden";
			if($('paging_select')) {
				$('paging_select').style.visibility = "hidden";
			}
		}
		showPopup('mappopup');
	} else {
		$('mappopupcont').innerHTML = req.responseText;
		reShowMapPopup();
	}
}

var handlerGroupAction = function (req) {
	jSonObj = getJSon(req);
	if(jSonObj.link) {
		$('group_actions_'+jSonObj.id).innerHTML = jSonObj.link; 
		$('group_members_'+jSonObj.id).innerHTML = jSonObj.count; 
		switch(jSonObj.action) {
			case 'add': alert('Вы вступили в сообщество "'+jSonObj.title+'"'); break;
			case 'del': alert('Вы покинули собщество "'+jSonObj.title+'"'); break;
		}
	}
}

var handlerPlaceAction = function (req) {
	jSonObj = getJSon(req);
	if(jSonObj.link) {
		$('place_actions_'+jSonObj.id).innerHTML = jSonObj.link; 
		$('place_members_'+jSonObj.id).innerHTML = jSonObj.count;
	}
}

var handlerEventAction = function (req) {
	jSonObj = getJSon(req);
	if(jSonObj.link) {
		$('event_actions_'+jSonObj.id).innerHTML = jSonObj.link; 
		$('event_members_'+jSonObj.id).innerHTML = jSonObj.count;
//		$('event_members_2'+jSonObj.id).innerHTML = jSonObj.count2;
		
	}
}


var handlerOpenPathPopup = function (req) {
	if(req.responseText.length > 0) {
		$('pathsContainer').innerHTML = req.responseText
		getTopForPopup('pathpopup'); 
		showPopup('pathpopup');
	}
}

var handlerDelContact = function (req) {
	jSonObj = getJSon(req);
	if(jSonObj.id) {
		$('contact_'+jSonObj.id).parentNode.removeChild($('contact_'+jSonObj.id));
	}
}

var handlerWriteSearch = function (req) {
	$('common').innerHTML = req.responseText;
	$('footer').style.display = 'block';
}

var handlerChangePrivate = function (req) {
	jSonObj = getJSon(req);
	$('inp_private').value = jSonObj.private;
}
var handlerChangeIncognito = function (req) {
	jSonObj = getJSon(req);
	$('inp_incognito').value = jSonObj.incognito;
}

var handlerAddWallNote = function (req) {
	$('add_wall_note_button').disabled = false;
	jSonObj = getJSon(req);
	if(jSonObj.err_is_error) {
		showFormErrors(jSonObj, 'addnote');
	} else if(jSonObj.objId) {
		newDiv = document.createElement('div');
		newDiv.id = 'note_' + jSonObj.objId;
		newDiv.className = 'wallnote';
		newDiv.innerHTML = jSonObj.obj;
		if($('wall').childNodes.length == 0) {
			$('wall').appendChild(newDiv);
		} else {
			$('wall').insertBefore(newDiv, $('wall').childNodes[0]);
		}		
		$('note').value = '';
	}
}

var handlerDelWallNote = function (req) {
	jSonObj = getJSon(req);
	if (jSonObj.id) {
		$('note_'+jSonObj.id).style.display = "none";
	}
}

var handlerWall = function(req) {
	jSonObj = getJSon(req);
	if (jSonObj.wall) {
		$('add_wall_note_button').disabled = false;
		$('wall').innerHTML = jSonObj.wall;
		if($('note')) $('note').value = '';
	}
}

var handlerSendStationAdminRequest = function (req) {
	alert('Спасибо, ваша заявка принята. С вами свяжутся в ближайшее время');
	hidePopup('moderPopup');
}

var handlerOpenGoMapPopup = function (req) {
	$('mappopupinner').innerHTML = req.responseText + '<br /><a href="#" onclick="return changeClassName(\'gocode\')">Получить код</a>&nbsp;<a href="" onclick="return hidePopup()">Закрыть</a>';
	getTopForPopup('gomappopup',50);
	showPopup('gomappopup');
}

var handlerStationSettings = function(req) {
	jSonObj = getJSon(req);
    if (jSonObj.err_is_error) {
        showFormErorrs(jSonObj, jSonObj.formname);
    } else {
    	switch(jSonObj.formname){
    		case 'load_avatar':
    			var time = new Date();
    			$('loadedImage').src = '';
    			$('station_card_avatar').style.background = 'url(/files/avatars/station/big/'+jSonObj.objId+'.jpg?'+time.getTime() + ') no-repeat scroll left top';
    			hidePopup('loadedPicture');
				break;
    		case 'change_station_info':
    			$('station_description').innerHTML = jSonObj.info;
    			hidePopup();
				break;
    		case 'change_station_history':
    			$('station_history_cont').innerHTML = jSonObj.history;
    			hidePopup();
				break;
			case 'change_station_date':
    			$('station_date').innerHTML = jSonObj.date;
    			hidePopup();
				break;
    	} 
    }
}

var handlerUserInviteFriends = function (req) {
	jSonObj = getJSon(req);
    if (jSonObj.err_is_error) {
        showFormErorrs(jSonObj, jSonObj.formname);
    } else {
		$('invite_friends_inp_invite_friends_err').innerHTML = "";
		$(jSonObj.formname+'_status').style.display = "block";
		$('inp_invite_friends').value="";
		setTimeout("changeClassName('"+jSonObj.formname+'_status'+"')", 3000);
	}	
}

var handlerChangeTimeNeed = function (req) {
	window.location.reload();
}

var handlerWants = function (req) {
	alert('Пользователь будет оповещён.');
	if(req.responseText == 1) {
		$('wants').parentNode.removeChild($('wants'));
	} else if(req.responseText == 2) {
		$('wants_album').parentNode.removeChild($('wants_album'));
	}
}

var handlerManageStatus = function(req) {
	var jSonObj = getJSon(req);
 	if (jSonObj.err_is_error) {
        showFormErorrs(jSonObj, 'selectStatus');
    } else if(jSonObj.data) {    	
        $("tags_status_list").innerHTML = jSonObj.data;
        if($('st_'+jSonObj.id)) $('st_'+jSonObj.id).checked = 'checked'; 
        $("status_input").value="";
        $("status_input").focus();
        if(jSonObj.overflow) {
    		$('addStatusLink').style.display = 'none';
    		$('status_inputdiv').style.display = 'none';
        } 
    }
}

var handlerSelectStatus = function(req) {
    var jSonObj = getJSon(req);
    if (jSonObj) {
        $("status_list").jSonObj = jSonObj;
        var str = '';
        numStatus = 0;
        selectedStatus = 0; //1;
        for (key1 in jSonObj) {
            if (key1.length > 0 && jSonObj[key1] && !isNaN(parseInt(key1))) {
            	numStatus++;  
            	str += '<a href="#" class="selectOff" id="s_field_'+numStatus+'" onclick="return saveStatus(\'' + jSonObj[key1]['name'] + '\', '+jSonObj[key1]['id']+');" onMouseOver="selectStatusTag('+numStatus+', true);" onMouseMove="mouseSelect = 1;" onMouseOut="deselectStatus('+numStatus+');" name="' + jSonObj[key1]['id'] + '">' + jSonObj[key1]['name'] + '</a>';
        	}
        }  
        $("status_list").style.height = numStatus*20;
        $("status_list").innerHTML = '<ul id="status_select">' + str + '</ul>';
        $("status_list").style.display = 'block';
        whiteRequest = 0;
    } else {
    	hideSelectStatusList ();
    }
}

var handlerDelStatus = function (req) {
	jSonObj = getJSon(req);
	if(jSonObj.id) {
		$('tags_status_list').removeChild($('status_'+jSonObj.id));
		if($('st_'+jSonObj.id)) $('st_'+jSonObj.id).checked = false;
		$('addStatusLink').style.display = 'block';
	}
}

var handlerVote = function (req) {
	var jSonObj = getJSon(req);
	if(jSonObj.rating !== false) {		
		$('plus_'+jSonObj.id_postfix).className = 'plus-disabled';
		$('plus_'+jSonObj.id_postfix).onclick = function () {return false;};
		if($('minus_'+jSonObj.id_postfix)) {
			$('minus_'+jSonObj.id_postfix).className = 'minus-disabled';
			$('minus_'+jSonObj.id_postfix).onclick = function () {return false;};
		}
		if(jSonObj.rating > 0) {
			$('rating_'+jSonObj.id_postfix).innerHTML = '+' + jSonObj.rating;
			$('rating_'+jSonObj.id_postfix).className = 'plus';
		} else if(jSonObj.rating < 0) {
			$('rating_'+jSonObj.id_postfix).innerHTML = jSonObj.rating;
			$('rating_'+jSonObj.id_postfix).className = 'minus';
		} else if(jSonObj.rating == 0) {
			$('rating_'+jSonObj.id_postfix).innerHTML = jSonObj.rating;
			$('rating_'+jSonObj.id_postfix).className = 'zero';
		}
	} else {
		if(jSonObj.decline.length > 0) {
			alert(jSonObj.decline);
		}
	}
}

var handlerMakeDaySelect = function (req) {
	$('day_select_container').innerHTML = req.responseText;
}

var handlerMakeDateSelect = function (req) {
	var jSonObj = getJSon(req);
	if(jSonObj.data) {
		$('date_select_container'+(jSonObj.postfix?'_'+jSonObj.postfix:'')).innerHTML = jSonObj.data;
		if(jSonObj.postfix == 'begin' && $('date_select_container_end') ) {
			var regEx = new RegExp('begin', 'g');
			var endDate = jSonObj.data.replace(regEx, 'end');
			$('date_select_container_end').innerHTML = endDate;
		}
	}
}

var handlerYoutube = function (req) {
	var jSonObj = getJSon(req);
	if(!jSonObj.err_is_error) {
		switch(jSonObj.action) {
			case 'add':
				if(jSonObj.token) {
					$('token').value = jSonObj.token;
					form = $(jSonObj.formname);
					form.action = jSonObj.url;					
					form.submit();
				}
			break;
			case 'del':
				if(jSonObj.vId) {
					window.location.href = jSonObj.location;
				}
			break;
		}
	}
}

var handlerSelectPlaceType = function (req) {
	var jSonObj = getJSon(req);
	if(jSonObj.data){
		$('place_select_cont' + jSonObj.postfix).innerHTML = jSonObj.data;
	} else {
		$('place_select_cont' + jSonObj.postfix).innerHTML = 'Мест такого типа пока не существует';
	}
}

var handlerAddGroupAdmin = function (req) {
	var jSonObj = getJSon(req);
	if(jSonObj.act) {
		switch(jSonObj.act) {
			case 'add':
				alert('Модератор добавлен');
				$('make_admin_'+jSonObj.user_id).parentNode.removeChild($('make_admin_'+jSonObj.user_id));
				break;
			case 'del':
				alert('Модератор удален');
				$('user_card_'+jSonObj.user_id).parentNode.removeChild($('user_card_'+jSonObj.user_id));
				break;
		}
	}
}

var handlerDomen = function (req) {
	var jSonObj = getJSon(req);
	if(jSonObj.result) {
		switch(jSonObj.result) {
			case 'free':
				$('domendeclared').style.display = 'none';
				$('domenfree').style.display = 'block';
				$('registerdomen').disabled = false;
				break;
			case 'declared':
				$('domendeclared').style.display = 'block';
				$('domenfree').style.display = 'none';
				$('registerdomen').disabled = 'disabled';
				break;				
			case 'added':
				$('register_domen').innerHTML = '<div id="domenismoderated">Ваша заявка на домен "'+jSonObj.domen+'" принята и в скором времени будет рассмотрена.</div>';
				break;
			case 'allow':
			case 'deny':
			case 'error':
				break;
		}
	}
}

var handlerChangeCategory = function (req) {
	var jSonObj = getJSon(req);
	if(jSonObj.select) {
		$('category_cont').innerHTML = jSonObj.select; 
	} else {
		$('category').disabled = 'disabled';
	}
}

var handlerAudio = function (req) {
	var jSonObj = getJSon(req);
	if(jSonObj.act) {
		switch(jSonObj.act) {
		case 'edit':
			if(jSonObj.artist) {
				$('artist_'+jSonObj.objId).value = jSonObj.artist; 
				$('title_'+jSonObj.objId).value = jSonObj.title;
				$('audio_info_'+jSonObj.objId).innerHTML = jSonObj.artist + ' - ' + jSonObj.title;
			}
			$('audio_info_'+jSonObj.objId).style.display = 'block';
			$('edit_'+jSonObj.objId).style.display = 'none';
			break;
		case 'del':
			if(jSonObj.objId) {
				$('audio_'+jSonObj.objId).parentNode.removeChild($('audio_'+jSonObj.objId));
				$('player_cont2_'+jSonObj.objId).parentNode.removeChild($('player_cont2_'+jSonObj.objId));
			}
		}
	}
}
