/*********************************************************************************************************/
var autoRefreshTimeOutValue;
var jsClockTimeOutValue;
var minutes=60000;
var loopDuration = minutes*1;
var countClock=60;
var timeoutVal="";
var msgCounter=0;
var totalMsgCount=15;
var customCounter=totalMsgCount;
var shuandaMessengerTimeout;
var shuandaMessengerTimeoutWithoutCookie;
var ShuandaMessengercookieName='read_messages';

function submit_selection() {
	dgid("bulten_selector").submit();
}


function LTrim( value ) {

var re = /,*((,+,*)*)/;
return value.replace(re, "$1");

}

// Removes ending whitespaces
function RTrim( value ) {

var re = /((,*,+)*),*/;
return value.replace(re, "$1");

}

// Removes leading and ending whitespaces
function trim( value ) {

return LTrim(RTrim(value));

}


function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return "";
	}
}	

function setCookie(name, value, days)
{
    //Fix Days
    if(days==null || days=="")days=365;

    // Set Date
    var d=new Date(); 
    d.setTime(d.getTime()+(days*24*60*60*1000));  
    var expires="; expires="+d.toGMTString();  

    // Write Cookie
    document.cookie = name+"="+value+expires+"; path=/"; 
} // function setCookie(name, value, days)


function Kapat() {
	changeOpac(0, 'fixme');
	writeShuandaMessengerCookie();
	//setTimeout("opacity('fixme', 0, 100, 500)", 10000);
}

function writeShuandaMessengerCookie() {
	var msgList=dgid("serialized_message_list").value;
	var existing_cookie_vals="";
	existing_cookie_vals=Get_Cookie(ShuandaMessengercookieName);
	var newCookieVal;
	if(existing_cookie_vals !='')
		newCookieVal=existing_cookie_vals+","+msgList;
	else
		newCookieVal=msgList;
	setCookie(ShuandaMessengercookieName, trim(newCookieVal), 1);
}

function showMessenger(setCookie) {
	if(setCookie == 1) 
		writeShuandaMessengerCookie();
	changeOpac(0, 'fixme');
	dgid("fixme").style.display="none";
	var msgContent='';
	var msgBoxMsgTitle='';
	var output='';
	var allowClose='';
	var msgDuration=0;
	var forCookie="";
	var msgID;
	var readMessagesFromCookie=Get_Cookie(ShuandaMessengercookieName);
	$.ajax({
			url: '/ajax/getCustomNotifications.php',
			type: 'POST',
			data: 'readMesages='+readMessagesFromCookie,
			dataType:'xml',
			timeout: 10000,
			error: function(){
					//alert(jsAjaxTimeOutError);
			},
			success: function(response){
				var msgCount=0;
				jQuery("/shuandamessenger/notification_info", response).each(function(){
					msgCount = jQuery("msg_count", this).text();
					allowClose = jQuery("box_closable", this).text();
					msgDuration=jQuery("box_duration", this).text();
				});
				
				if(allowClose == 1) {
					dgid("closeArea").style.display="block";
				}
				else {
					dgid("closeArea").style.display="none";
				}
				if(msgCount >0) {
					dgid("fixme").style.display="block";
					jQuery("/shuandamessenger/messages/message_info", response).each(function(){
						msgContent = jQuery("msgContent", this).text();
						msgBoxMsgTitle = jQuery("msgBoxMsgTitle", this).text();
						msgID=jQuery("msgID", this).text();
						if(forCookie !="")
							forCookie=forCookie+","+msgID;
						else
							forCookie=msgID;
						output=output+'<div id="msgBoxMsgTitle">'+msgBoxMsgTitle+'</div><div class="messgengerMsgArea">'+msgContent+'</div><br>';
					});
					dgid("serialized_message_list").value=trim(forCookie);
					$('#msgResponsePanel').html(output);
					setTimeout("autoStart()", 2000);
					clearTimeout(shuandaMessengerTimeout);
					clearTimeout(shuandaMessengerTimeoutWithoutCookie);
					refreshShuandaMessengerMessages();
					shuandaMessengerTimeout=setTimeout("showMessenger(1)", msgDuration);
				}
			}
	});
}

function refreshShuandaMessengerMessages() {
	shuandaMessengerTimeoutWithoutCookie=setTimeout("showMessenger()", minutes);
}


function autoStart() {
	opacity('fixme', 0, 100, 500);
}

