/**
 * @author	  Bas Scholts
 * @since	   10-dec-2010 11:43:45
 */

function log(message)					{ Global.log(0, message); }
function info(message)					{ Global.log(1, message); }
function warn(message)					{ Global.log(2, message); }
function error(message)					{ Global.log(3, message); }

var Global = {
	start:function() {
		Element.implement({
			'hClass': function(className) {
				if (!this.getAttribute('class'))
					return false;
				if (this.getAttribute('class') == '')
					return false;
				return this.hasClass(className);
			},
			'show': function() { this.setStyle('display',''); },
			'hide': function() { this.setStyle('display','none'); }
		});

		if (rruDomains)
		{
			this.siteDomain		= rruDomains.site;
			this.assetDomain	= rruDomains.assets;
			this.jsonDomain		= rruDomains.json;
			this.staticDomain	= rruDomains.static;
		}
		if ($(document.body).hClass('forum') || (document.id('forum') && document.id('forum').tagName.toLowerCase() == 'body'))
			Forum.start();
		else
			Site.start();

		if (document.id('header-images'))
			HeaderRotation.initialize();
	},
	log: function(severity, message)
	{
		if (!window.console || console.firebug)
			return;
		switch (severity)
		{
			case 3:	console.error(message);	break;
			case 2:	console.warn(message);	break;
			case 1:	console.info(message);	break;
			case 0:	console.log(message);	break;
		}
	},
	getSiteDomain: function() { return this.siteDomain; },
	getAssetDomain: function() { return this.assetDomain; },
	getJsonDomain: function() { return this.jsonDomain; },
	getStaticDomain: function() { return this.staticDomain; }
};
var Site = {
	start: function() {
		if ($$('.tabContainer').length > 0)
			$$('.tabContainer').each(function(tl){return new Tablist(tl);});
		if (document.id('memberList'))
		{
			$$('#memberList .list .memberInfo').each(function(ri){
				return;
				var rt	= ri.getNext('.memberTitle');
				ri.addEvents({'mouseover':function(){rt.addClass('hover');},'mouseout':function(){rt.removeClass('hover');}});
				rt.addEvents({'mouseover':function(){ri.addClass('hover');},'mouseout':function(){ri.removeClass('hover');}});
			});
		}
		if (document.id('reputationProgress'))
		{
			$$('#reputationProgress table tr').each(function (tr){
				var curTd	= tr.getFirst('td');
				var nextTd	= curTd.getNext('td') || false;
				while (nextTd)
				{
					if (!nextTd)
						break;
					if (nextTd.hasClass('achieved') || nextTd.hasClass('not-available'))
						curTd.addClass('bgColour');
					curTd	= nextTd;
					nextTd	= curTd.getNext('td') || false;
				}
			});
		}
	}
};
var Forum = {
	start: function() {
		if (Browser.ie8 || Browser.ie7 || Browser.ie6)
			this.ieDisplayFix();
		document.getElements('.postContainer .postBody').each(function(pb){
			if (!pb.getFirst('.message'))
				return;
			var m	= pb.getFirst('.message');
			if (m.getHeight() > pb.getFirst('.postUserMeta')) { return; }
			var sigHeight	= pb.getHeight();
			if (m.getFirst('.messageBody'))		{ sigHeight	= sigHeight - m.getFirst('.messageBody').getHeight(); }
			if (m.getFirst('.messageTitle'))	{ sigHeight	= sigHeight - m.getFirst('.messageTitle').getHeight(); }
			if (m.getFirst('.postedited'))		{ sigHeight	= sigHeight - m.getFirst('.postedited').getHeight(); }
			if (m.getFirst('.signature'))
				m.getFirst('.signature').setStyle('height', sigHeight+'px');
			//m.setStyle('height', (pb.getHeight()-5)+'px');
		});

		if (document.id('newReply') || document.id('newPost'))
			this.resizeTextarea();
		if (document.id('vB_Editor_QR_iframe'))
			document.id('vB_Editor_QR_iframe').setStyle('border',false);
	},
	resizeTextarea: function()
	{
		var textArea	= document.id('vbEditorContainer').getFirst('textarea');
		var editorId	= textArea.get('id').replace('_textarea', '');
		if (document.id('vbEditorContainer').getFirst('iframe'))
		{
			var editorTarget	= document.id(editorId+'_iframe');
			editorTarget.setStyles({
				'width':	document.id('vbEditorContainer').getWidth() - 10,
				'height':	250
			});
		}
		else
		{
			var editorTarget	= document.id(editorId+'_textarea');
		}
		document.id(editorId+'_cmd_resize_0_99').addEvent('click', function(e){
			e.stopPropagation();
			var height	= editorTarget.getHeight();
			if (height - 100 > 250)
				editorTarget.setStyle('rows', height - 100);
			else
				editorTarget.setStyle('height', 250);
		});
		document.id(editorId+'_cmd_resize_1_99').addEvent('click', function(e){
			e.stopPropagation();
			var height	= editorTarget.getHeight();
			editorTarget.setStyle('height', height + 100);
		});
	},
	ieDisplayFix: function() {
		if (document.id('navBar'))
		{
			var navBar = document.id('navBar').getFirst('ul');
			navBar.getFirst('li').addClass('firstChild');
			navBar.getLast('li').addClass('lastChild');
		}
		if (document.id('footerButtons'))
			document.id('footerButtons').getLast('li').addClass('lastChild');
		if (Browser.ie7 || Browser.ie6)
			$$('table').each(function(t){t.set('cellspacing', 0);});
		$$('#quickSearch .radio').each(function(e){e.setStyle('box-shadow', false);});
	}
};
var HeaderRotation = {
	initialize: function()
	{
		this.rotateDelay	= 15000;
		this.rotateDuration	= this.rotateDelay / 10;
		this.rotateActive	= 0;
		this.headers		= document.id('header-images').getChildren('img');
		if (this.headers.length > 1)
		{
			$$('#header-images img').each(function(img, idx){
				if (!Browser.ie7)
					img.setStyles({'opacity':(img.hClass('active') ? 1 : 0)}).set('tween', {duration: this.rotateDuration});
			}.bind(this));
			this.rotateHeader.periodical(this.rotateDelay, this);
		}
	},
	rotateHeader: function()
	{
		nImg = (this.rotateActive + 1 >= this.headers.length) ? 0 : this.rotateActive + 1;
		if (Browser.ie7)
		{
			this.headers[this.rotateActive].toggleClass('active');
			this.headers[nImg].toggleClass('active');
		}
		else
		{
			this.headers[this.rotateActive].tween('opacity', 0);
			this.headers[nImg].tween('opacity',1);
		}
		this.rotateActive = nImg;
	}
};
var Tablist = new Class({
	initialize: function(obj, windowSelector)
	{
		if (typeof windowSelector == 'undefined')
			windowSelector	= '.tabContent';
		this.tabContainer	= obj;
		this.tabs			= this.tabContainer.getFirst('.tabList').getChildren('li');
		this.windows		= this.tabContainer.getChildren(windowSelector);
		this.activeTab		= 0;
		this.hash			= window.location.hash.substring(1);
		this.tabs.each(function(t,ti) {
			var	ta	= t.getFirst('a');
			t.store('pagename', ta.get('href').substring(5));
			if (this.hash == ta.get('href').substring(1)) { this.activeTab	= ti; }
			ta.addEvent('click', function(e) { this.setActive(t, false); return false; }.bind(this));
		}.bind(this));
		this.setActive(this.tabs[this.activeTab], true);
		this.tabContainer.store('tablist', this);
	},
	setActive: function(tab, load)
	{
		if (!load)
			window.location.hash = tab.getFirst('a').get('href').substring(1);
		this.tabs.each(function(t){t.removeClass('active');});
		this.windows.each(function(w){w.removeClass('active');});
		document.id('tabpage-'+tab.addClass('active').retrieve('pagename')).addClass('active');
	}
});

