var OriginTitle = document.title;
var inboxCheckTimerId = 0;
var setLastTimerId = 1;
var newMessageTimerId = 2;
var aninBit = 1;
var animStatus = 0;

function getById(obj){
	return document.getElementById(obj);	
}


function anim(){
		if(aninBit==0) {
			document.title="**************";
			aninBit = 1;
		} else {
			document.title="ახალი შეტყობინება";
			aninBit = 0;
		}
}

function insComm(id,name){
	opener.getById('communityId').value=id;
	opener.getById('communityName').innerHTML=name;
	opener.getById('communityHidName').value=name;
	opener.focus();
	window.close();
}

function animateTitle(action){
	if(action=='start'){
		if(animStatus==0) {
			anim();
			newMEssageTimerId = setInterval("anim()", 1000);
			animStatus = 1;
		}
	} else {
		if(animStatus) {
			clearInterval(newMEssageTimerId);
		}
		document.title = OriginTitle;
		animStatus = 0;
	}
}

function inputTypes(obj){
	if(obj.type=="radio" || obj.type=="checkbox" || obj.id=="login") {
			return 'solid 1px #FFFFFF';
	} else {
			return 'solid 1px #1D2A5B';
	}
}

function doRequest(config) {
	var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
	req.open(config.method, config.url, true);
	req.onreadystatechange = function() {
		config.callback(req);
	};
	req.setRequestHeader("content-type", "application/x-www-form-urlencoded");
	req.send(config.params);		
}

function goUrl(url){
	document.location=url;
}

function ShowPicture(photoid) {
	var menu  = '<div style="min-width:128px; min-height:96px;text-align:center" id="photo-'+photoid+'"><img src="img/load1.gif" align="absmiddle" /><div>';
	Tip(menu, TITLE, '', STICKY, 1, CLICKCLOSE, true);
	var params = {photoid:photoid};
	$.post("ajax/getphoto.php", params,
	function(data){
		  $('#photo-'+photoid).html(data);
	});
}

function HidePicture(photoid) {
	tt_HideInit();
}


function retriveCity(objValue,sel) {
	if(getById('city')) { getById('city').disabled=true; }
	sel = (sel) ? sel : '147';
	doRequest({
		method: 'GET', 
			url: 'ajax/getCitys.php?country='+objValue+'&sel='+sel+'&nocache=' + (new Date()).getTime(),
		params: '',
		callback: function(req) {
			if (req.readyState == 4 && req.status == 200) {
					getById('citySpan').innerHTML=req.responseText;
			}
		}
	});
	if(getById('city')) { getById('city').disabled=false; }
}

function retriveCityComm(objValue,sel) {
	doRequest({
		method: 'GET', 
			url: 'ajax/getCitys4comm.php?country='+objValue+'&sel='+sel+'&nocache=' + (new Date()).getTime(),
		params: '',
		callback: function(req) {
			if (req.readyState == 4 && req.status == 200) {
					getById('citySpan').innerHTML=req.responseText;
			}
		}
	});
	if(getById('city')) { getById('city').disabled=false; }
}

function retriveCommsValues() {
	if(getById('commName').value!=-1){
		getById('sdate').disabled=false;
		getById('edate').disabled=false;
	} else {
		getById('sdate').disabled=true;
		getById('edate').disabled=true;
	}
}

function saveDelFavorties(act,userId){
	if (act=='delete'){
		if(confirm('დარწმუნებილი ხართ გსურთ ფავორიტებიდან ამოშლა?')==false) { return false; }
	}
	if(act=='add') {
		if(confirm('დარწმუნებილი ხართ გსურთ ფავორიტებში დამატება?')==false) { return false; }
	}
	getById('userFavoriteCenterMenu').innerHTML='<img src="img/ajaxFav.gif" align="absmiddle" /> მოითმინეთ...';
	doRequest({
		method: 'POST', 
		   url: 'ajax/favActions.php?act='+act+'&' + (new Date()).getTime(),
		params: 'userId='+userId,
		callback: function(req) {
			if (req.readyState == 4 && req.status == 200) {
					getById('userFavoriteCenterMenu').innerHTML=req.responseText;
			}
		}
	});
}

