
var windowCSS     = 'default';      // CSS file for all other windows (buddylist, IMs)
var audioNotify   = false;    // By default, play sounds upon getting an IM?
// Server //
//var pingFrequency = 5000;           // How often to ping the server (in milliseconds). Best range between 2500 and 3500 ms.
//var pingTo        = 'messenger.php';  // The file that is the "server".
//var pingTo        = 'poster.php';  // The file that is the "server".
var pingTo        = '/index.php?eID=user_volume_messenger';  // The file that is the "server".
var chatURI        = '/index.php?eID=user_volume_chat';  // The file that is the "server".
var top= 0;
var left= 0;
/*
*
*	templates for messenger
*
*/
var Layouts= new Object();
Layouts.AdminArea= '<div id="adminarea"></div>';
Layouts.LoginArea='<div id="loginarea"></div>';
Layouts.Panel= '<div id="#{identifier}_control"  class="splitter"><div class="splitter_text">#{description}#{notify_title}</div><div  id="#{identifier}_button" class="splitter_icon_open"  onclick="$(\'#{identifier}_body\').logToggle()">&nbsp;</div></div><div id="#{identifier}_body"  class="buddy_box">&nbsp;</div>';

Layouts.LoginPanel="<div id='volume_messenger_loginarea'><div id='volume_messenger_login' class='clearfix'><label>#{usernamelabel}<br/><input name='#{username}' value='' type='text' class='login_input'/></label><label>#{passwordlabel}<br/><input name='#{password}' value='' type='password' class='login_input'/></label><button name='#{submit}' type='submit' class='shiny_with_arrow'><div><div>#{textLogin}</div></div></button><input type='hidden' name='#{redirectUrlName}' value='#{redirectUrlValue}' /></div><div id='volume_messenger_login_admin'><a href='#{forgot_path}'>#{lang_forgot_password}</a><a href='#{register_path}'>#{lang_register}</a></div></div>";

Layouts.MyArea="<div id='user_box'><div class='user_img_msg'>#{picture}</div><div class='user_name'>#{nickname}</div><div id='logout'><a href='#{logout_path}'>logout</a></div><div class='msg_icons'></div><br clear='all' /></div>";
Layouts.MyArea+='<div id="big_icon_box"><div><ul><li class="msg_gallerie"><a href="#{gallery_path}"><span>#{lang_gallery}</span></a></li><li class="msg_mail"><a href="#{pm_path}"><span>#{lang_mailbox}</span>&nbsp;<strong id="unread_messages"></strong></a></li><li class="msg_profile"><a href="#{profile_path}"><span>#{lang_profile}</span></a></li></ul></div></div>';
/*
*
*	log the status of the panels
*
*/
Element.addMethods(
	{
		logToggle: function(element, argument)
		{
			// notifier shouldn't toogle if they are already open! argument is true ...
			if(argument)
			element.setStyle({display: "block"});
			else
			element.toggle();
			// save display status in the element!
			element.display= element.getStyle('display');
			// delete the cookie and set it new!
			Delete_Cookie( 'vmsgr_'+element.id , '/', '');
			Set_Cookie( 'vmsgr_'+element.id, element.getStyle('display'), 365, '/', '', '' );
			element.setDisplay(element.getStyle('display'));
		},
		setDisplay: function(element, argument)
		{
			// if nothing is set at the first load!
			if(argument!=null)
			{
				element.setStyle({display: argument});
				element.display= argument;
				//get identifier
				var id_array = element.id.split("_");
				var identifier= id_array[0];
				if(argument=="none")
				{
					if($(identifier+'_control'))
					{
						$(identifier+'_control').removeClassName('splitter');
						$(identifier+'_control').addClassName('splitter_inactive');
					}
					if($(identifier+'_button'))
					{
						$(identifier+'_button').removeClassName('splitter_icon_open');
						$(identifier+'_button').addClassName('splitter_icon_close');
					}
				}
				else if (argument=="block")
				{
					if($(identifier+'_control'))
					{
						$(identifier+'_control').removeClassName('splitter_inactive');
						$(identifier+'_control').addClassName('splitter');
					}
					if($(identifier+'_button'))
					{
						$(identifier+'_button').removeClassName('splitter_icon_close');
						$(identifier+'_button').addClassName('splitter_icon_open');
					}
				}
			}
		}
	}
);

var messengerSettingsDirty;

