/* jslint verified 2008.09.25 */
/*jslint browser: true, onevar: false, undef: true, white: false, eqeqeq: true */
/*globals $, $$, Class, Constants, Ajax, START_ASC, START_INDEX, statusBar, Flash, isset,
	check, checkSuccess, startTab, updateEncoding, updateWaveforms, CheckProgress */
START_ASC = true;
START_INDEX = 0;

var ProfileBit = new Class({
	initialize: function () {
		this.delUrl = Constants.ajax()+'delComment';
		this.defaultComment = 'post a note ...';
		this.comment = $('newnote');
		this.selectedTabs = [];
		this.pinUnpin = $('pin_unpin');
		this.pinImg = Constants.images()+'mbitIcons/pin.gif';
		this.unpinImg = Constants.images()+'mbitIcons/unpin.gif';
		this.pinMsg = 'Pin This';
		this.unpinMsg = 'Un-pin This';
		this.deleteLink = $('deleteLink');
		if (this.pinUnpin) { this.pinUnpin.addClick(this.doPinUnpin.bind(this)); }

//		this.deleteComment();

		// get the ID from the URL query string
		var url = document.URL, c,
			matches = url.match(/id=([^&]{32})/);	// profile link like: profile?id=ID
		if (!matches) { matches = url.match(/~([^&]{32})/); }		// profile link like: profiles/~ID
		this.id = matches && matches.length === 2 ? matches[1] : -1;
		if (this.deleteLink) {
			this.deleteLink.setClick(
				function () {
					var txt = 'Are you sure you want to delete this stem? This cannot be undone.\n';
					txt += 'If you only want to replace your music file or change the title, click Cancel and then click the "edit stem" link below';
					return window.confirm(txt);
				}
			);
		}
		c = new CheckProgress(this.id);
		
		if (this.id) {
			var play = $('play'), _playing = false,
				playerName = 'smallPlayerHidden',
				playPause = function (e, pause) {
					var src = Constants.images() + (_playing ? 'mbitIcons/play.gif' : (!!pause ? 'mbitIcons/pause.gif' : 'mbitIcons/stop.gif')),
						alt = _playing ? 'Play' : (!!pause ? 'Pause' : 'Stop');
					play.attrib('src', src).attrib('alt', alt).attrib('title', alt);
					if (_playing) { Flash.stop(playerName); }
					else { Flash.play(playerName); }
					if (_playing && !pause) {
						Flash.update(playerName);
						Flash.update(playerName, this.id);
					}
					_playing = !_playing;
				};
			if (play) {
				Flash.changePlayer(playerName);
				Flash.update(playerName, this.id);
				play.setClick(playPause.bind(this));
			}
		}
	},
	deleteComment: function () {
		var i, delLinks = $('comments').getElementsByClassName('delComment', 'a');
		for (i=0; i<delLinks.length; ++i) {
			this.addDeleteEvents($$(delLinks[i]));
		}
	},
	initCommentBox: function () {
		var postnew = $('postnewcomment'), me = this;
		if (postnew) { postnew.addClick(this.saveComments.bind(this)); }
		
		if (this.comment) {
			this.comment.value = this.defaultComment;
			this.comment.addEvent('focus', function () { me.clearThis(); });
			this.comment.addEvent('blur', function () { me.fillThis(); });
		}
	},
	addTabNavigation: function (div){
		if (div.id) {
			this.selectedTabs[div.id] = -1;
			var tabHeaders = div.getChildNodes();
			for (var 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 (isset(typeof(startTab)))	{ this.switchTab(div,startTab); }
		}
	},

	// Attach the clickable javascript to the tab header
	attachTabLink: function (div, tabHeader, tabIndex){
		var me = this;
		tabHeader.addClick(me.switchTab.bind(me, div, tabIndex));
	},

// 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.removeClassName("curTab");
							oldTab.hide();
						}
					}
					if ( j === tabIndex ) {
						tabHeaders[i].addClassName('currentTab');
						var newTab = $(div.id + '_' + tabIndex);
						if (newTab) {
							// newTab.addClassName("curTab");
							newTab.show();
						}
					}
					++j;
				}
			}
			this.selectedTabs[div.id] = tabIndex;
		}
	},
	addDeleteEvents: function (el) {
		var me = this;
		el.addClick(me.delCom.bind(me, el.id));
	},
	
	delCom: function (commentid) {
		if (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 = $('newnote');
		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,
				url = Constants.ajax()+'saveComments',
				subjectid = $('subjectid'),
				pars = 'comment_txt=' + encodeURIComponent(txt.value) + '&subjid=' + encodeURIComponent(subjectid.value),
				myAjax = new Ajax(
				url,
				{	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); }
		return; /*
		var response = JSON.parse(request.responseText),
			all_comments = $('comments'),

			new_comment_div = document.create('div', 'c_'+response.commentid, 'comment clearfix'),
			new_comment_body_div = new_comment_div.create('div', null, 'usercomment'),

			new_comment_header_div = new_comment_body_div.create('div', null, 'commenthead'),
			new_who_span = new_comment_header_div.create('span', null, 'who'),
			new_when_span = new_comment_header_div.create('span', null, 'when darkgray', response.date),
			new_profile_link = new_who_span.create('a').update(response.username+' - ');

		new_profile_link.setAttribute('href', Constants.profileLink(response.uid));

		var new_text = new_comment_body_div.create('p', null, 'darkgray', response.commenttxt),

			new_user_pic_div = new_comment_div.create('div', null, 'userpic'),
			new_user_pic_img = new_user_pic_div.create('img');
		new_user_pic_img.setAttribute('alt', response.username+'\'s picture');
		new_user_pic_img.setAttribute('title', response.username+'\'s picture');
		new_user_pic_img.setAttribute('src', Constants.profilePic(response.uid, 'thumb'));

		var new_comment_footer_div = new_comment_div.create('div', null, 'commentfoot'),
			new_footer_bar_p = new_comment_footer_div.create('p'),

			new_reply_link_span = new_footer_bar_p.create('span', null, 'commentlinks'),
			new_reply_link = new_reply_link_span.create('a').update('reply on '+response.username+'\'s board&nbsp;\/');
		new_reply_link.setAttribute('href', Constants.profileLink(response.uid)+'#commentboard');
		
		var new_message_link_span = new_footer_bar_p.create('span', null, 'commentlinks'),
			new_message_link = new_message_link_span.create('a').update('reply privately&nbsp;\/');
		new_message_link.setAttribute('href', 'mmmail?mode=n&rid='+response.uid);
		
		var new_delete_link_span = new_footer_bar_p.create('span', null, 'commentlinks'),
			new_delete_link = new_delete_link_span.create('a', response.commentid, 'delComment', 'delete');
		this.addDeleteEvents(new_delete_link);

		all_comments.insertBefore(new_comment_div, all_comments.firstChild);
		*/
	},
	//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; }
	},
	doPinUnpin: function () {
		var curMsg = this.pinUnpin.getAttribute('alt');
		
		if (curMsg === this.pinMsg) { this.pin(this.id); }
		else { this.unPin(this.id); }
	},
	preload: function () {
		var pinImgTmp = new Image();
		pinImgTmp.src = this.pinImg;
		var unpinImgTmp = new Image();
		unpinImgTmp.src = this.unpinImg;
	},
	pin: function (id) {
		var pars = "f=a&id=" + id, me = this,
			pinAjax = new Ajax( Constants.ajax()+'tag', 
			{	method: 'get',
				parameters: pars,
				onSuccess: function (request) { me.checkPin(request, true); },
				onFailure: function () { statusBar.error('Pinning failed. Please try again.'); }
			});
		pinAjax.send();
	},
	unPin: function (id) {
		var pars = "f=r&id=" + id, me = this,
			pinAjax = new Ajax( Constants.ajax()+'tag',
			{	method: 'get', 
				parameters: pars,
				onSuccess: function (request) { me.checkPin(request, false); },
				onFailure: function () { statusBar.error('Removing failed. Please try again.'); }
			});
		pinAjax.send();
	},
	checkPin: function (request, add) {
		var response = JSON.parse(request.responseText), msg, error = false;
		if (add && response.status === 1) {
			msg = "Added to your palette.";
			this.pinUnpin.src = this.unpinImg;
			this.pinUnpin.setAttribute('alt', this.unpinMsg);
			this.pinUnpin.setAttribute('title', this.unpinMsg);
		} else if (add && response.status === 2) {
			msg = "This is already in your palette.";
		} else if (!add && response.status === 1) {
			msg = "Removed from your palette.";
			this.pinUnpin.src = this.pinImg;
			this.pinUnpin.setAttribute('alt', this.pinMsg);
			this.pinUnpin.setAttribute('title', this.pinMsg);
		} else if (!add) {
			msg = "Failed to remove from your palette";
			error = true;
		} else if (add) {
			msg = "Failed to add to your palette.";
			error = true;
		} else {
			msg = "Unknown error.";
			error = true;
		}
		if (error) { statusBar.error(msg); }
		else { statusBar.talk(msg); }
	}
});

