/*global document, window, $, $$, Class, Constants, doNifty, Ajax, statusBar, WindowUtilities, LoginLink */
var Friend = new Class({
	initialize: function () {
		this.root = $('Profile');
		if (!this.root) { this.root = $('contentHolder'); } // this.root = $('Profile') || $('contentHolder');
		this.url = Constants.ajax()+'processFriends';
		this.mode = 'get';
		this.ajax = {};
		this.fcdiv = $('friendConfirm') || document.body.appendChild(document.create('div', 'friendConfirm'));
		this.checkP = Constants.images()+"mmmail/msg_close_p.jpg";
		this.checkU = Constants.images()+"mmmail/msg_close_u.jpg";
		if (this.root) {
			var links, i;
			links = this.root.getElementsByClassName('flink_addL', 'a');
			for (i=0; i<links.length; ++i) { this.buildAddEvent(links[i]); }
			links = this.root.getElementsByClassName('flink_rmvL', 'a');
			for (i=0; i<links.length; ++i) { this.buildRmvEvent(links[i]); }
			links = this.root.getElementsByClassName('flink_waitL', 'a');
			for (i=0; i<links.length; ++i) { this.buildWaitEvent(links[i]); }
		}
		this.niftyFriends();
	}, niftyFriends: function () {
		doNifty("div#myfriends", "large transparent");
		doNifty("div.friendout", "large transparent");
		doNifty("div.friend", "large transparent");
		//doNifty("div.friendbtm", "large transparent bottom");
		doNifty("div#quickMenu,div#subQuickMenu,div#adBarHolder,div#adBar,div#contentHolder", "small");
	}, cancelBubble: function (e) {
		// from http://www.quirksmode.org/js/events_order.html
		if (!e) { e = window.event; }
		if (e) {
			e.cancelBubble = true;
			if (e.stopPropagation) { e.stopPropagation(); }
		}
	}, frndFunc: function (func,mode,id,un,add,el) {
		if (!mode) { mode='s'; }
		var params = 'm='+mode+'&f='+func+'&id='+id;
		this.ajax = new Ajax( this.url, { method: this.mode, parameters: params, onFailure: this.reportError, onSuccess: (function (request) { this.parseFriends(request); this.friendDone(func,add,un,el,id);} ).bind(this) });
		this.ajax.send();
	}, parseFriends: function (request) {
		//var resp = JSON.parse(request.responseText);
	}, doFriend: function ( add, el, e ) {
		this.cancelBubble(e);
		var un, id, ids, span = el;
		if (el.name) { ids = el.name.split("|"); }
		else {
			do { span = $$(span.nextSibling); }
			while (span.nodeType === 3 || !span.isNode('SPAN'));
			ids = span.scan(true).split("|");
		}
		id = ids[0];
		un = ids[1];
		var checkP = this.checkP, checkU = this.checkU;
		if (add==='sent') {
			statusBar.talk('You have already sent a friend request to <span id="friendConfirm_un">'+un+'</span>.');
			this.hideConfirm();
		} else {
			var str = add ? "add" : "remove", prep = add ? "to" : "from",
				pfx = "friendConfirm_", d = "div", c = "clear",
				top = document.create(d, pfx+"top"),		close = top.create(d,"fc_close",null,'&nbsp'),
				mid = document.create(d, pfx+"mid"), 		imgD = mid.create(d, pfx+"img"),
				img = imgD.create("img", pfx+"imgI"),	fmsg = mid.create(d, pfx+"msg"),
				fun = document.create("span", pfx+"un", null, un),
				fyes = mid.create(d, pfx+"yes"), 		yesL = fyes.create("a", pfx+"yesLink", null, str),
				clr = mid.create(d,c,c), 				clr2 = document.create(d,c,c),
				fbtm = document.create(d, pfx+"btm"),		fid = document.create(d, pfx+"id", null, id),
				fCP = document.create(d, pfx+"cP", "hide"),	fCPI = fCP.create("img");
					img.src = Constants.profilePic(id, 'small');
					fmsg.update('Are you sure you want to '+str+' <span id="friendConfirm_un">'+un+'</span> '+prep+' your friends?');
			this.fcdiv.empty().appendChildren([top,mid,fbtm,fid,fCP,clr2]);
			$(yesL.id).setClick((function (e) { this.friendAct(add, id, el, e); }).bind(this));
			// change el to the right kind of link
			var fcC = $(close.id);
			fcC.setClick((function (e) { this.hideConfirm(e); }).bind(this));
			fcC.setEvent('mouseover',  function () { fcC.style.cursor = "pointer"; fcC.style.backgroundImage = "url("+checkP+")"; });
			fcC.setEvent('mouseout',  function () { fcC.style.backgroundImage = "url("+checkU+")"; });
			this.fcdiv.popup(this.hideConfirm.bind(this));
			statusBar.hide();
		}
	}, buildAddEvent: function (el) {
		el.setClick((function (e) { this.doFriend(true, el, e); }).bind(this));
	}, buildRmvEvent: function (el) {
		el.setClick((function (e) { this.doFriend(false, el, e); }).bind(this));
	}, buildWaitEvent: function (el) {
		el.setClick((function (e) { this.doFriend('sent', el, e); }).bind(this));
	}, hideConfirm: function (e) {
		this.cancelBubble(e);
		this.fcdiv.hide().empty();
		WindowUtilities.enableScreen();
	}, friendAct: function (add, id, el, e) {
		this.cancelBubble(e);
		var un = $('friendConfirm_un').scan();
		$('friendConfirm_msg').update('Loading...<br /><img src="'+Constants.ajaxImages()+'progress2.gif" alt="Loading..." />');
		$('friendConfirm_yesLink').remove();
		this.frndFunc(add ? 'r' : 'x','s',id,un,add,el);
	}, friendDone: function (func,add,un,el,id) {
		var ct, i,
			msg = add ? 'A friend request has been sent to <span id="friendConfirm_un">'+un+'</span>. (pleeease be my friend?)' : un+' has been removed from your friends. (Are you soooo in a fight?)';
		if (el.id && $(el.id)) {
			if (el.parentNode.parentNode.id !== "profileFriendList") {
				if (el) {
					el.update(add ? "friend request pending" : "add as a friend").setClassName(add ? "flink_waitL" : "flink_addL");
					if (add) { this.buildWaitEvent(el); }
					else { this.buildAddEvent(el); }
				}
			}
			var prol = add ? $('flink_addL_'+id) : $('flink_rmvL_'+id), proDiv, mine = !$("ratings");
			if (prol) {
				if (!add && mine) {
						$$(prol.parentNode.parentNode.parentNode.parentNode).remove();
						var pFL = $("profileFriendList");
						if (pFL) {
							var cN = pFL.getChildNodes(true);
							ct = 0;
							for (i = 0; i < cN.length; ++i) { ct += cN[i].isNode('div') ? 1 : 0; }
							if (ct === 0) {
								pFL.empty();
								var fEL = pFL.create("div", "fr_emptylist", "fr_emptylist"),
									fELtxt1 = fEL.createText(un+' has no friends - not even Tom!<br /><br />Why not '),
									eAL = fEL.create("a", "emptyAddLink", "hand", "add"),
									eSpan = fEL.create("span", '', "hide", id+'|'+un),
									fELtxt2 = fEL.createText('him or her, and make him or her feel special?');
									this.buildAddEvent($(eAL.id));
							}
						}
				} else {
					prol.update(add ? "friend request pending" : "add as a friend");
					prol.setClassName(add ? "flink_waitL" : "flink_addL");
					if (add) { this.buildWaitEvent(prol); }
					else { this.buildAddEvent(prol); }
				}
			}
			if ($('emptyAddLink')) { $("profileFriendList").update('<div id="fr_emptyList" class="fr_emptyList">'+un+' has not yet responded to your friend request.</div>'); }
		}
		if (!add) { //
			var fL = $("friendList");
			if (fL) {
				var fcN = fL.getChildNodes(true);
				ct = 0;
				for (i = 0; i < fcN.length; ++i) { ct += fcN[i].isNode('div') ? 1 : 0; }
				if (ct === 0) {
					var ffEL = document.create("div", "fr_emptyList", "fr_emptyList"),
						ffELtxt1 = ffEL.createText('You have no friends - not even Tom!'),
						br1 = ffEL.create("br"), br2 = ffEL.create("br"),
						ffELtxt2 = ffEL.createText('Go get yourself some friends!');
						fL.empty().appendChild(ffEL);
				}
				$("numfriends").update(ct);
			} //
		}
		if (msg) {
			statusBar.talk(msg);
			this.hideConfirm();
		}
	}
});

var friend, eLogLink, aLogLink;
window.addLoad(function () {
	friend = new Friend();
	var eAL = $('emptyAddLink'), eLL = $('emptyLogLink'), eALL = $('emptyAddLLink');
	if (eAL) { friend.buildAddEvent(eAL); }
	if (eLL) { eLogLink = LoginLink.setup(eLL.id); }
	if (eALL) { aLogLink = LoginLink.setup(eALL.id); }
});