function getNewMessage(){
	doRequest({
		method: 'GET', 
			url: 'ajax/ajaxInbox.php?act=read&' + (new Date()).getTime(),
		params: '',
		callback: function(req) {
			if (req.readyState == 4 && req.status == 200) {
					var text = req.responseText;
					if(text=='<action>logout</action>'){
						document.location.reload();	
					} else{ 
					getById('userAlerts').innerHTML = text;
					var actAnim = (text!='&nbsp;') ? 'start' : 'stop';
						animateTitle(actAnim);
					}
			}
		}
	});
}

function lastvisit(){
	doRequest({
		method: 'GET', 
			url: 'ajax/ajaxInbox.php?act=lastvisit&' + (new Date()).getTime(),
		params: '',
		callback: function(req) {
			if (req.readyState == 4 && req.status == 200) {
					var textTMP = req.responseText;
			}
		}
	});
}

function setCrushlist(_userId){
	if(confirm('დარწმუნებილი ხართ გსურთ ამ პიროვნებასთან საიდუმლო კავშირი?')==true) { 
				doRequest({
					method: 'POST', 
						url: 'ajax/ajaxInbox.php?act=crushlist&' + (new Date()).getTime(),
					params: 'userId='+_userId,
					callback: function(req) {
						if (req.readyState == 4 && req.status == 200) {
							if(req.responseText=='ok'){
								//alert('თქვენ დაემატეთ ამ პიროვნების კავშირში');
							}
						}
					}
				});
	}
}


function getInboxCNT(){
	doRequest({
		method: 'GET', 
			url: 'ajax/ajaxInbox.php?act=CNT&' + (new Date()).getTime(),
		params: '',
		callback: function(req) {
			if (req.readyState == 4 && req.status == 200) {
					getById('inboxCNT').innerHTML=req.responseText;
			}
		}
	});
}

function closeNewFriend(){
	animateTitle('stop');
	doRequest({
		method: 'POST', 
			url: 'ajax/ajaxInbox.php?act=AddFriend&' + (new Date()).getTime(),
		params: 'RecId='+getById('RecId').value + '&TypeId='+getById('TypeId').value,
		callback: function(req) {
			if (req.readyState == 4 && req.status == 200) {
					getById('userAlerts').innerHTML=req.responseText;
			}
		}
	});
	document.location.reload();
//	getNewMessage();
}

function commadd(){
//	if(getById('commType')!='-1' && getById('country')!='-1' && getById('city') && getById('city')!='-1'){
		params  = 'commType=' + getById('commType').value;
		params += '&country=' + getById('country').value;
		params += '&city=' + getById('city').value;

		doRequest({
			method: 'POST', 
				url: 'ajax/getcommadd.php?cn=' + (new Date()).getTime(),
			params: params,
			callback: function(req) {
				if (req.readyState == 4 && req.status == 200) {
						getById('commaddget').innerHTML=req.responseText;
				}
			}
		});
//	}
}



function closeNewPM(){
	animateTitle('stop');
	if(getById('RecId')) {
		doRequest({
			method: 'POST', 
				url: 'ajax/ajaxInbox.php?act=markAsRead&' + (new Date()).getTime(),
			params: 'RecId='+getById('RecId').value + '&TypeId='+getById('TypeId').value,
			callback: function(req) {
				if (req.readyState == 4 && req.status == 200) {
						getById('userAlerts').innerHTML=req.responseText;
				}
			}
		});
	}
	getNewMessage();
}


function closeNewInvite(){
	animateTitle('stop');
	if(getById('RecId')) {
		doRequest({
			method: 'POST', 
				url: 'ajax/ajaxInbox.php?act=Invite&' + (new Date()).getTime(),
			params: 'RecId='+getById('RecId').value + '&TypeId='+getById('TypeId').value,
			callback: function(req) {
				if (req.readyState == 4 && req.status == 200) {
						$('#userAlerts').html(req.responseText);
				}
			}
		});
	}
	getNewMessage();
}