function initMessenger(display)
{
	image_url= path+"lib/js/messenger/";
	
	if (window.volume_messenger_ui === undefined)
	{
		window.volume_messenger_ui = constructVolumeMessengerUI();
	}
	
	if(display=="messenger")
	{
		var makeDirty = function () { messengerSettingsDirty = true; }
		if(!$('win'))
		{
		       Win = new Window('win', {className: "dialog", width: 210, height: (browserHeight() - 400), zIndex: 100, resizable: true,
							title: language.messengerTitle, draggable: true, closable:true, maximizable: false, detachable: false, minWidth: 210, minHeight: 200,
							showEffectOptions: {duration: 5}, hideEffectOptions: {duration: 0},
							onMove: makeDirty, onResize: makeDirty});
		}
		//buddyListWin.setCookie(buddyListWin.getId(), 18000000, location.href);
		// now make it pretty
		Win.getContent().innerHTML =Layouts.AdminArea;
		
		var scrollable = document.createElement("div");
		scrollable.setAttribute("id", "scroll_container");
		Win.getContent().appendChild(scrollable);
		
		generatePanel('friends', language.friends, scrollable, true, true);
		generatePanel('receive.acc', language.rec_acceptlist, scrollable, false, true);
		generatePanel('send.acc', language.sen_acceptlist, scrollable, false, true);

		//show the window
		Win.show();
		// read out cookie
		setPosition();
		messengerSettingsDirty = false;
		
		// ------------------------------->
		pingTimer = setInterval("pinger('messenger_init')", IM.pingFrequency);
		//-------------------------------> loadbuddies
		loadMessengerData('messenger_init');
		// log the position to the cookie
		window.onunload= saveStatus;
		//a$('win_minimize').style.left = (Win.getSize()['width'] - 21) + 'px';

		Win.toFront()
		//-------------------------------> add eventlistener!
			// Set up a windows observer and trace into the textarea
			var myObserver = {
				  onClose:function(eventName, win)
				  {
					closer =  confirm("Wollen sie die Community wirklich verlassen?");
					if (closer)
					{
						window.location.href= logoutpath;
					}
					else
					{
						win.show();
					}
				  }
				};
			if (typeof document.body.style.maxHeight == "undefined")
			{
				// IE6, older browsers
				// for scrollbars in IE, explicitly size the scrollbar box.
				myObserver.onResize = function(eventName, win)
				{
					var scroll_box = document.getElementById("scroll_container");
					if (scroll_box)
					{
						var st = scroll_box.currentStyle;
						var delta = (st && parseInt(st.top)) || scroll_box.offsetTop;
						if (delta)
						{
							scroll_box.style.height = (win.height - delta) + "px";
						}
					}
				}
			};
			Windows.addObserver(myObserver);
			
		
	}
	if(display=="register")
	{
		if(!$('win'))
		{
		       Win = new Window('win', {className: "dialog", width: 210, height: 54, zIndex: 100, resizable: false,
							title: language.messengerTitleLogin, draggable: false, closable:false, maximizable: false, detachable: false, minWidth: 210, minHeight: 45,
							showEffectOptions: {duration: 5}, hideEffectOptions: {duration: 0},
							parent: $("container")});
		}
		//buddyListWin.setCookie(buddyListWin.getId(), 18000000, location.href);
		// read out cookie
		//setPosition();
		Win.setLocation(6, 692);
		//show the window
		Win.show();
		//saveStatus();
		// now make it pretty
		Win.getContent().innerHTML +=Layouts.LoginArea;
		generateRegForm();
		//Win.getContent().innerHTML = buildLogin();
	}
}

