// most parts (all except postUrl(), openUrl(), CallBack() and UrlCall()) are
// (C) Maarten van der Schrieck <maarten@vanderSchrieck.nl>

// called body.onload to indicate we do have javascript, and buttons may be removed
function javascript_enabled()
{
	var remove_items = new Array('filtersubmit','groupsubmittop','groupsubmitbottom');

	for ( var i=0; i<remove_items.length; i++ )
	{
		var element = document.getElementById(remove_items[i]);
		if ( element != null ) element.style.display='none';
	}
}

function postUrl ( url, vars, callback, cbarg1, cbarg2 )
{
	var http_request = false;

	if ( window.XMLHttpRequest ) { // Mozilla, Safari, ...
		http_request = new XMLHttpRequest();
		if ( http_request.overrideMimeType ) {
			http_request.overrideMimeType('text/xml');
		}
	} else if ( window.ActiveXObject ) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}

	if ( callback )
	{
		if ( cbarg2 )
		{
			http_request.onreadystatechange = function() { callback(http_request,cbarg1,cbarg2) };
		} else if ( cbarg1 ) {
			http_request.onreadystatechange = function() { callback(http_request,cbarg1) };
		} else {
			http_request.onreadystatechange = function() { callback(http_request) };
		}
	}
	//http_request.onreadystatechange = callback;
	http_request.open ( 'POST', url, true );
	http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	http_request.send ( vars );

	return true;
}

function openUrl ( url, callback )
{
	var http_request = false;

	if ( window.XMLHttpRequest ) { // Mozilla, Safari, ...
		http_request = new XMLHttpRequest();
		if ( http_request.overrideMimeType ) {
			http_request.overrideMimeType('text/xml');
		}
	} else if ( window.ActiveXObject ) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}

	if ( callback ) http_request.onreadystatechange = function() { callback(http_request) };
	http_request.open ( 'GET', url, true );
	http_request.send ( null );

	return true;
}

function Callback ( http_request )
{
	if ( http_request.readyState == 4 ) {
		if (http_request.status == 200) {
			alert(http_request.responseText);
		} else {
//			alert('There was a problem with the request.');
		}
	}
}

function UrlCall ( url )
{
	openUrl ( url, "" );
}


// called when checking note members on/off
function nlch ( noteid, linkid, add_linkid, checked, name, picturl )
{ 
	var id = 'frl'+noteid+'-'+add_linkid;
	var item = document.getElementById(id);

	//var checked = document.getElementById('ch'+noteid+'-'+linkid).checked;
	var url = "link_note.php";
	var args = "action=noteupdate";
	var change = 0;
	if ( checked )
	{
		if ( item )
		{
			item.style.display = item.olddisplay;
		} else {
			var container = document.getElementById('note'+noteid);
			if ( container )
			{
				if ( picturl != '' )
				{
					item = document.createElement('img');
					item.setAttribute('style','height: 24px;padding:0;margin:0;margin-left:2px;');
					item.src = picturl;
					item.title = name;
				} else {
					item = document.createElement('span');
					item.innerHTML = ', '+name;
				}
				item.id = id;
				container.appendChild(item);
			}
		}
		args += "&note["+noteid+"]["+add_linkid+"]=on";
		args += "&note_orig["+noteid+"]["+add_linkid+"]=0";
		change = 1;
	} else {
		if ( item )
		{
			item.olddisplay = item.style.display;
			item.style.display = 'none';
			change--;
		}
		//args += "&note["+noteid+"]["+linkid+"]=on";
		args += "&note_orig["+noteid+"]["+add_linkid+"]=1";

		if ( add_linkid - linkid != 0 ) // comparison using == failes, maybe string/int difference?
		{
			var id2 = 'frl'+noteid+'-'+linkid;
			var item2 = document.getElementById(id2);
			if ( item2 )
			{
				args += "&note_orig["+noteid+"]["+linkid+"]=1";
				item2.parentNode.removeChild(item2);
				change--;
			}
		}
	}

	var oval = parseInt(document.getElementById('notecount'+noteid).innerHTML);
	document.getElementById('notecount'+noteid).innerHTML = oval+change;
	//document.getElementById('notecount'+noteid).style.width = ((''+(oval+change)).length)+"em";

	postUrl ( url, args, '' );
}