function divActionAddComm(objname){
	if(getById(objname).style.display == 'none') {
		getById(objname).style.display = 'block';
		$('#newComm').focus();
	} else {
		getById(objname).style.display = 'none';
		$('#newComm').focus();
	}
	
}

function divAction(objname) {
	if(getById(objname).style.display == 'none') {
		getById('city').disabled = true;
		getById(objname).style.display = 'block';
		$('#newCity').focus();
	} else {
		getById(objname).style.display = 'none';
		getById('city').disabled = false;
		$('#city').focus();
	}
}

function clearCommFields(){
	getById('communityId').value='';
	getById('communityHidName').value='';
	getById('communityName').innerHTML='აირჩიეთ';
	$('#sdate').val('');
	$('#edate').val('');
}

function divActionComm(objname) {
	if(getById(objname).style.display == 'none') {
		getById('commName').disabled = true;
		getById(objname).style.display = 'block';
		$('#newComm').focus();
	} else {
		getById(objname).style.display = 'none';
		getById('commName').disabled = false;
		$('#commName').focus();
	}
}

function addNewComm(obj,commType){
	obj.disabled=true;
	var city = getById('city').value;
	var newComm	= getById('newComm').value;
	var post = 'commType='+commType+'&city='+city+'&newComm='+newComm;
	if(getById('city').value==-1) {
		alert('აირჩიეთ ქალაქი');
	} else {
		doRequest({
			method: 'POST',
			url: 'ajax/addComm.php?nocache=' + (new Date()).getTime(), 
			params: post,
			callback: function(req) {
				if (req.readyState == 4 && req.status == 200) {
						var status = req.responseText.split('[:sep:]');
						if (status[0]=='exists') {
							alert('ასეთი სახელი უკვე არსებობს');	
							divAction('addCommFieldLabel');
						} else if(status[0]=='myalert') {
							alert(status[1]);	
						} else if (status[0]=='addOk') {
							retriveCommsValues();
							divAction('addCommFieldLabel');
						}
				}
			}
		});
	}
	obj.disabled=false;
}

function addNewCity(obj){
	obj.disabled=true;
	var country = getById('country').value;
	var newCity	= getById('newCity').value;
	var post 	= 'country='+country+'&newCity='+newCity;
	if(getById('country').value==-1) {
		alert('აირჩიეთ ქვეყანა');
	} else {
		doRequest({
			method: 'POST',
			url: 'ajax/addCitys.php?nocache=' + (new Date()).getTime(), 
			params: post,
			callback: function(req) {
				if (req.readyState == 4 && req.status == 200) {
						var status = req.responseText.split('[:sep:]');
						if (status[0]=='exists') {
							alert('ასეთი ქალაქი უკვე არსებობს');	
							retriveCity(country,status[1]);
							divAction('addCityFieldLabel');
						} else if(status[0]=='myalert') {
							alert(status[1]);	
						} else if (status[0]=='addOk') {
							retriveCity(country,status[1]);
							divAction('addCityFieldLabel');
						}
				}
			}
		});
	}
	obj.disabled=false;
}

function popupImg(owner,img,w,h){
	top_val = (screen.height - h)/2 - 30;
	if (top_val < 0){ top_val	= 0; }
	left_val = (screen.width - w)/2;
	var win = window.open('image.php?userId='+owner+'&img='+img, 'win', "toolbar=0,location=0,status=1,menubar=0,scrollbars=1,resizable=0,width="+ w +",height="+ h +", top="+ top_val +"px,left="+ left_val + "px");	
	if(win) { win.focus(); }
}


