var Ambience = Class.create({
	initialize : function(id) {
		// The ajax object
		this.ajax		= new Object();
		
		// Init values
		this.rating		= false;
		this.rated		= false;
		this.commenting	= false;
		this.loading	= false;
		
		// Init i18n values
		this.i18n						= [];
		this.i18n['lang']				= '';
		this.i18n['path']				= '';
		this.i18n['downloadLink']		= '';
		this.i18n['permaLink']			= '';
		this.i18n['msg_sending_evaluation']	= '';
		this.i18n['msg_sending_comment']	= '';
		this.i18n['msg_loading_ambience']	= '';
		this.i18n['msg_buffering']		= '';
		this.i18n['msg_post_comment']	= '';
		this.i18n['label_nick']			= '';
		this.i18n['label_email']		= '';
		this.i18n['label_message']		= '';
		this.i18n['label_captcha']		= '';
		this.i18n['label_post_comment']	= '';
		this.i18n['btn_send']			= '';
		this.i18n['btn_cancel']			= '';
		this.i18n['btn_close']			= '';
		this.i18n['by']					= '';
		this.i18n['title']				= '';
		this.i18n['copyBtn']			= '';
		
		// Remove the comments stuff
		$('commentForm').hide();
		$('comments').hide();
		
		// Init ambiences selection listeners
		this.initAmbiencesListeners();
		
		// Load the ambience
		setTimeout(this.load.bind(this),0);
	},
	
	load : function() {
		var ambienceId = parseInt(unescape(self.document.location.hash.substring(1)).split('-', 1));
		if (ambienceId > 0) {
			this.onLoadAmbienceClick(ambienceId);
			
			// Init the listeners
			this.initListeners();
		}
	},
	
	initListeners : function() {
		// Add event on the AddComment link
		$('addCommentLink').stopObserving('click');
		$('addCommentLink').observe('click', this.onCommentClick.bind(this));
		$('addCommentLink').href = 'javascript:void(0);';
		
		// Add listeners on the rating links
		for(var i=1; i<=5; i++) {
			$('eval'+i).stopObserving('click');
			$('eval'+i).stopObserving('mouseover');
			$('eval'+i).stopObserving('mouseout');
			
			$('eval'+i).observe('click', this.onEvaluateClick.bind(this,i));
			$('eval'+i).observe('mouseover', this.onEvaluateMouseover.bind(this,i));
			$('eval'+i).observe('mouseout', this.onEvaluateMouseout.bind(this));
			
			$('eval'+i).href = 'javascript:void(0);';
		}
	},
	
	initAmbiencesListeners : function() {
		// Add listeners on the ambiences links
		var ambienceLinks = document.getElementsByClassName('_ambienceLink');
		for(var i=0; i<ambienceLinks.length; i++) {
			ambienceLinks[i].stopObserving('click');
			ambienceLinks[i].observe('click', this.onLoadAmbienceClick.bind(this,ambienceLinks[i].rel));
			ambienceLinks[i].href = 'javascript:void(0);';
		}
	},
	
	onBuffering : function(n) {
		if (n.substring(0,1) == '2') {
			n = n.substring(2);
			n = parseFloat(n);

			try {
				$('ambienceProgressBar').style.width = Math.round(n*100)+'%';
			} catch(e) {
				
			}
		}
	},

	onStartPlaying : function() {
		this.msg.hide();
	},

	onEvaluateClick : function(rate) {
		if (!this.rating && !this.commenting && !this.rated) {
			var options = {
				method :'post',
				onSuccess : this.onEvaluateSuccess.bind(this),
				onFailure : this.onEvaluateError.bind(this),
				parameters: {ambienceId: this.id, rate: rate, lang : this.i18n['lang']}
			};
			
			this.ajax = new Ajax.Request(
				'../../ajax/evaluateAmbience.php',
				options
			);

			this.msg = new Msg(
				{
					text : '<div>'+this.i18n['msg_sending_evaluation']+'</div><div style="text-align:center;"><img src="../../content/img/loader.gif" /></div>'
				}
			);
			$('msgBox').style.height = '194px';
			$('msg').style.height = '194px';
		}
	},
	
	onEvaluateSuccess : function(transport) {
		this.msg.hide();
		
		var response = transport.responseText.evalJSON() || {};
		switch(response.code) {
			case 0:
				this.msg = new Msg(
					{
						text : response.msgText,
						buttons : [
						   {
							   label : 'OK',
							   type : 'success',
							   action : this.msg.hide.bind(this)
				           }
						]
					}
				);
				this.rated = true;
				
				this.percent = response.percent;
				this.onEvaluateMouseout();
				break;
			
			case 1:
				this.msg = new Msg(
					{
						text : response.msgText,
						type : 'info',
						buttons : [
						   {
							   label : 'OK',
							   action : this.msg.hide.bind(this)
				           }
						]
					}
				);
				break;
			
			case 2:
				this.msg = new Msg(
					{
						text : response.msgText,
						type : 'error',
						buttons : [
						   {
							   label : 'OK',
							   action : this.msg.hide.bind(this)
				           }
						]
					}
				);
				break;
			
			default:
				this.onEvaluateError(transport);
		}
		
		this.rated = true;
		this.rating = false;
		
		// Stop observing the events
		for(var i=1; i<=5; i++) {
			$('eval'+i).stopObserving('click');
			$('eval'+i).stopObserving('mouseover');
			$('eval'+i).stopObserving('mouseout');
		}
		
		this.onEvaluateMouseout();
		
			$('msgBox').style.height = '194px';
			$('msg').style.height = '194px';
	},
	
	onEvaluateError : function(transport) {
		alert('');
	},
	
	onEvaluateMouseover : function(i) {
		$('rating2').style.width = (21*i)+'px';
	},
	
	onEvaluateMouseout : function() {
		$('rating2').style.width = this.percent+'px';
	},

	onCommentClick : function() {
		if (!this.commenting && !this.rating) {
			var buttons		= [];
			buttons.push	= {'label' : 'OK' , 'action' : 'close'};
			
			var options		= {
					'text'		: '<h2>'+this.i18n['msg_post_comment']+'</h2><table class="form" cellspacing="0" cellpadding="0" width="570" style="margin:0;"><tbody><tr><td class="key" width="200px"><label for="commentFormNick">'+this.i18n['label_nick']+'</label></td><td><input type="text" id="commentFormNick" value="" style="width:370px;" /></td></tr><tr><td class="key"><label for="commentFormEmail">'+this.i18n['label_email']+'</label></td><td><input type="text" id="commentFormEmail" value="" style="width:370px;" /></td></tr><tr><td class="key" valign="top"><label for="commentFormComment">'+this.i18n['label_message']+'</label></td><td><textarea id="commentFormComment" style="width:370px;height:150px;"></textarea></td></tr><tr><td class="key" valign="top"><label for="commentFormCaptcha">'+this.i18n['label_captcha']+'</label></td><td><img src="'+this.i18n['path']+'content/img/captcha.php?a=<?= rand() ?>" onclick="this.src=\''+this.i18n['path']+'content/img/captcha.php?a=\'+Math.random();" style="cursor:pointer;vertical-align:middle" /><input type="text" id="commentFormCaptcha" style="width:310px" /></td></tr></tbody></table>',
					'type'		: 'info',
					'buttons'	: [
											   {
												   label : this.i18n['btn_send'],
												   action : this.onCommentSend.bind(this)
									           },
									           {
												   label : this.i18n['btn_cancel'],
												   action : this.onCommentCancel.bind(this)
									           }
											]
				};
			this.msg = new Msg(options);
		}
		$('msgBox').style.height = 'auto';
		$('msg').style.height = 'auto';
	},
	
	onCommentSend : function() {
		var nick	= $('commentFormNick').value;
		var email	= $('commentFormEmail').value;
		var comment	= $('commentFormComment').value;
		var captcha	= $('commentFormCaptcha').value;
		
		var options = {
			method :'post',
			onSuccess : this.onCommentSuccess.bind(this),
			onFailure : this.onCommentError.bind(this),
			parameters: {nick: nick, email: email, comment : comment, captcha : captcha, ambienceId : this.id, lang : this.i18n['lang']}
		};
		
		this.ajax = new Ajax.Request(
			'../../ajax/commentAmbience.php',
			options
		);
		
		this.msg.hide();
		
		this.msg = new Msg(
			{
				text : '<div>'+this.i18n['msg_sending_comment']+'</div><div style="text-align:center;"><img src="../../content/img/loader.gif" /></div>'
			}
		);
		$('msgBox').style.height = 'auto';
		$('msg').style.height = 'auto';
	},
	
	onCommentCancel : function() {
		this.msg.hide();
	},
	
	onCommentSuccess : function(transport) {
		this.msg.hide();
		
		var response = transport.responseText.evalJSON() || {};
		switch(response.code) {
			case 0:
				this.msg = new Msg(
					{
						text : response.msgText,
						buttons : [
						   {
							   label : 'OK',
							   type : 'success',
							   action : this.msg.hide.bind(this)
				           }
						]
					}
				);
				break;
			
			case 1:
				this.msg = new Msg(
					{
						text : response.msgText,
						type : 'error',
						buttons : [
						   {
							   label : 'OK',
							   action : this.onCommentClick.bind(this)
				           }
						]
					}
				);
				break;
			
			case 2:
				this.msg = new Msg(
					{
						text : response.msgText,
						type : 'error',
						buttons : [
						   {
							   label : 'OK',
							   action : this.onCommentClick.bind(this)
				           }
						]
					}
				);
				break;
			
			default:
				this.onCommentError(transport);
		}

			$('msgBox').style.height = '194px';
			$('msg').style.height = '194px';
	},
	
	onCommentError : function() {
		var options = {
			text : 'Error while sending the comment',
			type : 'error',
			buttons : [
			           {
			        	   label : this.i18n['btn_close'],
			        	   action : this.msg.hide.bind(this)
			           }
			           ]
		};
		
		this.msg = new Msg(options);

		$('msgBox').style.height = '194px';
		$('msg').style.height = '194px';
	},
	
	onLoadAmbienceClick : function(ambienceId) {
		if (!this.rating && !this.commenting && !this.loading) {
			var options = {
				method :'post',
				onSuccess : this.onLoadAmbienceSuccess.bind(this),
				onFailure : this.onLoadAmbienceError.bind(this),
				parameters: {ambienceId: ambienceId, lang : this.i18n['lang']}
			};
			
			this.ajax = new Ajax.Request(
				'../../ajax/loadAmbience.php',
				options
			);
			
			this.msg = new Msg(
				{
					text : '<div>'+this.i18n['msg_loading_ambience']+'</div><div style="text-align:center;"><img src="../../content/img/loader.gif" /></div>',
					type : 'info'
				}
			);
		}
		
			$('msgBox').style.height = '194px';
			$('msg').style.height = '194px';
	},
	
	onLoadAmbienceSuccess : function(transport) {
		this.msg.hide();
		var response = transport.responseText.evalJSON() || {};
		switch(response.code) {
			case 0:
				// Load the values
				this.loadAmbience(response.ambience);
				
				// Load comments
				this.loadComments(response.ambience.comments);
				
				// Update the page
				this.updatePage();
				
				// Initialize listeners
				this.initListeners();
				
				// Add the anchor
				self.document.location.hash = '#'+this.id+'-'+this.url;
				
				// Show the details
				$('ambienceDetails').show();
				
				// Show the comments links
				$('permalink').show();
				
				// Show the rating
				$('rating2').show();
				
				// Update download link
				$('downloadLink').setAttribute('href',this.i18n['path']+this.i18n['downloadLink']+this.id+'-'+this.url);
				
				// Update the permalink
				$('permalinkInput').value = 'http://www.zenambience.com'+this.i18n['path']+this.i18n['permaLink']+this.id+'-'+this.url;
				
				// Update the flash player
				$('player').style.visibility = 'visible';
				this.updatePlayer();
				
				// Update title
				document.title = response.ambience.title + ' - ' + this.i18n['title'];
				
				this.msg = new Msg(
						{
							text : '<p>'+this.i18n['msg_buffering']+'</p><p><div class="ambienceProgressBarEmpty"><div class="ambienceProgressBarFill" id="ambienceProgressBar" style="width:0%"></div></div></p>',
							type : 'info'
						}
					);
				break;
			
			case 1:
				new Msg(
						{
							text : response.msgText,
							type : 'error',
							buttons : [
							   {
								   label : 'OK',
								   action : this.msg.hide.bind(this)
					           }
							]
						}
					);
				break;
			
			default:
				this.onLoadAmbienceError(transport);
		}

		this.loading = false;
		
		$('msgBox').style.height = '194px';
		$('msg').style.height = '194px';
	},
	
	onLoadAmbienceError : function(transport) {
		alert('');
	},
	
	loadAmbience : function(ambience) {
		// Load values
		this.id			= ambience.id;
		this.title		= ambience.title;
		this.url		= ambience.url;
		this.description= ambience.description;
		this.rate		= ambience.rating;
		this.percent	= ambience.percent;
		this.comments	= ambience.comments;
		
		this.i18n['title_fr'] = ambience.title_fr;
		this.i18n['title_en'] = ambience.title_en;
		
		// Reset values
		this.rating		= false;
		this.rated		= false;
		this.commenting	= false;
	},
	
	updatePlayer : function() {
		if (navigator.appName.indexOf("Microsoft") != -1) {
			var player = window['flashMovie'];
		} else {
			var player = document['flashMovie'];
		}
		player.FJSTOASChangeSound('../../content/mp3/'+this.id+'.mp3');
	},
	
	loadComments : function(comments) {
		if (comments.length > 0) {
			var html = '';
			for(var i=0; i<comments.length; i++) {
				html += '<div class="comment comment'+(i%2)+'"><div class="details"><span class="author">'+comments[i].date2+'</span> '+this.i18n['by']+' <span class="author">'+comments[i].name+'</span></div><div class="text">'+comments[i].comment+'</div></div>';
			}
			
			$('comments2').innerHTML = html;
			$('comments').show();
		} else {
			$('comments').hide();
		}
	},
	
	updatePage : function() {
		// Update text
		$('ambienceTitle').innerHTML = this.title;
		$('ambienceDescription').innerHTML = this.description;
		$('ambienceIMG').src = '../../content/img/ambiences/normal/'+this.id+'.png';
		$('ambienceNbComments').innerHTML = this.comments.length;
		
		$('flag_fr').href = this.i18n['path'] + this.i18n['title_fr'];
		$('flag_en').href = this.i18n['path'] + this.i18n['title_en'];
		
		$('permalinkButtonContainer').innerHTML = '<embed src="../../content/swf/clipboard.swf" '
			+ 'FlashVars="txtStr=' + this.i18n['copyBtn'] + '&copyStr=http://www.zenambience.com' + this.i18n['path'] + this.i18n['permaLink'] + this.id + '-' + this.url + '" '
			+ 'width="148" height="22" '
			+ 'type="application/x-shockwave-flash" '
			+ 'bgcolor="transparent" '
			+ 'wmode="transparent"'
			+ '></embed>';
		
		// Re-init the rating
		this.onEvaluateMouseout();
	}
});