function travel() {
	msgCounter++;
	if(msgCounter <totalMsgCount) {
		timeoutVal=setTimeout("travel()",5000);
		//document.getElementById("msgcount").innerHTML=tab_index;
		$("#gmaps_container").get(0).gmap.jq_maps.goTo($("#gmaps_container").get(0), msgCounter-1);
	}
	else {
		clearTimeout(timeoutVal);
		msgCounter=0;
		checkNewMessagesVision("NewMessages");
		//window.location.reload();
	}
}


function checkNewMessagesVision(targetDiv) {
	//document.getElementById("waitLog").style.display="block";
	//document.getElementById("waitLog2").style.display="block";
	jQuery.ajax({
		url: '/ajax/msg_collector.php',
		type: 'POST',
		data: 'a=bb',
		dataType:'xml',
		timeout: 95000,
		error: function(){
			alert(jsAjaxTimeOutError);
		},
		success: function(response){
			var simpleContent = "";
			var username = "";
			var maximizedContent = "";
			var latitude = "";
			var longitude = "";
			var zoom = "";
			var icon = "";
			var time = "";
			var source="";
			var user_image = "";
			var user_message = "";
			var arrayIndex=0;
			jQuery("/shuandavision/messages", response).each(function(){
				simpleContent = jQuery("simpleContent", this).text();
				username = jQuery("username", this).text();
				maximizedContent = jQuery("maximizedContent", this).text();
				latitude = jQuery("latitude", this).text();
				longitude = jQuery("longitude", this).text();
				zoom = jQuery("zoom", this).text();
				source = jQuery("source", this).text();
				icon = jQuery("icon", this).text();
				time= jQuery("time", this).text();
				user_image = jQuery("user_image", this).text();
				user_message= jQuery("user_message", this).text();
				locations_data.locations[arrayIndex].simpleContent=simpleContent;
				locations_data.locations[arrayIndex].username=username;
				locations_data.locations[arrayIndex].source=source;
				locations_data.locations[arrayIndex].maximizedContent=maximizedContent;
				locations_data.locations[arrayIndex].latitude=latitude;
				locations_data.locations[arrayIndex].longitude=longitude;
				locations_data.locations[arrayIndex].zoom=zoom;
				locations_data.locations[arrayIndex].icon=icon;
				locations_data.locations[arrayIndex].time=time;
				locations_data.locations[arrayIndex].user_image=user_image;
				locations_data.locations[arrayIndex].user_message=user_message;
				arrayIndex++;
			});
		//	document.getElementById("waitLog").style.display="none";
		//	document.getElementById("waitLog2").style.display="none";
			$("#gmaps_container").gmaps({
				data: locations_data,
				infopanel: $("#gmaps_info").get(0),
				relativepath: "http://www.shuanda.net/"
			});
			travel();
			return;
		}
	});
}


function closeMe(obj) {
	document.getElementById(obj).style.display='none';
//	document.getElementById("dummy").style.display='none';
	//document.getElementById("Disabler").style.display='none';
}

function startSelector() {
	document.getElementById("conditionPop").style.display='block';
	//document.getElementById("dummy").style.display='block';
//	document.getElementById("Disabler").style.display='block';
}



function dgByName(x) {
	return document.getElementsByName(x);
}

function getSelectedValueFromRadioButtonGroup(groupName) {
	var val = 0;
	var radioGroupObject=dgByName(groupName);
	for( i = 0; i < radioGroupObject.length; i++ ){
		if( radioGroupObject[i].checked == true )
			val = radioGroupObject[i].value;
	}
	return val;
} 


if(document.getElementById) {
var getRefById = function(id) {
return document.getElementById(id);
};
} else if(document.all) {
var getRefById = function(id) {
return document.all[id];
};
} else {
var getRefById = function() {
return null;
};
}

function insertText(str) {
var e = getRefById('message'), s = null, r = null;

if(e) {
if((s = document.selection) && s.createRange) {
var repos = false;

/* Element must have focus otherwise text
* will be written into other elements. */
e.focus();
if((r = s.createRange())) {
if(r.text.length) {repos = true;}
r.text = str + " ";
/* Clear the selection to stop continuous
* overwriting of inserted text. */
if(repos && s.empty) {s.empty();}
}
} else {
e.value += str + " ";
}
}
}