function popupImgGroup(owner,img,w,h){
	top_val = (screen.height - h)/2 - 30;
	if (top_val < 0){ top_val	= 0; }
	left_val = (screen.width - w)/2;
	var win = window.open('imageGroup.php?userId='+owner+'&img='+img, 'win', "toolbar=0,location=0,status=1,menubar=0,scrollbars=1,resizable=0,width="+ w +",height="+ h +", top="+ top_val +"px,left="+ left_val + "px");	
	if(win) { win.focus(); }
}

function chooseComm(ctype,w,h){
	page = 'ajax/chooseComm.php?ctype='+ctype+'&city='+getById('city').value;
	popup(page,w,h);
}

function popup(page,w,h){
	top_val = (screen.height - h)/2 - 30;
	if (top_val < 0){ top_val	= 0; }
	left_val = (screen.width - w)/2;
	var newWin = window.open(page, 'win', "toolbar=0,location=0,status=1,menubar=0,scrollbars=1,resizable=0,width="+ w +",height="+ h +", top="+ top_val +"px,left="+ left_val + "px");
	newWin.focus();
}

function thisTime(){
	return (new Date()).getTime();	
}

function image(obj){
	var imgs = new Array('jpg','peg','gif');
	var ret=0;
	var fileName = obj.value.toLowerCase();
	for (var i=0; i<imgs.length; i++) {
		ret += (imgs[i]==fileName.substr(-3)) ? 1 : 0;
	}
	if (ret<1) { 
		obj.value='';
		alert("ფაილის დასაშვები ტიპებია მხოლოდ jpg, jpeg და gif");
	}
}

function PMcountThis(obj){
	var maxSymbols = 1000;
	if(obj.value.length>maxSymbols) { 
	obj.value = obj.value.substring(0,maxSymbols);
	alert('შეტყობინებაში სიმბოლოების მაქსიმალური რაოდენობა '+1000);
	}
	getById('charCNT').value=(maxSymbols-obj.value.length)
}
function focusById(obj){
	getById(obj).focus();
}

function checkAllinbox(obj,maxId){
	for (var i=1; i<=maxId; i++) {
		getById('InbMailCheckbox_'+i).checked = (obj.checked==true) ? true :  false;
	}
}

function checkAllcheck(obj,otherObj,maxId){
	for (var i=1; i<=maxId; i++) {
		getById(otherObj+i).checked = (obj.checked==true) ? true :  false;
	}
}

var menuP = 0;
var menuD = 0;

function initVar(stat){
		menuD= stat;
		menuP= 0;
}

function show(_flname,_userId,_userPhotoId){
	menuP = 1;
	menuD = 0;
	var ImgOpen = (_userPhotoId!=1000000001) ?
		'<a href="javascript:void(0)" onclick="popupImg(\''+_userId+'\',\''+_userPhotoId+'\',\'670\',\'680\')" src="img.php?img='+_userPhotoId+'&size=m" />ფოტოს გადიდება<\/a>' :  
	 	'<span>ფოტოს გადიდება</span>';
	var menu  = '<div class="popMenu" onmouseover="initVar(1)"  onmouseout="initVar(0);hide()">';
		menu += '<img src="img/pop_image.png" align="absmiddle"> '+ImgOpen+'<br>';
		menu += '<img src="img/pop_newMail.png" align="absmiddle"> <a onclick="popup(\'ajax/newMessage.php?act=FromUser&Id='+_userId+'\',500,500)" href="javascript:void(0)">წერილის გაგზავნა<\/a><br>';
		menu += '<img src="img/corr.png" align="absmiddle"> <a href="?p=user&sp=correspondence&userId='+_userId+'">მიმოწერის ჩვენება<\/a><br>';
		menu += '<img src="img/secret.png" align="absmiddle"> <a href="javascript:void(0)" onClick="setCrushlist('+_userId+')">კავშირებში დამატება<\/a><br>';
		menu += '<img src="img/rightarrow.png" align="absmiddle"> <a href="?p=user&sp=invitegroup&inviteId='+_userId+'">ჯგუფში მოწვევა<\/a><br>';
		menu += "<hr>";
		menu += '<img src="img/pop_friends.png" align="absmiddle"> <a href="?p=user&sp=frs&userId='+_userId+'">მეგობრები<\/a><br>';
		menu += '<img src="img/pop_ffs.png" align="absmiddle"> <a href="?p=user&sp=ffrs&userId='+_userId+'">მეგობრების მეგობრები<\/a><br>';
		menu += '<img src="img/pop_gallery.png" align="absmiddle"> <a href="?p=user&sp=photogallery&userId='+_userId+'">ფოტოგალერეა<\/a><br>';
		menu += '<img src="img/pop_comm.png" align="absmiddle"> <a href="?p=user&sp=community&userId='+_userId+'">საზოგადოება<\/a><br>';
		menu += '<img src="img/pop_about.png" align="absmiddle">  <a href="?p=user&sp=about&userId='+_userId+'">შესახებ<\/a><br>';
		menu += "</div>";
	Tip(menu, TITLE, _flname, STICKY, 1, CLICKCLOSE, true);
}