function setPosition()
{
	// get cookies
	width = Get_Cookie('vmsgr_width') || 210;
	height = Get_Cookie('vmsgr_height') || 45;
	left = Get_Cookie('vmsgr_left') || 610;
	top = Get_Cookie('vmsgr_top') || 80;
	minimized = Get_Cookie('vmsgr_minimized');

	//cookie= document.cookie.split(";");
/*	cookie = Get_Cookie( 'volume_messenger' )
	alert ( cookie );
	position_c= cookie[0].split("_");
	//just position the window if there are data of position in the cookie
	if(position_c.length==5)
	{
		width= position_c[0];
		height= position_c[1];
		top= position_c[3].substring(0, position_c[3].length-2);
		left= position_c[2].substring(0, position_c[2].length-2);
		left= left.split(".")[0];
		top= position_c[3].substring(0, position_c[3].length-2);
		top= top.split(".")[0];
		// now position the object! */
		if(top>1200 || left>1200)
		Win.setLocation(0, 0);
		else
		Win.setLocation(top, left);
		Win.setSize(width, height);
		//is minimized?
		if ( minimized == "true" ) //(position_c[4]=="true")
		{
			Win.minimize();
		}
/*	}
	else
	{
		top=0;
		left=0;
		Win.setLocation(top, left);
	}*/
	/*
	$('friends_body').setDisplay(Get_Cookie( 'vmsgr_friends_body' ));
	$('pm_body').setDisplay(Get_Cookie( 'vmsgr_pm_body' ));
	$('notifier_body').setDisplay(Get_Cookie( 'vmsgr_notifier_body'));
	$('send_acc_body').setDisplay(Get_Cookie( 'vmsgr_send_acc_body'));
	$('receive_acc_body').setDisplay(Get_Cookie( 'vmsgr_receive_acc_body'));
	*/
}
function saveStatus()
{
	if (!messengerSettingsDirty)
		return;
	
	//document.cookie=";expires=Thu, 01-Jan-70 00:00:01 GMT;";
	Delete_Cookie('vmsgr_width', '/', '');
	Delete_Cookie('vmsgr_height', '/', '');
	Delete_Cookie('vmsgr_left', '/', '');
	Delete_Cookie('vmsgr_top', '/', '');
	Delete_Cookie('vmsgr_minimized', '/', '');
	//log panel values
	Delete_Cookie( 'vmsgr_friends_body' , '/', '');
//	Delete_Cookie( 'vmsgr_pm_body' , '/', '');
//	Delete_Cookie( 'vmsgr_notifier_body', '/', '');
	Delete_Cookie( 'vmsgr_send.acc_body', '/', '');
	Delete_Cookie( 'vmsgr_receive.acc_body', '/', '');


	left = Win.element.getStyle('left');
	left = left.replace( /px/, "" );
	left = left.split( "." )[0];

	top = Win.element.getStyle('top');
	top = top.replace( /px/, "" );
	top = top.split( "." )[0];
/*
	if(top>1200)
	top= 0;
	else
	top= Win.element.getStyle('top');
	if(left>1200)
	left= 0;
	else
	left= Win.element.getStyle('left');
*/
	//position= Win.getSize().width+"_"+Win.getSize().height+"_"+Win.element.getStyle('left')+"_"+ Win.element.getStyle('top')+"_"+Win.isMinimized();
	//document.cookie=position;
	Set_Cookie( 'vmsgr_width', Win.getSize().width, 365, '/', '', '' );
	Set_Cookie( 'vmsgr_height', Win.getSize().height, 365, '/', '', '' );
	Set_Cookie( 'vmsgr_left', left, 365, '/', '', '' );
	Set_Cookie( 'vmsgr_top', top, 365, '/', '', '' );
	Set_Cookie( 'vmsgr_minimized', Win.isMinimized(), 365, '/', '', '' );
	//log panel values
	Set_Cookie( 'vmsgr_friends_body', $('friends_body').getStyle('display'), 365, '/', '', '' );
//	Set_Cookie( 'vmsgr_pm_body', $('pm_body').getStyle('display'), 365, '/', '', '' );
//	Set_Cookie( 'vmsgr_notifier_body', $('notifier_body').getStyle('display'), 365, '/', '', '' );
	Set_Cookie( 'vmsgr_send.acc_body', $('send.acc_body').getStyle('display'), 365, '/', '', '' );
	Set_Cookie( 'vmsgr_receive.acc_body', $('receive.acc_body').getStyle('display'), 365, '/', '', '' );
	
	messengerSettingsDirty = false;
}
function pinger(action)
{
	//alert("hallo");
	//setOnline();
	loadMessengerData(action);
	saveStatus();
}
/*
+
+ ADMINISTRATION FOR REGISTER
+ START
+
*/
function generatePanel(identifier, description, node, hidden, notifier)
{
	var output;
	// build an external notifer to get alert on title panel
	if (notifier)
	var notify_title="&nbsp;(<span id='"+identifier+"_notify'>&nbsp;</span>)";
	else
	var notify_title="";
	
	var panel= new Template(Layouts.Panel);
			output= panel.evaluate(
			{
				identifier: identifier,
				icon_path: iconpath,
				description: description,
				notify_title: notify_title
			});
	// now add the panel
	node.innerHTML+= output;
	// do the default setup for the panel
	if (hidden)
	{
		$(identifier+'_body').hide();
		$(identifier+'_body').display='none';
		// make css closed
		$(identifier+'_control').removeClassName('splitter');
		$(identifier+'_control').addClassName('splitter_inactive');
		$(identifier+'_button').removeClassName('splitter_icon_open');
		$(identifier+'_button').addClassName('splitter_icon_close');
	}
	else
	{
		$(identifier+'_body').show();
		$(identifier+'_body').display='block';
		// make css closed
		$(identifier+'_control').removeClassName('splitter_inactive');
		$(identifier+'_control').addClassName('splitter');
		$(identifier+'_button').removeClassName('splitter_icon_close');
		$(identifier+'_button').addClassName('splitter_icon_open');
	}
	//preset from cookie
	//alert("identifier: "+identifier+"-->"+Get_Cookie( 'vmsgr_'+identifier+'_body'));
	if (Get_Cookie( 'vmsgr_'+identifier+'_body')!='undefined' && Get_Cookie( 'vmsgr_'+identifier+'_body')!='null')
	{
		//alert("identifier: "+identifier+"-->"+Get_Cookie( 'vmsgr_'+identifier+'_body'));
		$(identifier+'_body').setDisplay(Get_Cookie( 'vmsgr_'+identifier+'_body'));
	}
	return output;

}
function putPanelNotifier(element, number)
{
	//get identifier
	var id_array = element.id.split("_");
	var identifier= id_array[0];
	//alert(identifier);
	if ($(identifier+"_notify"))
	$(identifier+"_notify").innerHTML=number;
}
function generateRegForm()
{
	if(error)
	{
		alert(error);
	}
	/*
	*
	* the registration form is added!
	*
	*/
	 var loginForm = document.createElement("form");
	 $('loginarea').appendChild(loginForm);
	loginForm.setAttribute("action", action);
	loginForm.setAttribute("enctype", 'multipart/form-data');
	loginForm.setAttribute("method", 'post');
	loginForm.setAttribute("onsubmit", "return loginSanityCheck(this);");
	// now render the template!
	var login_template = new Template(Layouts.LoginPanel);
	login_template= login_template.evaluate(
	{
		username: logform.username,
		password: logform.password,
		submit:logform.submit,
		//lang_submit:language.submit,
		lang_submit:"",
		icon_path: iconpath,
		forgot_path: forgotpath,
		lang_forgot_password:language.forgot_password,
		register_path:registerpath,
		lang_register: language.register,
		redirectUrlName: redirectUrlName,
		redirectUrlValue: redirectUrlValue,
		textLogin: language.login,
		usernamelabel: language.user,
		passwordlabel: language.password
	});
	// render it to the form node!
	loginForm.innerHTML= login_template;
}
/*
+
+ ADMINISTRATION FOR USER
+ END now we append the pingFrequency to the parameter to control the refreshing from the externsion!
+
*/
function loadMessengerData(action)
{
	//alert(action);
	//pinger_url= path+"/lib/php/"+pingTo;
	var pinger_url= pingTo;
	//alert( pinger_url );
	var params = 'action='+action+'&content=json&timer='+IM.pingFrequency;
	var ajax_req = new Ajax.Request(
		pinger_url,
		{
			method: 'post',
			postBody: params,
			//parameters : "name=Fred",
			//parameters: {action: action, content: 'json', timer: IM.pingFrequency},
			onSuccess: function(t) {
				try
				{
					buildData(t.responseText);
				}
				catch (e)
				{
					//alert(e);
				}
			},
			onFailure: function(t) {alert("funkt nicht" + t.responseText); }
		}
	);
}