function set_status(netid,s)
{
	var url = '/images/icon_busy.gif?v2';

	if ( s == 'BUSY' ) url = '/images/icon_busy.gif?v2';
	else if ( s == 'OK' ) url = '/images/icon_ok.png';
	else if ( s == 'NOK' || s == 'ERROR' || s == 'REMOVED' ) url = '/images/icon_nok.png';
	else if ( s == 'UPD' || s == 'R' ) url = '/images/icon_reload.gif';

	if ( s == 'REMOVED' )
	{
		var netline = document.getElementById('networkline'+netid);
		if ( netline ) netline.style.display = 'none';
	}

	var stat = document.getElementById('networkstatus'+netid);
	if ( netid && stat )
	{
		stat.src = url;
	}
}

function set_ident_status(netid,identid,s)
{
	if ( !identid ) return;
	var url = '/images/icon_busy.gif?v2';

	if ( s == 'BUSY' ) url = '/images/icon_busy.gif?v2';
	else if ( s == 'OK' ) url = '/images/icon_ok.png';
	else if ( s == 'NOK' || s == 'ERROR' || s == 'REMOVED' ) url = '/images/icon_nok.png';
	else if ( s == 'UPD' || s == 'R' ) url = '/images/icon_reload.gif';

	if ( s == 'REMOVED' )
	{
		var identline = document.getElementById('identline'+identid);
		if ( identline ) identline.style.display = 'none';
	}

	var stat = document.getElementById('identstatus'+identid);
	if ( identid && stat )
	{
		stat.src = url;
	}
}