var tkio  = 0;
var tkio1 = 0;

function hide1(step){
	if(step==2){
		if(menuD==0 && menuP==0){
			var tkio=setTimeout("tt_HideInit()",1000);
		}
	} else {
			var tkio1=setTimeout("hide1(2)",1000);		
	}
}

function hide(){
	menuP = 0;
	hide1();
}

var imgObj = null;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function statusChangeDom(txt){
	var del = (txt!='') ? '<td valign="top" id="status_del"><span onclick="delstatus()">წაშლა</span></td>' : '<td valign="top">&nbsp;</td>';
		return '<table cellpadding="0" cellspacing="0" border="0" height="50" width="295">' +
				'<tr><td>&nbsp;</td>' + del + '</tr>' +
				'<tr>' +
				'<td valign="top"><input type="text" id="status" name="status" value="' + txt + '" align="absmiddle" /></td>' +
				'<td valign="top" width="40"><img src="img/addStatus.png" onclick="changestatus(this)"/></td>' +
				'</tr>' +
				'</table>';
}

function statusExistsDom(txt){
		return '<table cellpadding="0" cellspacing="0" border="0" height="50" width="295">' +
				'<tr><td>&nbsp;</td>' + 
				'<td valign="top" id="status_del"><span onclick="delstatus()">წაშლა</span></td>' +
				'</tr>' +
				'<tr>' +
				'<td valign="top" colspan="2" onclick="getchangestatus()" id="statex" style="padding-bottom:10px; padding-left:10px; cursor:pointer"><div style="overflow:hidden; width:275px">' + txt + '</div></td>' +
				'</tr>' +
				'</table>';
}

function getchangestatus(){
	$('#statusTool').html(statusChangeDom( $('#statex div').html() ));
	  GeoKBD.map('statusForm', ['status']);
	$('#status').focus();
}

function changestatus(obj){
	$(obj).attr('src','img/ajaxFav.gif');
	$(obj).removeAttr('onclick');
	$(obj).removeAttr('style');
	$.post("ajax/addStatus.php", {status:$('#status').val()},
	function(data){
		if(data!='') {
		  $('#statusTool').html( statusExistsDom(data));
		} else {
		  $('#statusTool').html(statusChangeDom(''));
		  GeoKBD.map('statusForm', ['status']);
		}
  });
}

function delstatus(){
	$('#status_del').html('');
	$('#statusTool').html(statusChangeDom(''));
    GeoKBD.map('statusForm', ['status']);
	GeoKBD.map({fields: ['#status']});
	$('#chstbut').attr('src','img/ajaxFav.gif');
	$('#chstbut').removeAttr('onclick');
	$('#chstbut').removeAttr('style');
	$.post("ajax/addStatus.php", {status:''},
	function(data){ return; });
}

$.hideAllAlert = function(id){
	$.cookie('mfah', id, {expires:1000})
	$('#'+id).slideUp();
}

$.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};