var browser_is_ie = false;
var request_id = 0;

function createRequestObject(){
	var request_o;
	var browser = navigator.appName;
	if  (browser == "Microsoft Internet Explorer") {
		/* Create the object using MSIE's method */
		request_o = new ActiveXObject("Microsoft.XMLHTTP");
		browser_is_ie = true;
	}
	else {
		/* Create the object using other browsers method */
		request_o = new XMLHttpRequest();
	}
	return request_o;
}

var http = createRequestObject();

function reloadParts() {
	var currentDate = new Date();
	
	// get data every 15th second
	if (currentDate.getSeconds()%15 == 0) {
		getData();
	}
}

function handleData() {
	if (http.readyState == 4) {
		var response = http.responseText;
		
		if (response) {
			var jsonTotalResponse = eval('(' + response + ')');

			for (var o in jsonTotalResponse) {
				eval(o + '(jsonTotalResponse[o]);');
			}
		}
	}
}

function getData(force_user_list) {
	request_id++;

	if (force_user_list == undefined)	{
		force_user_list = 0;
	}

	try {
		/*if (window.frames['chat_internal'] != undefined && window.frames['chat_internal'] != undefined ) {
			var max_msg_id = document.forms['chat_form'].max_msg_id.value;
			var chat_action = 'get_data';
		}
		else {
			var max_msg_id = 0;
			var chat_action = '';
		}
		http.open('get', 'internal_request.php?request_id=' + request_id + '&chat_action=' + chat_action + '&max_msg_id=' + max_msg_id + '&force_user_list=' + force_user_list);
		*/
		http.open('get', 'internal_request.php?request_id=' + request_id);

		http.onreadystatechange = function(aEvt) {
			handleData();
		}

		http.send(null);
	}
	catch (e) { }
}

function closePassiveChat() {
	try {
		http.open('get', 'internal_request.php?chat_action=close_chat');
		http.send(null);
	}
	catch (e)	{	}
}

function handleMessages(jsonResponse) {
	if (window.frames['chat_internal'] != undefined && window.frames['chat_internal'].document.getElementById('messages') != undefined) {
		
		if (jsonResponse.messages != undefined) {
			document.forms['chat_form'].max_msg_id.value = jsonResponse.max_msg_id;

			var str = '';

			for (var i=0; i<jsonResponse.messages.length; i++) {
				str += '<b><span class=' + ((jsonResponse.messages[i].is_author)?'self_text':'other_text') + '>' + jsonResponse.messages[i].username + "</span></b>:<br>\n";
				str += jsonResponse.messages[i].message + "<br>\n";
			}

			window.frames['chat_internal'].document.getElementById('messages').innerHTML += str;

			var objDiv = window.frames['chat_internal'].document.getElementById("messages");
			window.frames['chat_internal'].scrollTo(0, objDiv.scrollHeight);
		}
	}
}

function handleUsers(jsonResponse) {
	if (window.frames['chat_users'] != undefined && window.frames['chat_users'].document.getElementById('users') != undefined) {

		if (jsonResponse)	{
			if (jsonResponse!='')	{
				var str = '<table width="100%" cellpadding=0 cellspacing=0 class=user_list>';

				for (var i=0; i<jsonResponse.users.length; i++) {
					str += '<tr valign=top>';
					str += '<td><img src="image_' + jsonResponse.users[i].compound_photo_sid + '_5.jpg" onContextMenu="return false" class=user></td>';

					switch (jsonResponse.content) {
						case 'chat_user':
							str += '<td>' + jsonResponse.users[i].name;
							break;

						case 'requested_user':
							str += '<td><b>' + jsonResponse.users[i].name + '</b>' + jsonResponse.users[i].button_src;
							break;

						case 'all':
							str += '<td><a href="javascript: void invite(' + jsonResponse.users[i].user_sid + ')">' + jsonResponse.users[i].name + '</a>';
							break;
					}

					str += '<br><span class=gray>' + jsonResponse.users[i].ages + '</span> <i>' + jsonResponse.users[i].city + '</i></td>';
				}

				str += '</tr></table>';
			}
			else {
				var str = '';
			}

			window.frames['chat_users'].document.getElementById('users').innerHTML = str;
		}
	}
}

function handleVideoRequests(jsonResponse) {
	if (jsonResponse!='') {
		openCommunicatorWindow(jsonResponse.to, jsonResponse.from, 'en');
	}
}

function submitForm(field) {
	var xhr = createRequestObject();

	var msg = field.value;

	xhr.open("POST", "internal_request.php?action=submit_form", false);
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xhr.send("message=" + msg);

	getData();
}