var current_noteid = null;
var sugg_linkid = null;
function handle_ajax_response(msg,netid,identid)
{
	//alert(msg);
	var o = eval('('+msg+');');
	//alert("check");

	if ( !o ) { alert(msg); return; }

	if ( identid )
	{
		set_ident_status(netid,identid,o.status);
	} else {
		set_status(netid,o.status);
	}

	var statusline=o.message;

	// reset sugg_linkid on any event, unless we're requested to keep it
	var orig_sugg_linkid = sugg_linkid;
	sugg_linkid = null;

	if ( o.commands ) for ( var i = 0; i<o.commands.length; i++ )
	{
		var c = o.commands[i];

		if ( !c.cmd )
		{
			;// something is not ok, do nothing
		} else if ( c.cmd == 'RETAIN_SUGG_LINKID' ) {
			sugg_linkid = orig_sugg_linkid;
		} else if ( c.cmd == 'SET_CURRENT_NOTEID' ) {
			current_noteid = c.noteid;
		} else if ( c.cmd == 'INITIATE_LAYOUT_REDUCE' ) {
			initiate_layout_reduce();
		} else if ( c.cmd == 'REDIRECT' ) {
			if ( c.immediate )
			{
				window.location = c.url;
			} else {
				redirect_user(c.title,statusline,c.url);
			}
		} else if ( c.cmd == 'REPLACE' || c.cmd == 'ADDREPLACE' ) {
			var el = document.getElementById(c.id);
			if ( !el && c.cmd == 'ADDREPLACE' )
			{
				el = document.createElement(c.tagname);
				el.id = c.id;
				var p = document.getElementById(c.parentid);
				if ( p ) p.appendChild(el);
			}
			if ( el )
			{
				el.innerHTML = c.innerhtml?c.innerhtml:'';
				if ( c.className ) el.className = c.className;
				if ( c.style ) el.setAttribute("style",c.style);
				if ( c.onmouseover ) el.onmouseover = function() { eval(c.onmouseover); }; else el.onmouseover = null;
				if ( c.onmouseout ) el.onmouseout = function() { eval(c.onmouseout); }; else el.onmouseout = null;
				if ( c.id == 'friend_list' ) build_search_tree(el);
			}
		} else if ( c.cmd == 'REPLACEREG' ) {
			var re = new RegExp(c.regexp,c.regexp_modifiers);
			var el = document.getElementById(c.id);
			if ( el ) el.innerHTML = el.innerHTML.replace(re,c.innerhtml?c.innerhtml:'');
		} else if ( c.cmd == 'PREPEND' ) {
			var el = document.getElementById(c.id);
			if ( el ) el.innerHTML = (c.innerhtml?c.innerhtml:'')+el.innerHTML;
			if ( el && c.id == 'friend_list' ) build_search_tree(el);
		} else if ( c.cmd == 'APPEND' ) {
			var el = document.getElementById(c.id);
			if ( el ) el.innerHTML = el.innerHTML+(c.innerhtml?c.innerhtml:'');
		} else if ( c.cmd == 'ADDELEMENTONTOP' ) {
			var el = document.getElementById(c.id);
			if ( el )
			{
				var new_el = document.createElement(c.tagname);
				new_el.id = c.newid;
				new_el.innerHTML = c.innerhtml;
				el.insertBefore(new_el,el.firstChild);

				if ( el == fl ) update_search_tree(new_el);
			}
		} else if ( c.cmd == 'CHECKBOX' ) {
			plocky_checkbox_handler(c.id,c.baseid,c.noteid,c.list);
		} else if ( c.cmd == 'ADDELEMENTBEFORE' ) {
			var el = document.getElementById(c.id);
			if ( el )
			{
				var new_el = document.createElement(c.tagname);
				new_el.id = c.newid;
				new_el.innerHTML = c.innerhtml;
				if ( c.style ) new_el.setAttribute("style",c.style);
				if ( c.onmouseover ) new_el.onmouseover = function() { eval(c.onmouseover); }; else new_el.onmouseover = null;
				if ( c.onmouseout ) new_el.onmouseout = function() { eval(c.onmouseout); }; else new_el.onmouseout = null;
				el.parentNode.insertBefore(new_el,el);

				if ( el.parentNode == fl ) update_search_tree(new_el);
			}
		} else if ( c.cmd == 'PURGELIST' ) {
			if ( c.baseids )
			{
				var element_bases = c.baseids;
			} else {
				var element_bases = new Array(c.baseid);
			}
			var ids = c.list;
			for ( var k = 0; k<element_bases.length; k++ )
			{
				for ( var j = 0; j<ids.length; j++ )
				{
					var el = document.getElementById(element_bases[k]+ids[j]);
					if ( el && el.parentNode ) el.parentNode.removeChild(el);
				}
			}
		} else if ( c.cmd == 'SELECT' ) {
			var el = document.getElementById(c.id);
			if ( el ) el.selectedIndex = 1*c.selectedIndex;
		} else if ( c.cmd == 'STYLE' ) {
			var el = document.getElementById(c.id);
			if ( el ) el.setAttribute('style',c.style);
		} else if ( c.cmd == 'STYLELIST' ) {
			if ( c.baseids )
			{
				var element_bases = c.baseids;
				var style_tags = c.styles;
			} else {
				var element_bases = new Array(c.baseid);
				var style_tags = new Array(c.style);
			}
			var ids = c.list;
			for ( var k = 0; k<element_bases.length; k++ )
			{
				for ( var j = 0; j<ids.length; j++ )
				{
					var el = document.getElementById(element_bases[k]+ids[j]);
					if ( el ) el.setAttribute('style',style_tags[k]);
				}
			}
		} else if ( c.cmd == 'SERVER_ERROR' ) {
			log_message("<pre>"+c.msg+"</pre>");
		} else if ( c.cmd == 'COMEGETMORE' ) {
			network_update(netid,"incomplete","full");
		} else if ( c.cmd == 'CALCULATE_TIMEZONE' ) {
			calculate_time_zone(c.id?c.id:'fields[plocky_tz]');
		} else if ( c.cmd == 'SHOWPOPUP' ) {
			show_popup(c.title,c.message,c.url,c.onclick,c.buttext);
		} else if ( c.cmd == 'HIDEPOPUP' ) {
			disablePopup();
		}
	}
	log_message(statusline,netid);
}

function ajax_request(method,args,netid,identid)
{
	if ( !args ) args = '';
	if ( !netid ) netid = 0;
	if ( !identid ) identid = 0;
//	if ( netid == 0 )
//	{
		//postUrl("/ajax.php",'ajax='+method+'&'+args,update_callback,netid);
		postUrl("/",'ajax='+method+'&'+args,update_callback,netid,identid);
//	} else {
//		postUrl_map[netid]("/ajax.php",'ajax='+method+'&'+args,update_callback,netid);
//	}
}