function smileySelector() {
	document.getElementById("smileyPop").style.display='block';
	//document.getElementById("dummy").style.display='block';
//	document.getElementById("Disabler").style.display='block';
}

function changeCondition(userID,obj,current_cond_id) {
//	jQuery("#myHomeWait").html('');
	jQuery("#cond_waiting_div").html('<img src="'+jsImagePath+'/loading.gif" width="20" height="20" border="0" align="absmiddle" alt="Yükleniyor...">');
//	document.getElementById("waiting_div").style.display="inline";
	//document.getElementById("waitLog").style.display="block";
	
	var condition=getSelectedValueFromRadioButtonGroup(obj);
	jQuery.ajax({
		url: '/ajax/setUserStatus.php',
		type: 'POST',
		data: 'user_id='+userID+'&condition='+condition,
		timeout: 10000,
		error: function(){
			alert(jsAjaxTimeOutError);
		},
		success: function(response){
			
			var radioGroupObject=dgByName(obj);
			for( i = 0; i < radioGroupObject.length; i++ ){
				var oldText=dgid('cond_text_'+i).innerHTML;
				var newText;
				if( radioGroupObject[i].value == condition ) {
					dgid('cond_text_'+i).className='bold_condition';
				}
				else {
					dgid('cond_text_'+i).className='normal_condition';
				}
			}
			jQuery("#currentConditionText").html(response);
			jQuery("#cond_waiting_div").html('');
			closeMe('conditionPop');
			if (current_cond_id) {
				if (condition==current_cond_id) {
					dgid('true_cond').style.display='block';
					dgid('wrong_cond').style.display='none';
				} else if (condition!=current_cond_id) {
					dgid('true_cond').style.display='none';
					dgid('wrong_cond').style.display='block';
				}
			}
	
		}
	});
	return;
}


function overMe(toOver,toNormal) {
	document.getElementById(toOver).className='mesajlarim_visited';
	document.getElementById(toNormal).className='mesajlarim';
}

function getHomePage(mode,pageNo) {
		autoScreenRefresh(mode,pageNo);
}

function jsClock() {
	if(countClock <= 0)
		dgid("JSTimer").innerHTML='Güncelleniyor...';
	else {
		//display='Mesajların güncellenmesine '+countClock+' sn kaldı' ;
		display=counterMsg+' '+countClock+' '+counterMsgLast;
		dgid("JSTimer").innerHTML=display;
	}
	dgid("JSTimer").style.display="block";
	jsClockTimeOutValue=setTimeout("jsClock()",1000);
	countClock--;
}


function autoScreenRefresh(mode,pageNo) {
	jQuery("#myHomeWait").html('');
	document.getElementById("waitLog").style.display="block";
	jQuery.ajax({
		url: '/ajax/getUserHomePage.php',
		type: 'POST',
		data: 'friends='+mode+'&pn='+pageNo,
		timeout: 10000,
		error: function(){
			//alert('Hata! Lütfen tekrar deneyin.');
			window.location.reload();
		},
		success: function(response){
			jQuery("#myHome").html(response);
			jQuery("#myHomeWait").html('');
			document.getElementById("waitLog").style.display="none";
			if(pageNo ==1) {
				clearTimeout(autoRefreshTimeOutValue);
				autoRefreshTimeOutValue=setTimeout('autoScreenRefresh('+mode+','+pageNo+')',loopDuration);
				countClock=60;
				clearTimeout(jsClockTimeOutValue);
				
				jsClock();
			}
			else {
				clearTimeout(autoRefreshTimeOutValue);
				clearTimeout(jsClockTimeOutValue);
				dgid("JSTimer").innerHTML='';
				dgid("JSTimer").style.display="none";
			}
			fillUserTools();
		}
	});
	return;
}
function checkAvailability(username) {
	jQuery("#CUR").html('<img src="'+jsImagePath+'/loading.gif" width="20" height="20" border="0" alt="Yükleniyor...">');
	jQuery.ajax({
		url: '/test/checkUsername.php',
		type: 'POST',
		data: 'username='+username,
		timeout: 10000,
		error: function(){
			alert(jsAjaxTimeOutError);
		},
		success: function(response){
			jQuery("#CUR").html('');

			if (response == 'yok') {
				document.forms['signup_form'].UserExists.value="false";
				jQuery("#CUR").css("color","green");
			} else {
				document.forms['signup_form'].UserExists.value="true";
				jQuery("#CUR").css("color","red");
			}

			if (response == 'gecersiz') {
				jQuery("#CUR").html('Geçersiz kullanıcı adı');
			} else if (response == 'var') {
				jQuery("#CUR").html('Bu kullanıcı adı kullanılmaktadır!');
			} else if (response == 'uygunsuz') {
				jQuery("#CUR").html('Uygunsuz kullanıcı adı!');
			} else if (response == 'yok') {
				jQuery("#CUR").html('Bu kullanıcı adını kullanabilirsiniz');
			} else if (response == 'bosluk') {
				jQuery("#CUR").html('Kullanıcı adında boşluk kullanmayınız!');
			} 
		}
	});
}

