/*globals $, $$, Constants, Class, Ajax, makeFakeLink, mmmAttachSubmitHoverEvents, Flash */
var ua = navigator.userAgent.toLowerCase(),
	isIE = (/msie/.test(ua)) && !(/opera/.test(ua)) && (/win/.test(ua)),

	Modifications = new Class({
	initialize: function() {
		// Page level elements
		this.holder = $('modificationHolder');
		if (this.holder) {
			this.links = {
				attribution: $('modAttribution'), genre: $('modGenre'),
				instrument: $('modInstrument'), keys: $('modKey'),
				tempo: $('modTempo'), component: $('modSongComp'),
				effect: $('modEffects'), soundslike: $('modSoundsLike'),
				tags: $('modTags')
			};
			this.id = $('mbit_id').value;

			this.holders = {
				attribution: $('modAttributionHolder'), genre: $('modGenreHolder'),
				instrument: $('modInstrumentHolder'), keys: $('modKeyHolder'),
				tempo: $('modTempoHolder'), component: $('modSongComponentHolder'),
				effect: $('modEffectHolder'), soundslike: $('modSoundsLikeHolder'),
				tags: $('modTagsHolder')
			};
			
			// Private vars
			this._selected = null;
			this._newRule = null;
			this._blurSelector = ".field, .data, .infoHeader, #maybeLegend";
			this._blurDeclaration = "filter:alpha(opacity=20); -moz-opacity: 0.2; opacity: 0.2;";
			this._blurDeclarationIE = "visibility:hidden;";
			this._defaultCommentText = "click here to post a comment about your modification...";
			this._url = Constants.ajax() + "modifications";
			this._content = {};
			this.cssLoaded = false;
			
			var me = this;
			makeFakeLink(this.links.attribution, me.showAttribution.bind(me));
			makeFakeLink(this.links.genre, me.showGenre.bind(me));
			makeFakeLink(this.links.instrument, me.showInstrument.bind(me));
			makeFakeLink(this.links.keys, me.showKey.bind(me));
			makeFakeLink(this.links.tempo, me.showTempo.bind(me));
			makeFakeLink(this.links.component, me.showSongComp.bind(me));
			makeFakeLink(this.links.effect, me.showEffects.bind(me));
			makeFakeLink(this.links.soundslike, me.showSoundsLike.bind(me));
			makeFakeLink(this.links.tags, me.showTags.bind(me));
		}
	},
	updateContent: function(request, type) {
		if (request.responseText !== "") {
			this.holders[type].loaded = true;
			this.holders[type].update(request.responseText);
			this.setupContent(type);
			if (this.holders[type].jsLoaded) { eval(this.holders[type].js); }
		}
	},
	executeJS: function(request, type) {
		if (request.responseText !== "") {
			if (this.holders[type].loaded) {
				eval(request.responseText);
			} else {
				this.holders[type].jsLoaded = true;
				this.holders[type].js = request.responseText;
			}
		}
	},
	setupContent: function(type) {
		var me = this;
		
		this.submit = $(type + 'ModSubmit');
		this.submit2 = $(type + 'ModSubmit2');
		this.cancel = $(type + 'ModCancel');
		this.cancel2 = $(type + 'ModCancel2');
		this.cancel.addClick(me._hideBox.bind(me));
		if (this.cancel2) {
			this.cancel2.addClick(me._hideBox.bind(me));
		}
		this.check = $(type + 'ModCheck');
		this.check2 = $(type + 'ModCheck2');
		
		this.modTab = $(type + 'ModTab');
		this.discTab = $(type + 'DiscTab');
		this.historyTab = $(type + 'HistoryTab');
		this.modBox = $(type + 'ModBox');
		this.discBox = $(type + 'DiscBox');
		this.historyBox = $(type + 'HistoryBox');
		
		//this.modComment = $('modComment');
		//this.modComment2 = $('modComment2');
		this.modPost = $(type + 'ModPost');
		
		if (this.check) {
			this.check.addClick(me._handleCheck.bind(me, 1));
		}
		if (this.check2) {
			this.check2.addClick(me._handleCheck.bind(me, 2));
		}
		this.modTab.addClick(me._switchTab.bind(me, 'mod'));
		this.discTab.addClick(me._switchTab.bind(me, 'disc'));
		this.historyTab.addClick(me._switchTab.bind(me, 'history'));
		//this._setupComment(this.modComment);
		//this._setupComment(this.modComment2);
		this._setupComment(this.modPost, "comments:");
		
		mmmAttachSubmitHoverEvents($(type + 'ModSubmit'));
		if ($(type + 'ModSubmit2')) {
			mmmAttachSubmitHoverEvents($(type + 'ModSubmit2'));
		}
		mmmAttachSubmitHoverEvents(this.cancel);
		if (this.cancel2) {
			mmmAttachSubmitHoverEvents(this.cancel2);
		}
	},
	getContent: function(type) {
		if (this.holders[type].loaded) {
			this.holders[type].show();
			this.setupContent(type);
		} else {
			var pars = "id=" + this.id + "&type=" + type,
				me = this;
			this._ajax = new Ajax(
				this._url, 
				{	method: 'get', 
					parameters: pars,
					onSuccess: function(request) { me.updateContent.bind(me,request,type)(); },
					onFailure: function(request) { statusBar.error('failed'); }
				});
			this._ajax.send();
			
			pars += "&js=1";
			
			this._ajax = new Ajax(
				this._url, 
				{	method: 'get', 
					parameters: pars,
					onSuccess: function(request) { me.executeJS.bind(me,request,type)(); },
					onFailure: function(request) { statusBar.error('failed'); }
				});
			this._ajax.send();
		}
	},
	showAttribution: function() { this._showBox('attribution'); },
	showGenre: function() 		{ this._showBox('genre'); },
	showInstrument: function() 	{ this._showBox('instrument'); },
	showKey: function() 		{ this._showBox('keys'); },
	showTempo: function() 		{ this._showBox('tempo'); },
	showSongComp: function() 	{ this._showBox('component'); },
	showEffects: function() 	{ this._showBox('effect'); },
	showSoundsLike: function() 	{ this._showBox('soundslike'); },
	showTags: function() 		{ this._showBox('tags'); },
	_showBox: function(type) {
		Flash.stop('smallPlayerMod');
		if (this._selected != type) {
			if (!this.cssLoaded) {
				this.cssLoaded = true;
				var l = document.create("link");
				l.setAttribute("type","text/css");
				l.setAttribute("rel","stylesheet");
				l.setAttribute("href",Constants.css()+"modifications.css");
				l.setAttribute("media","screen");
				document.getElementsByTagName("head")[0].appendChild(l);
			}
			this.holder.show();
			this.getContent(type);
			if (this._selected) {
				this.holders[this._selected].hide();
			}
			this.holders[type].show();
			if (!this._selected) {
				this._newRule = createCSS(this._blurSelector, this._blurDeclaration, this._blurDeclarationIE);
			}
			this._selectMod(type);
		} else {
			this._hideBox();
		}
	},
	_hideBox: function() {
		Flash.stop('smallPlayerMod');
		this.holder.hide();
		if (this._selected) {
			this.links[this._selected].removeClassName('selected');
			this.holders[this._selected].hide();
			this._selected = null;
		}
		if (this._newRule) {
			this._newRule.parentNode.removeChild(this._newRule);
			this._newRule = null;
		}
	},
	_selectMod: function(type) {
		if (this._selected != type) {
			this.links[type].addClassName('selected');
			if (this._selected) {
				this.links[this._selected].removeClassName('selected');
			}
			this._selected = type;
		}
	},
	_switchTab: function(tab) {
		if (tab == 'disc') {
			this.modBox.hide();
			this.discBox.show();
			this.historyBox.hide();
			this.modTab.removeClassName('selectedTab');
			this.discTab.addClassName('selectedTab');
			this.historyTab.removeClassName('selectedTab');
		} else if (tab == 'history') {
			this.modBox.hide();
			this.discBox.hide();
			this.historyBox.show();
			this.modTab.removeClassName('selectedTab');
			this.discTab.removeClassName('selectedTab');
			this.historyTab.addClassName('selectedTab');
		} else {
			// default tab is mod tab
			this.modBox.show();
			this.discBox.hide();
			this.historyBox.hide();
			this.modTab.addClassName('selectedTab');
			this.discTab.removeClassName('selectedTab');
			this.historyTab.removeClassName('selectedTab');
		}
	},
	_setupComment: function(commentBox, txt) {
		if (commentBox) {
			if (txt === null) {
				txt = this._defaultCommentText;
			}
			var me = this;
			commentBox.addEvent('focus', me._checkComment.bind(me, commentBox, 'focus', txt));
			commentBox.addEvent('blur', me._checkComment.bind(me, commentBox, 'blur', txt));
			if (commentBox.value === "") {
				commentBox.update(txt);
			}
		}
	},
	_checkComment: function(commentBox, action, txt) {
		var val = commentBox.value;
		if (action == 'blur') {
			if (val === "") {
				commentBox.update(txt);
			}
		} else {
			// default action is focus
			if (val == txt) { commentBox.empty(); }
		}
	},
	_handleCheck: function(num) {
		var submit, check;
		if (num == 1) {
			submit = this.submit;
			check = this.check;
		} else {
			submit = this.submit2;
			check = this.check2;
		}
		submit.disabled = !check.checked;
		if (submit.disabled) {
			submit.addClassName('disabled');
		} else {
			submit.removeClassName('disabled');
		}
	}
});
		
/* NOTE: the following code was extracted from the UFO source and extensively reworked/simplified */
/* Unobtrusive Flash Objects (UFO) v3.20 <http://www.bobbyvandersluis.com/ufo/>
        Copyright 2005, 2006 Bobby van der Sluis
        This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
*/
function createCSS(selector, declaration, declarationIE) {
        // create the style node for all browsers
        var style_node = document.create("style");
        style_node.setAttribute("type", "text/css");
        style_node.setAttribute("media", "screen");

        // append a rule for good browsers
        if (!isIE) { style_node.createText(selector + " {" + declaration + "}"); }

		// append the style node
        document.getElementsByTagName("head")[0].appendChild(style_node);

        // use alternative methods for IE
        if (isIE && document.styleSheets && document.styleSheets.length > 0) {
                var last_style_node = document.styleSheets[document.styleSheets.length - 1];
                if (typeof(last_style_node.addRule) == "object") {
					var fields = selector.split(",");
					for (var i=0; i<fields.length; i++) {
						last_style_node.addRule(fields[i].trim(), declaration);
						last_style_node.addRule(fields[i].trim(), declarationIE);
					}
				}
        }
		return style_node;
}
window.addLoad(function() {var m = new Modifications();});