function show_popup(title,message,url,onclick,buttext)
{
	var titlebox = document.getElementById('popupTitle');
	if ( titlebox ) titlebox.innerHTML = title;

	var messagebox = document.getElementById('popupContent');
	if ( messagebox ) messagebox.innerHTML = message;

	if ( !buttext ) buttext = "OK";

	var popupLink = document.getElementById('popupLink');
	//var popupClose = document.getElementById('popupClose');
	if ( url || onclick )
	{
		if ( popupLink )
		{
			popupLink.style.visibility = 'visible';
			popupLink.href = url;
			popupLink.innerHTML = buttext;
			if ( onclick != null )
			{
				if ( typeof onclick == 'function' )
				{
					popupLink.onclick = onclick;
				} else {
					popupLink.onclick = new Function(onclick);
				}
			}
		}
	} else {
		if ( popupLink ) popupLink.style.visibility = 'hidden';
	}

	centerPopup();
	loadPopup();
}

function update_callback(req,netid,identid)
{
	if ( req.readyState == 4 )
	{
		if ( req.status == 200 )
		{
			set_status(netid,'NOK'); // if we crash below, make sure state is left set NOK
			set_ident_status(netid,identid,'NOK'); // if we crash below, make sure state is left set NOK
			handle_ajax_response(req.responseText,netid,identid);
		} else {
			//alert(req.responseText);
			set_status(netid,'NOK');
			set_ident_status(netid,identid,'NOK');
			handle_ajax_response(req.responseText,netid,identid);
		}
	}
}

var msgbox=null;
function log_message(msg,netid)
{
	if ( msg == '' || msg == '-' ) return;
	if ( !msgbox ) msgbox = document.getElementById('messagebox');
	if ( !msgbox ) return;
	if ( netid > 0 ) msgbox.innerHTML += '<img alt="'+netnames[netid]+'" class="netlogo" src="/get_logo.php?netid='+netid+'"> ';
	msgbox.innerHTML += msg+"<br />";
}

function legal_user(cid)
{
	ajax_request("loadpopup","id="+cid);
}