function handleNotifications(jsonResponse) {

	if (jsonResponse) {
		switch (jsonResponse.content) {
			case 'protocol:chat_is_closed':
				if (window.frames['chat_internal'] != undefined) {
					if (window.document.forms['chat_form'].elements['chat_is_closed'].value==0) {
						window.document.forms['chat_form'].elements['chat_is_closed'].value = 1;
						window.document.forms['chat_form'].elements['visible_message'].disabled = true;
						window.frames['chat_internal'].document.getElementById('messages').innerHTML += '*** The chat has been closed.<br>';
						window.document.getElementById('close_button').style.visibility = 'hidden';
						closePassiveChat();
					}
				}
				break;

			case 'protocol:chat_request_denial':
				if (window.frames['chat_internal'] != undefined) {
					window.alert('Your chat invitation has been denied.');
					parent.frames['chat_internal'].document.getElementById('messages').innerHTML = '*** You should invite somebody from the list on the right.<br>';
				}
				break;

			case 'protocol:chat_request_acceptance':
				if (window.frames['chat_internal'] != undefined) {
					window.frames['chat_internal'].document.getElementById('messages').innerHTML = '*** The chat is now open.<br>';
					window.document.forms['chat_form'].elements['visible_message'].disabled = false;
					window.document.getElementById('close_button').style.visibility = 'visible';
					window.frames['chat_users'].document.getElementById('users').innerHTML = 'Loading...';
				}
				break;

			case 'protocol:chat_new_msg':
				if (window.frames['chat_internal'] == undefined) {
					var element = document.getElementById('blink_img');
					element.innerHTML = '<a href="chat.php"><img src="images/header_01_blink.gif" width="260" height="60" border=0></a>';
				}
				break;

			case 'notification':
				if (jsonResponse.notifications.length) {
					var str = '<table>';
					for (var i=0; i<jsonResponse.notifications.length; i++) {
						if (browser_is_ie) {
							if (jsonResponse.notifications[i].notification_type_sid==1)	{
								// mail
								str += '<embed src="/sounds/bell.wav" autostart=true loop=false width=0 height=0>';
							}
							else if (jsonResponse.notifications[i].notification_type_sid==2) {
								// emoticon
								str += '<embed src="/sounds/whistle.wav" autostart=true loop=false width=0 height=0>';
							}
						}

						if (jsonResponse.notifications[i].notification_type_sid==1) {
							url = 'messages.php';
						}
						else if (jsonResponse.notifications[i].notification_type_sid==2 || jsonResponse.notifications[i].notification_type_sid==3) {
							url = 'profile_view.php#comments_tab';
						}
						else if (jsonResponse.notifications[i].notification_type_sid==7) {
							url = 'profile_view.php?profile_sid='+jsonResponse.notifications[i].profile_sid+'#gallery_tab';
						}
						else if (jsonResponse.notifications[i].notification_type_sid==8) {
							url = 'friends.php?type=new';
						}
						else {
							url = 'favorites.php';
						}

						str += '<tr><td width=10% style="width:10%"><img src="image_' + jsonResponse.notifications[i].compound_photo_sid + '_4.jpg" width=82 height=82></td><td width=90%><a href="' + url + '" onClick="b4_popup_exit(\'popup\'); return true;">' + jsonResponse.notifications[i].name + "</a> (" + jsonResponse.notifications[i].notification_count + ")</td></tr>";
					}
					str += '</table>';
					document.getElementById('popup_title').innerHTML = 'Notification';
					document.notpopform.notpopbutton.click();
					document.getElementById('nothtml').innerHTML = str;
				}
				break;

			case 'chat_invitation':
				str = '<table>';
				if (browser_is_ie) {
					str += '<embed src="/sounds/phone.wav" autostart=true loop=false width=0 height=0>';
				}
				str += '<tr><td colspan=2>You have been invited to chat with ' + jsonResponse.user.username + '</td></tr><tr><td width=10% style="width:10%"><img src="image_' + jsonResponse.user.compound_photo_sid + '_4.jpg" width=82 height=82></td><td width=90%><input type=button value="Accept" onClick="notifier.document.location=\'chat_request_reply.php?chat_request_sid=' + jsonResponse.user.chat_request_sid + '&answer=1\'; b4_popup_exit(\'popup\');"> <input type=button value="Decline" onClick="notifier.document.location=\'chat_request_reply.php?chat_request_sid=' + jsonResponse.user.chat_request_sid + '&answer=0\'; b4_popup_exit(\'popup\')"></td></tr></table>';
				document.getElementById('popup_title').innerHTML = 'Invitation';
				document.notpopform.notpopbutton.click();
				document.getElementById('nothtml').innerHTML = str;
				break;
		}
	}
}