// put all this mess in a namespace

function constructVolumeMessengerUI() {
	// private static variables:
	var current_json_string;
	var current_json_obj;

	// the icons used in the messenger UI
	var buddy_icons =
	{
		"mail_alert":
			{ "path": "icons/in_mail_big_pulse.gif", "width": 28, "height": 22 },
		"msg_alert":
			{ "path": "icons/in_chat_big_pulse.gif", "width": 28, "height": 23 },
		"offline":
			{ "path": "icons/status_offline.gif", "width": 12, "height": 12 },
		"online":
			{ "path": "icons/status_online.gif", "width": 12, "height": 12 },
		"unknown":
			{ "path": "icons/status_unknown.gif", "width": 12, "height": 12 },
		"mail":
			{ "path": "icons/mail.gif", "width": 12, "height": 9 },
		"mail_disabled":
			{ "path": "icons/mail_disabled.png", "width": 12, "height": 9 },			
		"chat":
			{ "path": "icons/chat.gif", "width": 16, "height": 16 },
		"chat_disabled":
			{ "path": "icons/chat_disabled.png", "width": 16, "height": 16 },			
		"accept":
			{ "path": "icons/add.gif", "width": 14, "height": 14 },
		"deny":
			{ "path": "icons/delete.gif", "width": 14, "height": 14 }
	};
	
	// XHTML templates for the messenger components.
	var markup = new Object();
	markup.main = new Template(
		"<div class=\"buddy clearfix#{extra_classes}\" id=\"buddy_#{id}\"><div class=\"buddy_icon\"><a href=\"#{profile_url}\">#{picture}</a></div>#{notifications}<p>#{online_indicator} <a href=\"#{profile_url}\">#{nickname}</a><br/>#{chat_button} #{mail_button}</p></div>");
		
	markup.accept_deny = new Template(
		"<p><a href='javascript:void(0);' onClick='acceptFriend(#{user_uid}, #{my_uid}, 1);  return false;'>#{accept}</a><br /><a href='javascript:void(0);' onClick='acceptFriend(#{user_uid}, #{my_uid}, 2); return false;'>#{deny}</a></p>");
	
	markup.chat_notify = new Template(
		"<a href=\"javascript:void(0);\" onClick=\"openNotifierChat(\'#{buddy_id}\', \'#{user_id}\')\">#{button_icon}</a>");
	markup.mail_notify = new Template(
		"<a href=\"#{pm_notify_path}\">#{button_icon}</a>");
	markup.new_mail = new Template(
		"<a href=\"#{pm_href}\">#{button_icon}</a>");
		
	markup.mail_disabled = new Template(
		"#{button_icon}");		
	
	markup.chat = new Template(
		"<a href=\"javascript:void(0);\" onClick=\"openChat(#{buddy_uid}, #{user_id})\">#{button_icon}</a>");

	markup.chat_disabled = new Template(
		"#{button_icon}");
				
	markup.notifications = new Template(
		"<div class=\"notifications\">#{incoming_chat}#{incoming_mail}#{approval}</div>");

	// function bodies:
	function sanitiseBuddy(buddy)
	{
		// convert various properties to numeric/boolean types.
		var bud = new Object();
		bud.uid = parseInt(buddy["uid"], 10);
		bud.nickname = buddy["nickname"];
		bud.is_online = parseInt(buddy["is_online"],10) != 0;
		bud.status = parseInt(buddy["status"], 10);
		bud.picture = buddy["picture"];
		bud.pendingChat = buddy["pendingChat"] && (parseInt(buddy["pendingChat"], 10) > 0);
		bud.pendingMessage = buddy["pendingMessage"] && (parseInt(buddy["pendingMessage"], 10) > 0);
		bud.awaitingApproval = false;
		return bud;
	}
		
	function sanitiseRequest(request)
	{
		var req = sanitiseBuddy(request);
		req.awaitingApproval = true;
		return req;
	}
	function sanitiseMessengerJSON(json_object)
	{
		// uses: sanitiseBuddy() and sanitiseRequest()
		/* incoming JSON Format:
		*	{	"myself":
		*		{
		*			"uid": "9",
		*			"nickname": "name",
		*			"picture": null | "<img src='...' />" },
		*		"buddies":
		*		[
		*			{
		*				"uid": "7",
		*				"nickname": "buddyname",
		*				"is_online": 0 | 1, // offline | online
		*				"status": "1" | "0", // accepted | pending acceptance
		*				"picture": null | "<img src='...' />"
		*				"pendingChat": "0" | "1", // no incoming chat | incoming chat
		*				"pendingMessage": "0" | "1" }, // no unread PM from user | unread PM
		*			...],
		*		"acceptions":
		*		[], // TODO
		*		"notifier":
		*		[
		*			{
		*				"uid":"10",
		*				"nickname":"buddyname",
		*				"is_online": 1 | 0,
		*				"picture": null | "<img src='..' />" },
		*			...],
		*		"pm":
		*		"0" // TODO
		*	}
		*/

		// copy the JSON object, sanitise each buddy.
		var json_copy = Object.clone(json_object);
		json_copy.buddies = json_object["buddies"].clone();
		for (var i = 0; i < json_copy.buddies.length; ++i)
		{
			json_copy.buddies[i] = sanitiseBuddy(json_copy.buddies[i]);
		}
		
		json_copy.acceptions = json_object["acceptions"].clone();
		for (var i = 0; i < json_copy.acceptions.length; ++i)
		{
			json_copy.acceptions[i] = sanitiseRequest(json_copy.acceptions[i]);
		}
		
		return json_copy;
	}

	function filterBuddyStatus(buddies, buddy_status)
	{
		if (arguments.length < 2 || buddy_status === undefined || buddy_status === null)
			return buddies;
		
		var filtered = new Array();
		for (var i = 0; i < buddies.length; ++i)
		{
			if (buddies[i].status == buddy_status)
				filtered.push(buddies[i]);
		}
		return filtered;
	}
	
	function clearChatNotify(user_id)
	{
		// clear cache
		current_json_string = "";
		for (var i = 0; i < current_json_obj.buddies.length; ++i)
		{
			if (current_json_obj.buddies[i].uid == user_id)
			{
				current_json_obj.buddies[i].pendingChat = false;
				buildUserLists(current_json_obj);
				return;
			}
		}
	}

	function buildMessengerUI(json_string)
	{
		if (json_string == current_json_string)
			return;
		current_json_string = json_string;
		
		//alert(json_string);
		var object = decode_json(json_string);
		
		var sanitised_data = sanitiseMessengerJSON(object);
		current_json_obj = sanitised_data;
		
		// now devide the object to its areas (myself, buddies, a.s.o)
		var myself= object.myself;
		buildAdminArea(myself);
		
		setUnreadMessageCount(sanitised_data.pm);
		buildUserLists(sanitised_data);
	}

	function buildUserListPanel(panel_id, user_array)
	{
		var panel = $(panel_id);
		if (panel)
		{
			panel.innerHTML = "";
			buildBuddyList(user_array, panel);
			putPanelNotifier(panel, user_array.length);
		}
	}
	
	function setUnreadMessageCount(count)
	{
		count = parseInt(count, 10);
		$('unread_messages').innerHTML =
			(count == 0) ? "" : ("(" + count + ")");
	}

	function buildUserLists(sanitised_data)
	{
		buildUserListPanel('friends_body', filterBuddyStatus(sanitised_data.buddies, 1));
		
		buildUserListPanel("send.acc_body", filterBuddyStatus(sanitised_data.buddies, 0));

		buildUserListPanel("receive.acc_body", sanitised_data.acceptions);
	}

	// Construct an image tag from the image descriptor, using specified alt and title attributes
	// function buildImage(img_desc, alt_text, tooltip_text)
	var buildImage = function()
	{
		// pregenerate templates
		var path_prefix;
		var alt_template = new Template(" alt=\"#{alt_text}\"");
		var title_template = new Template(" title=\"#{title_text}\"");
		var img_tag;
		var img_template;
		
		return function(img_desc, alt_text, tooltip_text)
		{
			if (path_prefix === undefined)
				path_prefix = iconpath + "images/";
			if (img_tag === undefined)
				img_tag = "<img src=\"" + path_prefix + "#{path}\" width=\"#{width}\" height=\"#{height}\"#{alt_attr}#{title_attr} />";
			if (img_template === undefined)
				img_template = new Template(img_tag);
			
			var desc_copy = Object.clone(img_desc);
			desc_copy.alt_attr =
				(alt_text !== undefined && alt_text !== null && alt_text != "")
				? alt_template.evaluate({"alt_text" : alt_text })
				: "";
			desc_copy.title_attr =
				(tooltip_text !== undefined && tooltip_text !== null && tooltip_text != "")
				? title_template.evaluate({"title_text" : tooltip_text })
				: "";
			return img_template.evaluate(desc_copy);
		};
	} ();

	// generates the <div class="notification" /> right-float that contains accept/deny, new mail, new chat icons.
	function buildUserNotifications(user)
	{
		var mail_notify_button = markup.mail_notify.evaluate(
			{ "button_icon": buildImage(buddy_icons.mail_alert, language.text_newMessage, language.text_newMessage),
				"pm_notify_path": pmpath.replace(/_ACTION_/, 'inbox')});
		var chat_notify_icon = buildImage(buddy_icons.msg_alert, language.text_sendChat, language.text_sendChat);
		var accept_label = buildImage(buddy_icons.accept, null, language.text_accept) + "&nbsp;" + language.text_accept;
		var deny_label = buildImage(buddy_icons.deny, null, language.text_deny) + "&nbsp;" + language.text_deny;
		var notifications_markup = "";
		if (user.pendingChat || user.pendingMessage || user.awaitingApproval)
		{
			notifications_markup = markup.notifications.evaluate(
				{
					"incoming_mail":
						user.pendingMessage
							? mail_notify_button
							: "",
					"incoming_chat":
						user.pendingChat
							? markup.chat_notify.evaluate(
								{	"buddy_id": user.uid,
									"user_id": userid,
									"button_icon": chat_notify_icon })
							: "",
					"approval":
						user.awaitingApproval
							? markup.accept_deny.evaluate(
								{ "user_uid": user.uid,
									"my_uid": userid,
									"accept": accept_label,
									"deny": deny_label })
							: "" });
		}
		return notifications_markup;
	}
	
	var online_icon;
	var offline_icon;
	function buildBuddy(buddy, is_first)
	{	
		if (online_icon === undefined)
			online_icon = buildImage(buddy_icons["online"], language.text_online, language.text_online);
		if (offline_icon === undefined)
			offline_icon = buildImage(buddy_icons["offline"], language.text_offline, language.text_offline);
		
		var user_id = userid;
		var pm_href = pmpath.replace(/_ACTION_/, 'sendmessage');
		var online_status_icon = buddy.is_online ? online_icon : offline_icon;
		var notifications_markup = buildUserNotifications(buddy);
		if ( buddy.status == 1 )
		{
			var mail_button = markup.new_mail.evaluate(
				{	"buddy_uid": buddy.uid,
					"pm_href": pm_href.replace(/_UID_/, buddy.uid),
					"button_icon": buildImage(buddy_icons.mail, language.text_sendMessage, language.text_sendMessage) });

			var chat_button = markup.chat.evaluate(
				{	"buddy_uid": buddy.uid,
					"user_id": user_id,
					"button_icon": buildImage(buddy_icons.chat, language.text_sendChat, language.text_sendChat) });

		}
		else
		{
			var mail_button = markup.mail_disabled.evaluate(
				{	"button_icon": buildImage(buddy_icons.mail_disabled, "", "") });

			var chat_button = markup.chat_disabled.evaluate(
				{	"button_icon": buildImage(buddy_icons.chat_disabled, "", "") });
		
		}
		
		var buddy_data =
		{
			"extra_classes": is_first ? " first" : "",
			"id": buddy.uid,
			"picture": buddy.picture || "",
			"chat_button": chat_button,
			"mail_button": mail_button,
			"online_indicator": online_status_icon,
			"nickname": buddy.nickname,
			"notifications": notifications_markup,
			"profile_url": profilepath.replace(/_UID_/, buddy.uid)
		};
		
		return markup.main.evaluate(buddy_data);
	}

	// Walks through an array of users and appends markup for each of them within the specified node.
	function buildBuddyList(buddy_array, below_node)
	{
		var list_markup = "";
		for (var i = 0; i < buddy_array.length; ++i)
		{
			list_markup += buildBuddy(buddy_array[i], i == 0);
		}
		
		below_node.innerHTML += list_markup;
		return null;
	}


	return {
		// public functions:
		// clean up the JSON object and transform it into a more usable format.
		"sanitiseMessengerJSON": sanitiseMessengerJSON,
		// remove the "new chat message" icon from the specified user in the messenger
		"clearChatNotify": clearChatNotify,
		// (re)Construct the Messenger's UI elements given a JSON string from the server.
		"buildMessengerUI": buildMessengerUI
	};
}