function getmyurl()
{
	var url = window.location.href;
	url = url.replace(/#.*$/,"");
	return url;
}

function highlight_li(id,count,toggle)
{
	var el = document.getElementById(id);

	if ( el ) highlight_li_next(el,count,toggle);
}

function highlight_li_next(el,count,toggle)
{
	el.style.background = toggle?'#ccccff':'';
	if ( count > 1 )
	{
		el = el.nextSibling;
		while ( el && el.tagName != 'LI' ) el = el.nextSibling;
		if ( el ) highlight_li_next(el,count-1,toggle);
	}
}

function xabs(e) { return e.pageX?e.pageX:e.clientX+document.body.scrollLeft; }
function yabs(e) { return e.pageY?e.pageY:e.clientY+document.body.scrollTop; }

function add_mousemove_handler() { document.onmousemove = movable_frame_mousemove; } 
function remove_mousemove_handler() { document.onmousemove = null; }

var movable_frame_current=null;
var movable_frame_dragging = 0;
var attached_x = 0; var attached_y = 0;
var orig_x = 0; var orig_y = 0;
var must_detach = false;
var next_drag_event = null;
function movable_frame_mousedrag(e)
{
	if ( movable_frame_dragging == 1 ) return false;
        if ( !e ) { e = window.event; if ( !e ) return; }

	if ( dragdrop_locked == true )
	{
 // cancel current dropping action asap and get back here
		next_drag_event = e;
		return false;
	}
	next_drag_event = null;

        if (e.stopPropagation) e.stopPropagation();
        var input;
        if ( e.target ) input = e.target;
        else if ( e.srcElement ) input = e.srcElement;
        if ( !input ) return false;

	movable_frame_current = null;
	while ( input && input != document.body )
	{
		if ( input.className.search("draggable") >= 0 ) { movable_frame_current = input;  break; }
		input = input.parentNode;
	}
	if ( !movable_frame_current ) return false;

	movable_frame_current.justdragged = null;
	movable_frame_dragging = 1;
	add_mousemove_handler();
	attached_x = xabs(e);
	attached_y = yabs(e);

	orig_x = offX(movable_frame_current);
	orig_y = offY(movable_frame_current);

	must_detach = true;

	movable_frame_mousemove_savexy(e);

	return false;
}

function movable_frame_mouseup(e)
{
	if ( movable_frame_dragging )
	{
        	//if ( !e ) e = window.event;
		remove_mousemove_handler();
		if ( !must_detach ) movable_frame_subst_proxy();
	}
	movable_frame_dragging = 0;
}

function movable_frame_detach()
{
	movable_frame_current.position_orig = movable_frame_current.style.position;
	movable_frame_current.style.position = 'absolute';
	movable_frame_opacitate();
	movable_frame_insert_proxy();
}

function movable_frame_opacitate(calledat,prev_op)
{
	if ( !movable_frame_current.style.opacity ) movable_frame_current.style.opacity = 1;
	var op = movable_frame_current.style.opacity;
	if ( prev_op && op > prev_op ) return;
	op *= 0.93;

	var d = new Date(); // bail out if we're slow
	var now = d.getTime();
	if ( calledat && now - calledat > 300 ) op = 0.7;

	movable_frame_current.style.opacity = op;
	movable_frame_current.style.filter = "alpha(opacity="+Math.round(100*op)+")";
	if ( movable_frame_current.style.opacity > 0.7 ) setTimeout("movable_frame_opacitate("+now+","+op+");",200);
}

var movable_frame_proxy = null;
function movable_frame_insert_proxy()
{
	movable_frame_proxy = document.createElement('DIV');
	movable_frame_proxy.style.width = movable_frame_current.offsetWidth+'px';
	movable_frame_proxy.style.height = movable_frame_current.offsetHeight+'px';
	movable_frame_current.parentNode.insertBefore(movable_frame_proxy,movable_frame_current.nextSibling);
	proxyx = offX(movable_frame_proxy);
	proxyy = offY(movable_frame_proxy);
	movable_frame_current.className += " dragging";
}

function offX(el)
{
	var x = el.offsetLeft;
	if ( el.offsetParent )
	{
		for ( var walk = el.offsetParent; walk && walk != document.body ; walk = walk.offsetParent ) x += walk.offsetLeft;
	}
	return x;
}

function offY(el)
{
	var y = el.offsetTop;
	if ( el.offsetParent )
	{
		for ( var walk = el.offsetParent; walk && walk != document.body ; walk = walk.offsetParent ) y += walk.offsetTop;
	}
	return y;
}

var dragdrop_locked = false;
function movable_frame_subst_proxy(calledat,xdist,ydist,ox,oy)
{
	dragdrop_locked = true;

	if ( !calledat )
	{
		var ox = offX(movable_frame_proxy);
		var oy = offY(movable_frame_proxy);
		var ydist = offY(movable_frame_current) - oy;
		var xdist = offX(movable_frame_current) - ox;
	}

	if ( !next_drag_event && ( ydist < -1 || ydist > 1 || xdist < -1 || xdist > 1 ) )
	{
		var d = new Date();
		var drop_interval = 100;
		if ( !calledat || d.getTime() - calledat < 1.5*drop_interval )
		{
			ydist *= 0.85;
			xdist *= 0.85;
			if ( xdist < -1 ) xdist++; else if ( xdist > 1 ) xdist--;
			if ( ydist < -1 ) ydist++; else if ( ydist > 1 ) ydist--;

			newy = parseInt(oy + ydist);
			movable_frame_current.style.top = ''+newy+'px';

			newx = parseInt(ox + xdist);
			movable_frame_current.style.left = ''+newx+'px';

			var op = movable_frame_current.style.opacity;
			if ( op < 1 )
			{
				op *= 1.05;
				if ( op > 1 ) op = 1;
				movable_frame_current.style.opacity = op;
				movable_frame_current.style.filter = "alpha(opacity="+Math.round(100*op)+")";
			}

			setTimeout('movable_frame_subst_proxy('+d.getTime()+','+xdist+','+ydist+','+ox+','+oy+');',drop_interval);
			return;
		}
	}
	movable_frame_current.style.top = ''+oy+'px';
	movable_frame_current.style.left = ''+ox+'px';
	movable_frame_current.style.opacity = 1;
	movable_frame_current.style.filter = "alpha(opacity=100)";
	
	movable_frame_current.className = movable_frame_current.className.replace(/dragging/,"");
	var d = movable_frame_current.parentNode.removeChild(movable_frame_current);
	d.style.position = d.position_orig;
	movable_frame_proxy.parentNode.insertBefore(d,movable_frame_proxy);
	movable_frame_proxy.parentNode.removeChild(movable_frame_proxy);
	delete movable_frame_proxy;
	d.justdragged = true;
	gui_log_change();
	dragdrop_locked = false;
	movable_frame_mousedrag(next_drag_event);
}

var lasty = 0;
var lastx = 0;
var proxyx = 0;
var proxyy = 0;
function movable_frame_mousemove_savexy(e)
{
        if ( !e ) e = window.event;
	var topy = orig_y + yabs(e) - attached_y;
	var leftx = orig_x + xabs(e) - attached_x;
	lasty = topy;
	lastx = leftx;
}

function movable_frame_mousemove(e)
{
	if ( !movable_frame_dragging ) return true;
        if ( !e ) e = window.event;

	var topy = (orig_y + yabs(e) - attached_y);
	var bottomy = topy + movable_frame_current.offsetHeight;
	var leftx = orig_x + xabs(e) - attached_x;

	if ( must_detach )
	{
		if ( Math.abs(lasty-topy)+Math.abs(lastx-leftx) > 5 )
		{
			movable_frame_detach();
			must_detach = false;
		} else {
			return;
		}
	}

	lasty = topy;
	lastx = leftx;

	movable_frame_current.style.top = ''+topy+'px';
	movable_frame_current.style.left = ''+(proxyx*2/3+leftx/3)+'px';

	if ( topy < movable_frame_proxy.offsetTop )
	{
		for ( var el = movable_frame_proxy.parentNode.firstChild; el && el != movable_frame_proxy; el = el.nextSibling )
		{
			if ( !el.tagName || el.tagName != 'DIV' || el == movable_frame_current ) continue;
			if ( topy < el.offsetTop + el.offsetHeight/2 ) {
				movable_frame_proxy = movable_frame_current.parentNode.removeChild(movable_frame_proxy);
				el.parentNode.insertBefore(movable_frame_proxy,el);
				proxyx = offX(movable_frame_proxy);
				proxyy = offY(movable_frame_proxy);
				break;
			}
		}
	} else if ( bottomy > movable_frame_proxy.offsetTop + movable_frame_proxy.offsetHeight ) {
		for ( var el = movable_frame_proxy.nextSibling; el && el.id != 'footer'; el = el.nextSibling )
		{
			if ( !el.tagName || el.tagName != 'DIV' || el == movable_frame_current ) continue;
			if ( bottomy > el.offsetTop+el.offsetHeight/2 ) {
				movable_frame_proxy = movable_frame_current.parentNode.removeChild(movable_frame_proxy);
				el.parentNode.insertBefore(movable_frame_proxy,el.nextSibling);
				proxyx = offX(movable_frame_proxy);
				proxyy = offY(movable_frame_proxy);
				break;
			}
		}
	}

	return false;
}

function gui_find_box(el)
{
	for ( ; el && el.tagName && el.tagName != 'BODY' ; el = el.parentNode )
	{
		if ( el.className && el.className.match(/(small|large)_box/) && !el.className.match(/box_top/) ) return el;
	}
	return null;
}

function gui_find_content(el,block_recursion)
{
	if ( !el ) return null;
	for ( i in el.childNodes )
	{
		if ( el.childNodes[i] && el.childNodes[i].className && el.childNodes[i].className.match(/(small|large)_box_content/) ) return el.childNodes[i];
	}
	if ( !block_recursion ) for ( i in el.childNodes )
	{
		var deep = gui_find_content(el.childNodes[i],true);
		if ( deep ) return deep;
	}
	return null;
}

function gui_el_from_event(e)
{
	if ( !e ) e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
	var input;
	if ( e.target ) input = e.target;
	else if ( e.srcElement ) input = e.srcElement;
	if ( !input ) alert("problem with event handler");
	if ( input.nodeType == 3 ) input = input.parentNode; // safari bug?
	return input;
}

function gui_event_close(e)
{
	var el = gui_el_from_event(e);
	el = gui_find_box(el);
	el = gui_find_content(el);
	if ( !el ) return;

	if ( gui_is_minimized(el) )
	{
		gui_maximize(el);
	} else {
		gui_minimize(el);
	}
}

function gui_event_forceopen(e)
{
	var el = gui_el_from_event(e);
	el = gui_find_box(el);
	if ( el.justdragged || dragdrop_locked )
	{
		el.justdragged = null;
		return;
	}
	el = gui_find_content(el);
	if ( !el ) return;
	gui_maximize(el);
}

function gui_minimize(el)
{
	el.style.display = 'none';
	gui_log_change();
}

function gui_is_minimized(el)
{
	return el&&el.style&&(el.style.display == 'none');
}

function gui_maximize(el)
{
	el.style.display = 'block';
	gui_log_change();
}

var laststate = '';
function gui_log_change()
{
	var c = document.getElementById('content');

	var state = '';
	var sep = '';
	for ( ch = c.firstChild; ch; ch = ch.nextSibling )
	{
		if ( !ch.tagName || ch.tagName != 'DIV' || !ch.className || ch.className.search("draggable") == -1 ) continue;
		var content = gui_find_content(ch);
		if ( content )
		{
			state += sep;
			if ( content.style.display == 'none' ) state += '-';
			state += ch.id.replace(/_box/,"");
			sep = ',';
		}
	}
	if ( state != laststate )
	{
		ajax_request("profile_save","fields[boxorder]="+state);
	}
	laststate = state;
}

// included from script by Josh Fraser (http://www.onlineaspect.com)
// small amendments by plocky.com
function calculate_time_zone(id) {
	var rightNow = new Date();
	var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
	var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
	var temp = jan1.toGMTString();
	var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	temp = june1.toGMTString();
	var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
	var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
	var dst;
	if (std_time_offset == daylight_time_offset) {
		dst = "0"; // daylight savings time is NOT observed
	} else {
		// positive is southern, negative is northern hemisphere
		var hemisphere = std_time_offset - daylight_time_offset;
		if (hemisphere >= 0)
			std_time_offset = daylight_time_offset;
		dst = "1"; // daylight savings time is observed
	}
	var i;
	// check just to avoid error messages
	var el = document.getElementById(id);
	if ( el )
	{
		for (i = 0; i < el.options.length; i++) {
			if ( el.options[i].value == convert_offset_tz(std_time_offset)+","+dst) {
				el.selectedIndex = i;
				break;
			}
		}
	}
}

function convert_offset_tz(value) {
	var hours = parseInt(value);
   	value -= parseInt(value);
	value *= 60;
	var mins = parseInt(value);
   	value -= parseInt(value);
	value *= 60;
	var secs = parseInt(value);
	var display_hours = hours;
	// handle GMT case (00:00)
	if (hours == 0) {
		display_hours = "00";
	} else if (hours > 0) {
		// add a plus sign and perhaps an extra 0
		display_hours = (hours < 10) ? "+0"+hours : "+"+hours;
	} else {
		// add an extra 0 if needed 
		display_hours = (hours > -10) ? "-0"+Math.abs(hours) : hours;
	}
	
	mins = (mins < 10) ? "0"+mins : mins;
	return display_hours+":"+mins;
}

//onload = calculate_time_zone;

function invite_submit(form)
{
	if ( !form ) form = document.getElementById("inviteform");
	if ( !form ) return;
	var formel = form.getElementsByTagName("input");
	if ( !formel ) return;
	var post = "";
	post += "doinvite=1&personalmsg="+encodeURIComponent(document.getElementById("personalmsg").value);
	for ( var i=0; i<formel.length; i++ )
	{
		if ( formel[i].type == "checkbox" )
		{
 			if ( formel[i].checked ) post += "&"+formel[i].name+"=on";
		}
	}
	
	ajax_request("friendinvite",post);
	return false;
}

function invite_select(check)
{
	var form = document.getElementById("inviteform");
	if ( !form ) return;
	var formel = form.getElementsByTagName("input");
	if ( !formel ) return;
	for ( var i=0; i<formel.length; i++ )
	{
		if ( formel[i].type == "checkbox" ) formel[i].checked = check;
	}
	return false;
}