function checkGrpAvailability(group_name) {
	jQuery("#CUR").html('<img src="'+jsImagePath+'/loading.gif" width="20" height="20" border="0" alt="Yükleniyor...">');
	jQuery.ajax({
		url: '/test/checkGroup_Name.php',
		type: 'POST',
		data: 'group_name='+group_name,
		timeout: 10000,
		error: function(){
			alert(jsAjaxTimeOutError);
		},
		success: function(response){
			jQuery("#CUR").html('');

			if (response == 'yok') {
				document.forms['group_form'].GroupExists.value="false";
				jQuery("#CUR").css("color","green");
			} else {
				document.forms['group_form'].GroupExists.value="true";
				jQuery("#CUR").css("color","red");
			}

			if (response == 'gecersiz') {
				jQuery("#CUR").html('Geçersiz grup adı');
			} else if (response == 'var') {
				jQuery("#CUR").html('Bu grup adı kullanılmaktadır!');
			} else if (response == 'yok') {
				jQuery("#CUR").html('Bu grup adını kullanabilirsiniz');
			}
		}
	});
}

function setTimeZone() {
	var countryID=dgid("country_id").value;
	var timezoneObj=dgid("timezone_id");
	if(gmtCodes[countryID])
		timezoneObj.value=gmtCodes[countryID];
	else
		timezoneObj.value=16;
}

function getCityList() {
//	document.getElementById("displayCities").style.display="none";
	dgid("Citylist").style.display="none";
	var countryId=document.getElementById("country_id").value;
	var locationID="";
	if(dgid("location"))
		locationID=dgid("location").value;
	MBGAjax(AJX_GET_CITY_LIST_URL, showCityList, 'POST', '&ulke_id='+countryId+'&city='+locationID);
}

function checkSearchForm(formOnj) {
	var formVld = new Validator();
	formVld.AddField("search_area", "Aranacak Kelime", true);
	if (formVld.Validate())
		return true;
	else
		return false;
}
function fillUserTools() {
	var divID='ajaxUserTools';
	//MBGAjaxDIV(AJX_GET_USR_TOOLS_URL, divID, '&a=b');
	

	jQuery("#"+divID).html('<div class="login_form_small_texts" align="center"><img src="'+jsImagePath+'/loading.gif" width="20" height="20" border="0" alt="Yükleniyor..." align="absmiddle">Lütfen bekleyin...</div>');
	jQuery.ajax({
		url: AJX_GET_USR_TOOLS_URL,
		type: 'POST',
		data: '',
		timeout: 10000,
		error: function(){
			jQuery("#"+divID).html(jsAjaxTimeOutError);
		},
		success: function(response){
			jQuery("#"+divID).html(response);
		}
	});
	
	
	
}

function dgid(val) {
	return document.getElementById(val);
}
function addFavorites(message_id, divID, what) {
	if(what == 'del')
	{
		var onay = confirm("Silmek istediğinize emin misiniz?");
		if (onay) {
			MBGAjax(AJX_REMOVE_FAV_URL, callBackFavouriteDelete, 'POST', '&message_id='+message_id+'&what='+what);
		}
		else
			return;
	}
	else
		MBGAjaxDivCallBack(divID,AJX_FAVORITES_URL,callBackFunction, '&message_id='+message_id+'&what='+what);
} 
function addAbuse(message_id, divID, what) {
		var onay = confirm("Bu Mesajı Şikayet Ediyorum !");
		if (onay) {
			MBGAjaxDivCallBack(divID,'/ajax/addabuse',callBackFunction, '&message_id='+message_id);
		}
		else
			return;
}