if (window.volume_messenger_ui === undefined)
	window.volume_messenger_ui = constructVolumeMessengerUI();
/*function volume_messenger_ui()
{
	return volume_messenger_ui_ns;
}*/

function buildData(json_string)
{
/*	if (!volume_messenger_ui)
		volume_messenger_ui = constructVolumeMessengerUI();*/
	
	return window.volume_messenger_ui.buildMessengerUI(json_string);
}




function loadNotifierData()
{
	//pinger_url= path+"/lib/php/"+pingTo;
	var pinger_url= pingTo;
	var params = 'action=getnotifier&content=json&timer='+IM.pingFrequency;
	var ajax_req = new Ajax.Request(
		pinger_url,
		{
			method: 'post',
			//postBody: params,
			parameters: params,
			onSuccess: function(t) { buildNotifier(t.responseText) },
			onFailure: function(t) {alert("notifier funkt nicht"); }
		}
	);
}
/*
*
* NOW BUILSD ALL THE STUFF
*/
function buildAdminArea(object)
{
	// own profile
	var pm_path= pmpath.replace(/_UID_/, object.uid);
	pm_path= pm_path.replace(/_ACTION_/, 'inbox');
	// now render the template!
	var myarea_template = new Template(Layouts.MyArea);
	myarea_template= myarea_template.evaluate(
	{
		picture: object.picture,
		profile_path:profilepath.replace(/_UID_/, object.uid),
		nickname:object.nickname,
		logout_path: logoutpath,
		icon_path: iconpath,
		lang_unsubscribe:language.unsubscribe,
		gallery_path:gallerypath.replace(/_UID_/, object.uid),
		lang_gallery: language.gallery,
		pm_path:pm_path,
		lang_mailbox: language.mailbox,
		lang_profile: language.profile
	});
	//alert($("adminarea").innerHTML);
	$("adminarea").innerHTML = myarea_template;
}