var CheckProgress = function (id) {
	var encoding, waveforms, mbitProgress,
		url = Constants.ajax()+"inprogress", interval, params,
		encodingInterval, waveformsInterval, encodingCnt=0, waveformsCnt=0, encodingMsg = 'Encoding in progress',
		waveformsMsg = 'Waveform processing in progress';

	function check() {
		var ajax = new Ajax(url,params);
		ajax.send(); 
	}
	function checkSuccess(result) {
		if (result.responseText) {
			var res = JSON.parse(result.responseText);
			if (res.encoding) {
				if (!encoding) {
					// create the encoding message
					encoding = mbitProgress.create("div", null, 'inProgress', encodingMsg);
					encodingInterval = setInterval(updateEncoding, 0.5*1000);
				}
			} else {
				if (encoding) {
					clearInterval(encodingInterval);
					encoding.remove();
				}
			}
			if (res.waveforms) {
				if (!waveforms) {
					// create the encoding message
					waveforms = mbitProgress.create("div", null, 'inProgress', waveformsMsg);
					waveformsInterval = setInterval(updateWaveforms, 0.5*1000);
				}
			} else {
				if (waveforms) {
					clearInterval(waveformsInterval);
					waveforms.remove();
				}
			}
			if (!res.encoding && !res.waveforms) {
				clearInterval(interval);
			}
		}
	}
	function getDots(cnt) {
		var dots;
		switch (cnt%4) {
			case 0: dots=''; break;
			case 1: dots='.'; break;
			case 2: dots='..'; break;
			case 3: dots='...'; break;
		}
		return dots;
	}
	function updateEncoding() {
		encodingCnt++;
		encoding.update(encodingMsg+getDots(encodingCnt));
	}
	function updateWaveforms() {
		waveformsCnt++;
		waveforms.update(waveformsMsg+getDots(waveformsCnt));
	}
	function setup() {
		mbitProgress = $('mbitProgress');
		params = {method:'get', onSuccess: checkSuccess, parameters: 'id='+id};
		check();
		interval = setInterval(check, 5*1000);
	}
	setup();
};
