/*globals $, $$, Element, Constants, START_INDEX, START_ASC, Ajax, statusBar, MbitLinks, isset, Handfuls, cancelBubble, makeFakeLink, Class, startTab */
// table sort params
START_INDEX = 6;
START_ASC = false;

var ProfileUserStatic = function () {
	var _tableCounts = {created:0,uploaded:0},
		_tableNames = ['created','uploaded'],
		_currThoughtPool = _tableNames[0],
		self = {
		_undoing: false,
		setup: function () {
			self.mbitLinks = new MbitLinks({
				isSequencer: false,
				topOffset:205,
				topBgndOffset:205,
				leftOffset:55,
				leftBgndOffset:55,
				pinCallback: self.checkAdded,
				unpinCallback: self.checkRemoved
			});
		},
		checkAdded: function (request) {
			var response = JSON.parse(request.responseText);
			if (response.status == 1) {
				//ProfileUserStatic.mbitLinks.updateLinks(response.id, _currTab);
				var msg = self._undoing ? "Re-a" : "A";
				statusBar.talk(msg+"dded to your palette");
				if (!self._undoing) {
					var undo = document.create("a", "undoAddLink", "blue hand", "Undo");
					undo.setClick(function () {
						self._undoing = true;
						self.mbitLinks.unPin(response.id);
					});
					statusBar.map([undo]);
				}
				self._undoing = false;
			} else if (response.status == 2) {
				statusBar.talk("This is already in your palette");
			} else { statusBar.error("Failed to add to your palette"); }
		},
		checkRemoved: function (request) {
			var response = JSON.parse(request.responseText);
			if (response.status == 1) {
				//ProfileUserStatic.mbitLinks.updateLinks(response.id, _currTab);
				var msg = self._undoing ? "Adding to your Palette undone." : "Removed from your Palette.";
				statusBar.talk(msg);
				if (!self._undoing) { 
					var undo = document.create("a", "undoPinRmv", "blue hand", "Undo");
					undo.setClick(function () {
						self._undoing = true;
						self.mbitLinks.pin(response.id);
					});
					statusBar.map([undo]);
				}
				self._undoing = false;
			} else { statusBar.error("Failed to remove from your palette"); }
		},
		switchThoughtPool: function (where) {
			if (!isset(typeof(where)) || _currThoughtPool != where) {
				if (!isset(typeof(where))) { where = _currThoughtPool; }
				if (_currThoughtPool) {
					$(_currThoughtPool + 'Link').removeClassName('selected');
					$(_currThoughtPool).hide();
				}
				$(where + 'Link').addClassName('selected');
				var wh = $(where);
				wh.show();
				_currThoughtPool = where;
				ProfileUserStatic.mbitLinks.closeResult(0);
				$('what').update(where);
				$('howMany').update(_tableCounts[where]);
				Handfuls.setList(wh.empty());
				Handfuls.setType('userprofile_' + where.substring(0,1));
				Handfuls.go();
			}
		},
		setupThoughtPoolTable: function (tbl, zero) {
			makeFakeLink($(tbl + 'Link'),(function (e){cancelBubble(e); self.switchThoughtPool(tbl);}).bind(this));
			var tblEl = $(tbl), rows = tblEl.rows, mine = tblEl.hasClassName('mine'), count = 0, i;
			for (i=1; i<rows.length; ++i) {
				if (rows[i].id !== "" && !zero) {
					self.addRowEvents($$(rows[i]), mine);
					++count;
				}
			}
			_tableCounts[tbl] = count;
		},
		addRowEvents: function (row, mine) {
			var id = row.id.substring(2);
			row.addEvent('mouseover', self.mbitLinks.hoverResult.bind(this.mbitLinks, row, id));
			row.addEvent('mousemove', self.mbitLinks.prolong);
			row.addEvent('mouseout', self.mbitLinks.closeResult);
			row.addClassName('thoughtPoolHover');
		},
		rowHeader: function (list) {
			if ($$(list)) {
				var rowH = list.create("tr");
				rowH.create("th").classify("hide");
				rowH.create("th").classify("title").create("div").update("title");
				rowH.create("th").classify("genre").create("div").update("genre");
				rowH.create("th").classify("instrument").create("div").update("instruments");
				rowH.create("th").classify("tempo").create("div").update("tempo");
				rowH.create("th").classify("key").create("div").update("key");
				rowH.create("th").classify("date").create("div").update("date");
			}
		},
		rowsHandful: function (data, list) {
			for (var id in data) if (data.hasOwnProperty(id)) {
				var row = list.create("tr", 'u_'+id),
					genre = data[id].g === "" ? "&nbsp;" : data[id].g,
					inst = data[id].i === "" ? "&nbsp;" : data[id].i,
					tempo = data[id].t === "" ? "&nbsp;" : data[id].t + "bpm",
					tdID = row.create("td", list.id+'_'+id+'_name', "hide", data[id].n),
					bLink = row.create("td").classify("title").create("div").
						create("a").update(data[id].bN).attrib('href', Constants.profileLink(id)),
					tdGenre = row.create("td").classify("genre").create("div").update(genre),
					tdInst = row.create("td").classify("instrument").create("div").update(inst),
					tdTempo = row.create("td").classify("tempo"),
					tdKey = row.create("td").classify("key").create("div").classify("hide").update(data[id].c),
					tdDate = row.create("td").classify("date").create("div").update(data[id].d),
					tHide = tdTempo.create("div").classify("hide").update(data[id].t),
					tShow = tdTempo.create("div").update(tempo);
			}
		}
	};
	return self;
}();
window.addLoad(ProfileUserStatic.setup);