function addBlackList(user_id, divID, what) {
		var onay = confirm("Bu Kullanıcıyı Bloke Ederek IP sini Karalisteye Ekliyorsunuz !");
		if (onay) {
			MBGAjaxDivCallBack(divID,'/ajax/addblacklist',callBackFunction, '&user_id='+user_id);
		}
		else
			return;
}
function removeMessage(message_id, what,isRefresh) {
	MBGAjax(AJX_REMOVE_MSG_URL, callBackFunctionMessageDelete, 'POST', '&mid='+message_id+'&what='+what+'&refresh_mode='+isRefresh);
} 

function removeDirectMessage(message_id, what,isRefresh) {
	MBGAjax(AJX_REMOVE_DIRECT_URL, callBackFunctionDirectMessageDelete, 'POST', '&mid='+message_id+'&what='+what+'&refresh_mode='+isRefresh);
}

function removeGroup(group_id, what,isRefresh) {
	MBGAjax(AJX_REMOVE_GRP_URL, callBackFunctionGroupDelete, 'POST', '&gid='+group_id+'&what='+what+'&refresh_mode='+isRefresh);
} 

function removeComment(comment_id, what,isRefresh) {
	MBGAjax(AJX_REMOVE_COMMENT_URL, callBackFunctionCommentDelete, 'POST', '&cid='+comment_id+'&what='+what+'&refresh_mode='+isRefresh);
} 

function removeFriend(friend_id, what,isRefresh) {
	MBGAjax(AJX_REMOVE_FRIEND_URL, callBackFunctionDeleteFriend, 'POST', '&fid='+friend_id+'&what='+what+'&refresh_mode='+isRefresh);
} 

function onayla(messageID,islem,isRefresh) {
	var onay = confirm(islem + " istediğinize emin misiniz?");
	if (onay) {
		removeMessage(messageID, 'delete',isRefresh);
		//setTimeout('location.reload(true)', 500);
	}
	return false;
}	

function onaylaGroup(groupID,islem,isRefresh) {
	var onay = confirm(islem + " istediğinize emin misiniz?");
	if (onay) {
		removeGroup(groupID, 'delete',isRefresh);
		//setTimeout('location.reload(true)', 500);
	}
	return false;
}

function yorum_sil(commentID,islem,isRefresh) {
	var onay = confirm(islem + " istediğinize emin misiniz?");
	if (onay) {
		removeComment(commentID, 'delete',isRefresh);
		//setTimeout('location.reload(true)', 500);
	}
	return false;
}	

function ozel_sil(messageID,islem,isRefresh) {
	var onay = confirm(islem + " istediğinize emin misiniz?");
	if (onay) {
		removeDirectMessage(messageID, 'delete',isRefresh);
		//setTimeout('location.reload(true)', 500);
	}
	return false;
}	


function removeFriendConfirm(friend_id,islem,isRefresh) {
	var onay = confirm(islem + " istediğinize emin misiniz?");
	if (onay) {
		removeFriend(friend_id, islem,isRefresh)
		//setTimeout('location.reload(true)', 500);
	}
	else
		return;
}	


function addFriend(friend_id, divID, what) {
	MBGAjaxDivCallBack(divID,AJX_MAKE_FRIENDS_URL,callBackFunction, '&friend_id='+friend_id+'&what='+what);
} 


function actionWithConfirm(url,islem)
{
	var onay=confirm(islem + " istediğinize emin misiniz?");
	if (onay) {
		window.location.href=url;
	}
	else
		return;
}

function uncheck_all()
{
	var checks = document.getElementsByTagName("input");
	var tip;

	for(i = 0; i < checks.length; i++)
	{
		tip = checks[i].type;
		
		if(tip == "checkbox") {
			checks[i].checked = false;
		}
	}
}

function check_all()
{
	var checks = document.getElementsByTagName("input");
	var tip;

	for(i = 0; i < checks.length; i++)
	{
		tip = checks[i].type;
		
		if(tip == "checkbox") {
			checks[i].checked = true;
		}
	}
}

function add_friend(uid)
{
	jQuery.ajax({
	url: '/getContacts.php',
	type: 'POST',
	data: 'addMyFriend=true&friend_id='+uid,
	timeout: 10000,
	error: function(){
		alert(jsAjaxTimeOutError);
	},
	success: function(response){
		jQuery("#td_friend_"+uid).html(response);

	}
	});

	ajax('/getContacts.php', 'td_friend_'+uid, '?addMyFriend=true&freind_id='+uid, 'div');
}