function handleEvents(jsonResponse) {

	if (jsonResponse) {
		if (jsonResponse.events.length) {
			var str = '<table>';
			for (var i=0; i<jsonResponse.events.length; i++) {
				//if (browser_is_ie) {
					if (jsonResponse.events[i].event_type_sid==1)	{
						// mail
						str += '<embed src="/sounds/bell.wav" autostart=true loop=false width=0 height=0>';
					}
					else if (jsonResponse.events[i].event_type_sid==2) {
						// emoticon
						str += '<embed src="sounds/whistle.wav" autostart=true loop=false width=0 height=0>';
					}
				//}

				url = 'events.php';

				str += '<tr><td>' + jsonResponse.events[i].event_count + ' event(s) of type <a href="' + url + '">' + jsonResponse.events[i].name + "</a> registred.</td></tr>";
			}
			str += '</table>';
			document.getElementById('popup_title').innerHTML = 'Event';
			document.notpopform.notpopbutton.click();
			document.getElementById('nothtml').innerHTML = str;
		}
	}
}

var userListOffset = 0;

function getMainUserList(next) {
	try {
		http.open('get', 'internal_request.php?get_list=1&list_name=mainusers&from=' + (userListOffset + 10 * next));
		http.onreadystatechange = function(aEvt) {
			handleData();
		}
		http.send(null);
	}
	catch (e) { }
}

function handleMainUserList(jsonResponse) {
	if (jsonResponse)	{
		userListOffset = (jsonResponse.offset >= 0) ? jsonResponse.offset : 0;
		var showLinks = (jsonResponse.registration_status > 3);

		var str = '<table cellpadding=1 cellspacing=0 class="chatlistTable">';

		var length = jsonResponse.username.length;

		for (var i=0; i < length; i++) {
			str += '<tr>';
			str += '<td class="icon">'+getGenderIcon(jsonResponse.composition[i])+'</td>';
			var html = (showLinks) ? jsonResponse.profile_link[i] : jsonResponse.username[i];
			str += '<td class="username">' + html + '</td>';

			str += '<td class="location" nowrap>' + jsonResponse.location[i] + getOnlineIcon(jsonResponse.is_logged_in[i], jsonResponse.username[i], showLinks) + '</td>';

			str += '</tr>';
		}

		str += '</table>';
	}
	else {
		var str = '';
	}

	document.getElementById('mainUserList').innerHTML = str;

  document.getElementById('previous').style.visibility = (userListOffset <= 0) ? 'hidden' : 'visible';
}

function getOnlineIcon(is_online, username, showLinks) {
  if (is_online) {
		if (showLinks) {
	    return " <a href=\"#\" onclick=\"callToActionscript('"+username+"');\" ondblclick=\"callToActionscript('"+username+"');\" title=\"Chat\"><img src=\"/images/start_chat.gif\" border=\"0\" /></a>";
		}
		else {
			return '<img src="/images/start_chat.gif" />';
		}
  }
	else {
		return ' <img src="/images/px.gif" width="12" height="8"/>';
	}

	return '';
}

window.setTimeout('getData()', 1000);

$(document).ready(function() {
	getMainUserList(0);

	//if (getCookie('userListHidden')) {
		toggleUserList(false);
	//}

	$("#pagelist a").click(
		function () {
			toggleUserList($("#mainUserList").is(":visible"));
		}
	);

	$("#advancedLink a").click(
		function () {
			toggleSearch($("#advancedSearch").is(":visible"));
		}
	);
});

function toggleUserList(visible) {
	if (visible) {
		$("#mainUserList").slideUp(500, function() {});
		$("#next").css('visibility', 'hidden');
		$("#previous").css('visibility', 'hidden');
		$("#pagelist a").text('Show');

		//setCookie('userListHidden', true);
	}
	else {
		$("#mainUserList").slideDown(500, function() {});
		$("#pagelist a").text('Hide');
		$("#next").css('visibility', 'visible');

		if (userListOffset > 0)	{
			$("#previous").css('visibility', 'visible');
		}

		//setCookie('userListHidden', false);
	}
}

function toggleSearch(visible) {
	if (visible) {
		$("#advancedSearch").slideUp(500, function() {});
		$("#advancedLink a").text('more');

		//setCookie('userListHidden', true);
	}
	else {
		$("#advancedSearch").slideDown(500, function() {});
		$("#advancedLink a").text('less');

		//setCookie('userListHidden', false);
	}
}