var ProfileUser = new Class({
	initialize: function () {
		this.delUrl = Constants.ajax() + 'delComment';
		this.saveURL = Constants.ajax() + 'saveComments';
		this.mouseoutTimer = this.mouseinTimer = null;
		this.selectedTabs = [];
		this.comment = $('newcomment');
		this.defaultComment = 'post a comment ...';

//		this.deleteComment();
	},
	deleteComment: function () {
		var i, delLinks = document.getElementsByClassName("delComment", "a")
		for (i=0; i < delLinks.length; i++) {
			this.addDeleteEvents($$(delLinks[i]));
		}
	},
	initCommentBox: function () {
		var pnc = $('postnewcomment'), me = this;
		if (pnc) {
			pnc.setClick(this.saveComments.bind(this));
			this.comment.value = this.defaultComment;
			this.comment.addEvent('focus', function () { me.clearThis(); });
			this.comment.addEvent('blur', function () { me.fillThis(); });
		}
	},
	// Switch the current content with the selected content (by using the display property)
	switchTab: function (div, tabIndex) {
		if ( this.selectedTabs[div.id] != tabIndex ) {
			var tabHeaders = div.getChildNodes(), i, j;
			for (i=0, j=0; i<tabHeaders.length; ++i ) {
				if ( tabHeaders[i].isNode('div') ) {
					if ( j == this.selectedTabs[div.id] ) {
						tabHeaders[i].removeClassName('currentTab');
						var oldTab = $(div.id + '_' + this.selectedTabs[div.id]);
						if (oldTab) { oldTab.hide(); }
					}
					if ( j == tabIndex ) {
						tabHeaders[i].addClassName('currentTab');
						var newTab = $(div.id + '_' + tabIndex);
						if (newTab) { newTab.show(); }
					}
					++j;
				}
			}
			this.selectedTabs[div.id] = tabIndex;
		}
	},
	addTabNavigation: function (div){
		if ( div.id ) {
			this.selectedTabs[div.id] = -1;
			var tabHeaders = div.getChildNodes(), i, j;
			for (i=0, j=0; i<tabHeaders.length; ++i ) {
				// Attach tab switching javascript to the spans
				if ( tabHeaders[i].isNode('div') ) {
					this.attachTabLink(div, tabHeaders[i], j);
					if ( tabHeaders[i].className.indexOf('currentTab') != -1 ) {
						this.switchTab(div,tabHeaders[i].className.indexOf('currentTab'));
						this.selectedTabs[div.id] = j;
					}
					++j;
				}
			}
			// Select the first tab is none is specified with CSS
			if ( (this.selectedTabs[div.id] == -1) && (j!==0) ) {
				this.switchTab(div, 0);
				this.selectedTabs[div.id] = 0;
			}
			if (startTab) { this.switchTab(div,startTab); }
		}
	},

	// Attach the clickable javascript to the tab header
	attachTabLink: function (div, tabHeader, tabIndex){
		var me = this;
		tabHeader.setClick(me.switchTab.bind(me, div, tabIndex));
	},
	addDeleteEvents: function (el) {
		var me = this;
		el.addClick(me.delCom.bind(me, el.id));
	},
	delCom: function (commentid) {
		if (window.confirm("are you sure you want to remove this comment?")) {
			//var comObj = $(commentid);
			//var comParent = comObj.parent;
			var pars = 'cid=' + commentid,
				delAjax = new Ajax( this.delUrl,
				{	method: 'get',
					parameters: pars,
					onComplete: function (request) {
						var response = JSON.parse(request.responseText), comDiv;
						if (response.status == 1) {
							comDiv = $('c_'+response.id);
							if (comDiv) { comDiv.remove(); }
						}
						else { statusBar.error("Could not remove comment"); }
					}
				});
			delAjax.send();
		}
	},
	saveComments: function () {
		var txt = $('newcomment');
		if (txt.value === this.defaultComment) {
			window.alert("You did not change the default text.");
		} else if (txt.value === '') {
			window.alert("You cannot enter a blank comment.");
		} else {
			var me = this,
				subjectid = $('subjectid'),
				pars = 'comment_txt=' + encodeURIComponent(txt.value) + '&subjid=' + encodeURIComponent(subjectid.value),
				myAjax = new Ajax( this.saveURL,
				{	method:'get',
					parameters:pars,
					onSuccess: function (request) {
						me.updateComments(request);
						txt.value = me.defaultComment;
					},
					onFailure: function () { statusBar.error('Could not save comment'); }
				}
			);
			myAjax.send();
		}
	},
	updateComments: function (request){
		var cm = $('comments');
		if (cm && cm.handful) { cm.handful.firstPage(true); }
	},

	//clear the comment/note textarea
	clearThis: function () {  if (this.comment.value==this.defaultComment) { this.comment.value = ''; } },
	fillThis: function () { if (this.comment.value.trim() === '') { this.comment.value = this.defaultComment; } }
});

var SocialLinks = function () {
	var self = {
			attachHover: function (el) {
				var lbl = $('user_social_lbl');
				if (lbl && $$(el)) {
					el.addEvent('mouseover', function () { lbl.update(el.name.split('|')[0]); });
					el.addEvent('mouseout', function () { lbl.empty(); });
				}
				return !!lbl;
			},
			setup: function () {
				var socs = $('user_socials').getElementsByClassName("Social", "a"), i;
				for (i = 0; i < socs.length; ++i) { self.attachHover(socs[i]); }
			}
		};
	return self;
}();
window.addLoad(SocialLinks.setup);