var CharacterEdit = {
	initialize: function()
	{
		if (!document.id('characterEdit'))
			alert('Error: Character edit form could not be found, fancy features not available.');
		this.form				= document.id('characterEdit');
		this.vocationSelect		= document.id('character-vocationid');
		this.professionLabel	= document.id('professions-label');
		this.professionStatus	= document.id('professions-status');
		this.pStatusDefault		= this.professionStatus.get('text');
		this.professionFields	= this.professionStatus.getParent().getChildren('dt.profession');
		if (this.professionFields.length == 0)
			this.createProfessionFields();
		this.vocationSelect.addEvent('change', this.requestVocation.bind(this));
		this.professionStatus.set('tween', {duration:'long'});

		this.guildLabel			= document.id('craftingguild-status');
		this.guildSelector		= document.id('character-craftingfactionid');
		this.guildStandingDummy	= document.id('character-factionstanding-dummy');
		this.guildSelector.addEvent('change', this.handleGuildSelection.bind(this));

		this.biographyText		= document.id('character-biography');
		this.biographyHtmlBar	= document.id('biography-htmlbar');
		this.biographyHtmlBar.getChildren('a').each(function(a){
			a.addEvent('click', function(){ this.insertBiographyHtml(a.get('id')); return false; }.bind(this));
		}.bind(this));
		this.form.addEvent('submit', function(){
			this.biographyText.tidy();
		}.bind(this));

		if (document.id('character-radiance'))
			this.initRadiancePicker(180, 5);
	},
	initRadiancePicker: function(max, step)
	{
		this.radianceField		= document.id('character-radiance');
		var options				= [];
		for (var i = 0; i <= max; i += step)
			options.push(i);
		var barWidth			= 300;
		var knobWidth			= 16;
		var numSteps			= options.length;
		var areaWidth			= (Math.ceil(barWidth/numSteps - knobWidth/numSteps) * numSteps) + knobWidth;
		this.radianceField.addClass('usingSlider');
		this.sliderContainer	= new Element('div', {'id':'radianceSlider'}).inject(this.radianceField, 'after');
		this.sliderContainer.setStyle('width', areaWidth);
		this.sliderBar			= new Element('div', {'id':'radianceSliderBar'}).inject(this.sliderContainer);
		this.sliderBar.setStyle('width', areaWidth);
		this.sliderKnob			= new Element('img', {'id':'radianceSliderKnob', 'src':'/static/images/icons/ruby.png', 'alt':'V'}).inject(this.sliderContainer);
		this.slider				= new Slider(this.sliderBar, this.sliderKnob, {
			snap		: true,
			wheel		: true,
			range		: [0, max / 5],
			initialStep	: Math.ceil(this.radianceField.get('value') / 5),
			onChange	: function(curStep) { this.radianceField.set('value', curStep * 5); }.bind(this)
		});
		this.radianceField.addEvent('blur',function(){this.slider.set(Math.ceil(this.radianceField.get('value') / 5));}.bind(this));
	},
	insertBiographyHtml: function(codeId)
	{
		codeId			= codeId.substring(5);
		var startTag	= '';
		var endTag		= '';
		switch (codeId)
		{
			case 'strong':
			case 'emphasis':
			case 'underline':
			case 'cite':
			case 'blockquote':
				startTag	= '<'+codeId+'>';
				endTag		= '</'+codeId+'>';
				break;
			case 'abbr':
				var title	= prompt('Meaning of this abbreviation?');
			case 'acronym':
				if (typeof title == 'undefined')
					var title	= prompt('Meaning of this acronym?');
				startTag	= '<'+codeId+' title="'+title+'">';
				endTag		= '</'+codeId+'>';
				break;
		}
		if (startTag != '' && endTag != '')
			this.biographyText.insertAroundCursor({'before': startTag, 'after': endTag, 'defaultMiddle': 'text'});
	},
	createProfessionFields: function()
	{
		var dt	= document.id('profession-dummy-dt'); //dt.dispose();
		var dd	= document.id('profession-dummy-dd');// dd.dispose();
		for (var i = 0; i < 3; i++)
		{
			dd.clone().inject(this.professionLabel, 'after').addClass('profession');
			dt.clone().inject(this.professionLabel, 'after').addClass('profession');
		}
		this.professionFields	= this.professionLabel.getParent().getChildren('dt.profession');
	},
	requestVocation: function()
	{
		var value	= this.vocationSelect.getSelected()[0].get('value').toInt();
		if (value == 0)
		{
			this.professionLabel.addClass('hidden');
			this.professionStatus.removeClass('hidden').set({'text':this.pStatusDefault, 'style':false});
			this.professionFields.each(function(dt){ dt.addClass('hidden').getNext('dd').addClass('hidden'); });
			return;
		}
		this.request	= new Request.JSON({
			method:		'get',
			url:		Global.getJsonDomain()+'my/character',
			link:		'cancel',
			onRequest:	function() {
				this.professionLabel.addClass('hidden');
				this.updateStatus('Retrieving professions for this vocation, please wait...', false);
				this.professionFields.each(function(dt){
					dt.addClass('hidden').getNext('dd').addClass('hidden');
				});
			}.bind(this),
			onFailure:	function(r) {
				this.professionLabel.addClass('hidden');
				this.updateStatus('Unable to retrieve professions', true);
				this.updateVocation();
			}.bind(this),
			onSuccess:	function(r) {
				this.updateVocation(r);
				this.professionStatus.addClass('hidden');
				this.professionLabel.removeClass('hidden');
			}.bind(this)
		}).send('a=getvocation&vocation='+this.vocationSelect.getSelected()[0].get('value'));
	},
	updateStatus: function(txt, error)
	{
		if (this.professionStatus.hasClass('hidden'))
		{
			this.professionStatus.removeClass('hidden');
			this.professionLabel.addClass('hidden');
		}
		if (!this.fx)
		{
			this.fx	= new Fx.Tween(this.professionStatus, {
				duration:'normal',
				link:'cancel',
				onComplete:function(a){
					this.professionStatus.setStyle.delay(1000, this.professionStatus, ['color','']);
					this.professionStatus.tween.delay(500, this.professionStatus, ['background-color','#FFFFDD']);
				}.bind(this)
			});
		}
		if (typeof error == 'boolean' && error === true)
			this.professionStatus.addClass('error');
		else
			this.professionStatus.removeClass('error');
		this.professionStatus.set('text', txt);
		this.fx.start('background-color','#EEEEEE','#FFFFDD').set('color','#000000');
	},
	updateVocation: function(r)
	{
		c	= 0;
		Object.each(r.data.p, function(lbl, i) {
			var dd	= this.professionFields[c].getNext('dd');
			this.professionFields[c].set('text', lbl).removeClass('hidden');
			dd.getFirst('.proficiency').set('name', 'craftingproficiency['+i+'][proficient]').set('disabled',false);
			dd.getFirst('.mastery').set('name', 'craftingproficiency['+i+'][master]').set('disabled',false);
			dd.removeClass('hidden');
			c++;
		}, this);
		this.guildSelector.empty().adopt(new Element('option',{value:'-1',text:'No guild',selected:'selected'}));
		Object.each(r.data.g, function(guild, i) {
			this.guildSelector.adopt(new Element('option',{value:i,text:guild.name}));
			var sel		= this.guildStandingDummy.clone();
			sel.set({'name':'character-factionstanding['+i+']',	'id':'character-factionstanding-'+i	});
			sel.inject(this.guildStandingDummy, 'before');
			var selC	= sel.getChildren().filter(function(o) { return !guild.standings.contains(o.get('value')); });
			Object.each(selC, function(o){ if (typeof o == 'HTMLOptionElement') o.dispose(); });
		}, this);
		this.handleGuildSelection();
	},
	handleGuildSelection: function()
	{
		$$('.guildrep').each(function(s){
			s.setProperty('selectedIndex', 0);
			s.getChildren('option').each(function(o){o.setProperty('selected', false);});
			s.addClass('hidden').set('disabled','disabled');
		});
		var factionId	= this.guildSelector.getSelected()[0].get('value');
		if (factionId.toInt() > 0)
			$('character-factionstanding-'+factionId).removeClass('hidden').set('disabled',false);
	}
};

if (!Browser.ie7)
	window.addEvent('domready', function(){ Global.start(); });
else
	window.onload = function(){ Global.start(); };