function unsetPMNotifier()
{
	window.location.href = pmpath.replace(/_ACTION_/, 'inbox');
}
function setOnline()
{
	//pinger_url= path+"/lib/php/"+pingTo;
	var pinger_url= pingTo;
	var params = 'action=setonline';
	var ajax_req = new Ajax.Request(
		pinger_url,
		{
			method: 'post',
			//postBody: params,
			parameters: params,
			//onSuccess: function(t) { alert(t.responseText) },
			onFailure: function(t) {alert("kann nicht online setzen"); }
		}
	);
}

function acceptFriend(user, selfid, status)
{
	// if he accepts you as friend you will be asked if you like to add him too?
	var counterpart = false;
	if(status == 1)
		counterpart = confirm(language.addFriendToo);
	//pinger_url= path+"/lib/php/"+pingTo;
	var pinger_url= pingTo;
	var params = 'action=handleAccept&id='+user+"&status="+status+"&counter=" + counterpart;
	//alert(params);
	var ajax_req = new Ajax.Request(
		pinger_url,
		{
			method: 'post',
			postBody: params,
			onSuccess: function(t) {reloadOnAccept(user); /*alert(t.responseText);*/},
			onFailure: function(t) {alert("add user doesn't work!"); }
		}
	);
}
function reloadOnAccept(user)
{
	loadMessengerData('messenger_init');
}
function openNotifierChat(sender, receiver)
{
	//pinger_url= path+"/lib/php/"+pingTo;
	var pinger_url= pingTo;
	var params = 'action=deleteNotifier&id='+sender;
	var ajax_req = new Ajax.Request(
		pinger_url,
		{
			method: 'post',
			//postBody: params,
			parameters: params,
			onSuccess: function(t) { /*alert(t.responseText)*/ },
			onFailure: function(t) {alert("kann notifier nicht updaten"); }
		}
	);
	//now open the chat window
	openChat(sender, receiver);
	// delete the notifier div
	window.volume_messenger_ui.clearChatNotify(sender);
}
function openChat(receiverid, meid)
{
	//var url= path+"/lib/php/chat.php?receiverid="+receiverid;
	var url= chatURI+'&receiverid='+receiverid;
	chat= window.open(url, receiverid+"_"+meid, "width=300,height=400,left=100,top=200");
	if (chat && chat.focus) // doesn't exist on IE6
		chat.focus();
}
function decode_json(string)
{
	return eval('(' + string + ')');
}
function browserWidth() {
   if (self.innerWidth) {
      return self.innerWidth;
   } else if (document.documentElement && document.documentElement.clientWidth) {
      return document.documentElement.clientWidth;
   } else if (document.body) {
      return document.body.clientWidth;
   }
   return 630;
}

function browserHeight() {
   if (self.innerWidth) {
      return self.innerHeight;
   } else if (document.documentElement && document.documentElement.clientWidth) {
      return document.documentElement.clientHeight;
   } else if (document.body) {
      return document.body.clientHeight;
   }
   return 470;
}
//--------------------CODE FOR MESSENGER EVENTS IN THE FRONTEND-----------------------------

//-------------------------------------------------------------------------------------------------------------------------

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
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 null;
	}
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


// Funktionen für Eingabefelder, die sich beim Erhalt des Fokus leeren
var volClearOnFocus = function ()
{
	var MAX_CAPTCHA_LEN = 5;
	var getElementsByNameAndClass = function (tagname, classname, node) {
		if(!node) node = document.getElementsByTagName("body")[0];
		var a = [];
		var re = new RegExp('\\b' + classname + '\\b');
		var els = node.getElementsByTagName(tagname);
		for(var i=0,j=els.length; i<j; i++)
			if(re.test(els[i].className))
				a.push(els[i]);
		return a;
	}
	var ns = new Object();
	ns.cacheDefaults = function()
	{
		var clearfields = getElementsByNameAndClass("input", "clear_on_focus");
		for (var i = 0; i < clearfields.length; ++i)
		{
			var field = clearfields[i];
			field.volume_default_val = field.value;
		}
	}
	
	ns.clearIfDefault = function(field, default_val)
	{
		if (field.value == (default_val === undefined ? field.volume_default_val : default_val))
		{
			field.value = "";
			field.maxLength = MAX_CAPTCHA_LEN;
		}
	}
	ns.resetIfClear = function(field, default_val)
	{
		if (field.value == "")
		{
			var setval = default_val === undefined ? field.volume_default_val : default_val;
			field.maxLength = setval.length;
			field.value = setval;
		}
	}
	return ns;
} ();

function loginSanityCheck(login_form)
{
	if (login_form)
	{
		if (login_form["user_volume_pi10[user]"].value == "" || login_form["user_volume_pi10[password]"].value == "")
		{
			window.alert(language.alertNoInput);
			return false;
		}
	}
	return true;
}

