/**
 * Class for the AJAX renommee dialog
 *
 * @author      Oliver Kliebisch
 * @copyright   2009-2010 Oliver Kliebisch
 * @license     Commercial
 */
var RenommeeRatingDialog = Class.create({

	/**
	 * Initializes the rating dialog
	 */
	initialize: function(objectType, activeUserModifier, objectData) {
		this.objectType = objectType;
		this.objectData = objectData;
		this.activeUserModifier = activeUserModifier;
		this.activeID = 0;
		this.sending = false;
		this.renommeeDialogVisible = false;
		this.IE6 = (navigator.appVersion.indexOf('MSIE 6.')==-1) ? false : true;
		this.IE7 = (navigator.appVersion.indexOf('MSIE 7.')==-1) ? false : true;
		this.dialogTemplate = new Template(
			'<div class="border titleBarPanel" style="display: none; position:absolute; overflow: hidden;' + ((this.IE6 || this.IE7) ? 'width: 400px;' : '') + ' " id="renommeeDialog">' +
			'	<div class="containerHead">' +
			'		<h3 style="text-align: right;">' +
			'			<span style="float: left;">' + language['wcf.user.renommee.add'] + '</span>' +
			'			<a href="index.php?page=Help&item=user.renommee' + SID_ARG_2ND + '"><img src="#{helpIcon}" alt="" title="' + language['wcf.help.title'] +'" /></a>' +
			'			<a onclick="renommeeDialog.showDialog(#{objectID}); return false;"><img src="#{closeIcon}" alt="" title="' + language['wcf.global.button.close'] + '" /></a>' +
			'		</h3>' +
			'	</div>' +
			'       <form id="renommeeForm" class="container-1" method="post" action="index.php?form=UserRenommee" onsubmit="return renommeeDialog.sendForm();" style="overflow: hidden;">' +
			'		<fieldset style="margin: 10px 10px 5px;">' +
			'			<legend>#{objectStateTitle}</legend>'+
			'				<div>'+
			'					<div class="formGroupField">' +
			'						<fieldset>' +
			'								<div class="formField">' +
			'									<label><input type="radio" id="renommeeState" name="state" value="1" checked="checked" /> ' + language['wcf.user.renommee.' + this.objectType + '.state.positive'] + '</label>' +
			'									<label><input type="radio" name="state" value="-1" /> ' + language['wcf.user.renommee.' + this.objectType + '.state.negative'] + '</label>' +
			'								</div>' +
			'						</fieldset>' +
			'					</div>' +
			'				</div>' +
			'				<div id="ratingCommentDiv">' +
			'					<div class="formFieldLabel" style="text-align: left;">' +
			'						<label for="ratingComment">' + language['wcf.user.renommee.comment'] + '</label>' +
			'					</div>' +
			'					<div class="formField">' +
			'						<input type="text" class="inputText" name="comment" id="ratingComment" value="" />' +
			'					</div>' +
			'					<div class="formFieldDesc">' +
			'						' + language['wcf.user.renommee.comment.description']  +
			'					</div>' +
			'				</div>' +
			'		</fieldset>' +
			'		<div class="formSubmit">' +
			'			<input type="hidden" name="s" value="#{SID_ARG_2ND}" />' +
			'			<input type="hidden" name="t" value="#{SECURITY_TOKEN}" />' +
			'			<input type="hidden" name="objectID" value="#{objectID}" />' +
			'			<input type="hidden" name="objectType" value="#{objectType}" />' +
			'			<input type="hidden" name="userID" value="#{userID}" />' +
			'			<input onclick="renommeeDialog.sendForm();" style="margin: 0px auto;" type="button" value="' + language['wcf.global.button.submit'] + '" />' +
			'		</div>' +
			'	</form>' +
			'' +
			'</div>'
			);
		this.options = Object.extend({
			icons: {
				help: RELATIVE_WCF_DIR + 'icon/helpS.png',
				close: RELATIVE_WCF_DIR + 'icon/closeS.png',
				positive: RELATIVE_WCF_DIR + 'icon/renommeePositiveS.png',
				neutral: RELATIVE_WCF_DIR + 'icon/renommeeNeutralS.png',
				negative: RELATIVE_WCF_DIR + 'icon/renommeeNegativeS.png'
			}
		}, arguments[3] || { });
		this.objectData.each(function(object) {
			if ($('renommeeButton' + object.key)) {
				$('renommeeButton' + object.key).onclick =  function() {
					return renommeeDialog.showDialog(object.key);
				};
				$('renommeeButton' + object.key).ondblclick = function() {
					document.location.href = fixURL('index.php?form=UserRenommee&userID=' + object.value.userID + '&objectType=' + this.objectType + '&objectID=' + object.key + '&t=' + SECURITY_TOKEN + SID_ARG_2ND);
				}.bind(this);
			}
		}.bind(this));

		this.initializeInlineObjectRenommee();
	},

	/**
	 * Displays the rating dialog
	 */
	showDialog: function(objectID) {
		var button = $('renommeeButton' + objectID);
		var dialog = $('renommeeDialog');
		var visible = this.renommeeDialogVisible;

		if (dialog && visible) {
			new Effect.Parallel([
				new Effect.BlindUp(dialog, {
					duration: 0.5
				}),
				new Effect.Fade(dialog, {
					duration: 0.5
				})
				], {
					duration: 0.5
				});
			this.renommeeDialogVisible = false;
		}

		if (!visible || this.activeID != objectID) {
			this.activeID = objectID;
			var objectData = this.objectData.get(objectID);
			var templateData = {
				SID_ARG_2ND: SID_ARG_2ND.replace(/&s=/, ''),
				SECURITY_TOKEN: SECURITY_TOKEN,
				objectStateTitle: language['wcf.user.renommee.' + this.objectType + '.state'].replace(/\{\$username\}/, objectData['username']),
				objectType: this.objectType,
				objectID: objectID,
				userID: objectData['userID'],
				username: objectData['username'],
				helpIcon: this.options.icons.help,
				closeIcon: this.options.icons.close
			};
			// remove old dialog
			if (dialog) {
				dialog.remove();
			}
			// insert new dialog
			$$('body')[0].insert(this.dialogTemplate.evaluate(templateData));
			var dialog = $('renommeeDialog');

			var offset = button.cumulativeOffset()[0];
			if (button.cumulativeOffset()[0] + dialog.getWidth() > document.viewport.getWidth()) {
				offset = document.viewport.getWidth() - dialog.getWidth() - 5;
			}
			if (button) {
				dialog.setStyle('left: ' + offset + 'px; top: ' + (button.cumulativeOffset()[1] + button.getHeight() + 5) + 'px');
			}

			if (dialog) {
				new Effect.Parallel([
					new Effect.BlindDown(dialog, {
						duration: 0.5
					}),
					new Effect.Appear(dialog, {
						duration: 0.5
					})
					], {
						duration: 0.5
					});
				this.renommeeDialogVisible = true;

			}
		}
		return false;
	},

	/**
	 * Validates and submits the form
	 */
	sendForm: function() {
		// validate
		if (enforceComments) {
			var comment = $('ratingComment').value;
			comment = comment.replace(/^\s+|\s+$/g,"");
			if (comment.length == 0) {							
				if (!$('ratingCommentError')) {
					$('ratingCommentDiv').addClassName('formError');
					var errorParagraph = document.createElement('p');
					errorParagraph.id = 'ratingCommentError';
					errorParagraph.addClassName('innerError');
					errorParagraph.insert(language['wcf.global.error.empty']);
					$('ratingComment').up().insert(errorParagraph);
				}
				
				return false;
			}
		}

		if (!this.sending) {
			this.sending = true;
			$('renommeeForm').request({
				onSuccess: function() {this.showSendResult()}.bind(this),
				onFailure: function() {
					$('renommeeForm').submit();
				},
				parameters: {
					ajax: 1
				}
			});
		}
		return false;
	},

	/**
	 * Updates the buttons or hides them
	 */
	showSendResult: function() {
		this.sending = false;
		var dialog = $('renommeeDialog');
		var button = $('renommeeButton' + this.activeID);
		var visible = this.renommeeDialogVisible;

		if (dialog && visible && button) {
			new Effect.Parallel([
				new Effect.BlindUp(dialog, {
					duration: 0.5
				}),
				new Effect.Fade(dialog, {
					duration: 0.5
				})
				], {
					duration: 0.5
				});
			this.renommeeDialogVisible = false;

			if (showRenommee && !showRenommeeAlways) {
				button.href = fixURL('index.php?page=ObjectRenommee&objectType=' + this.objectType + '&objectID=' + this.activeID + SID_ARG_2ND);
				var renommee = this.objectData.get(this.activeID)['renommee'];
				var form = $('renommeeForm');
				var state = form['renommeeState'];
				var renommeeChange = Form.Element.getValue(state) ? parseInt(Form.Element.getValue(state)) : -1;
				var renommee = renommee + this.calculateRenommee(renommeeChange, this.activeUserModifier);

				var children = button.childElements();
				if (renommee > 0) {
					children[0].src = this.options.icons.positive;
				}
				else if (renommee == 0) {
					children[0].src = this.options.icons.neutral;
				}
				else children[0].src = this.options.icons.negative;
				children[1].update(renommee);

				button.onclick = null;
				var title = language['wcf.user.renommee.' + this.objectType + '.renommee'];
				title = title.replace(/\{\$renommee\}/, renommee);
				button.title = title;
				button.id = 'objectRenommeeButton' + this.activeID;
				button.addClassName('objectRenommeeButton');

				new Effect.Pulsate(button, {
					pulses: 2,
					duration: 1.5
				});
			}
			else if (showRenommee && showRenommeeAlways) {
				new Effect.Fade(button.up(), {
					duration: 0.5
				});

				var objectButton = $('objectRenommeeButton' + this.activeID);

				var renommee = this.objectData.get(this.activeID)['renommee'];
				var form = $('renommeeForm');
				var state = form['renommeeState'];
				var renommeeChange = Form.Element.getValue(state) ? parseInt(Form.Element.getValue(state)) : -1;
				var renommee = renommee + this.calculateRenommee(renommeeChange, this.activeUserModifier);

				var children = objectButton.childElements();
				if (renommee > 0) {
					children[0].src = this.options.icons.positive;
				}
				else if (renommee == 0) {
					children[0].src = this.options.icons.neutral;
				}
				else children[0].src = this.options.icons.negative;
				children[1].update(renommee);
				var title = language['wcf.user.renommee.' + this.objectType + '.renommee'];
				title = title.replace(/\{\$renommee\}/, renommee);
				objectButton.title = title;

				new Effect.Pulsate(objectButton, {
					pulses: 2,
					duration: 1.5,
					delay: 0.5
				});
			}

			if (rerateThreshold) {
				this.hideRatingButtons(this.objectData.get(this.activeID)['userID']);
			}
			this.initializeInlineObjectRenommee(this.activeID);
		}

	},

	/**
	 * Removes all obsolete rading buttons
	 */
	hideRatingButtons: function(userID) {
		this.objectData.each(function(object) {
			var object = object.value;
			var objectID = object.objectID;
			if (objectID != this.activeID && object['userID'] == userID) {
				var button = $('renommeeButton' + objectID);
				if (button) {
					new Effect.Fade(button.up(), {
						duration: 0.5
					});
				}
			}
		}.bind(this));

	},

	/**
	 * Initializes the inline renommee of all objects
	 */
	initializeInlineObjectRenommee: function(objectID) {
		if (objectID) {
			displayButton = $('objectRenommeeButton' + objectID);
			if (displayButton) {
				displayButton.onclick = function() {
					return renommeeDialog.displayInlineObjectRenommee(this.objectData.get(objectID));
				}.bind(this);
				displayButton.ondblclick = function() {
					document.location.href = fixURL('index.php?page=ObjectRenommee&objectType=' + objectType + '&objectID=' + objectID + SID_ARG_2ND);
				};
			}
		}
		else {
			this.objectData.each(function(object) {
				var object = object.value;
				var objectID = object.objectID;
				var objectType = this.objectType;
				displayButton = $('objectRenommeeButton' + objectID);
				if (displayButton) {
					displayButton.onclick = function() {
						return renommeeDialog.displayInlineObjectRenommee(this.objectData.get(objectID));
					}.bind(this);
					displayButton.ondblclick = function() {
						document.location.href = fixURL('index.php?page=ObjectRenommee&objectType=' + objectType + '&objectID=' + objectID + SID_ARG_2ND);
					};
				}
			}.bind(this));
		}
	},

	/**
	 * Displays the inline renommee of an object
	 */
	displayInlineObjectRenommee: function(object) {
		if ($('inlineObjectRenommee' + object.objectID)) {
			new Effect.Parallel([
				new Effect.BlindUp('inlineObjectRenommee' + object.objectID, {
					duration: 0.5
				}),
				new Effect.Fade('inlineObjectRenommee' + object.objectID, {
					duration: 0.5
				})],
				{
					duration: 0.5,
					afterFinish: function() {
						$('inlineObjectRenommee' + object.objectID).remove();
						loadingInlineRenommee = false;
					}
				});
		}
		else {
			if (loadingInlineRenommee) return false;
			// get button
			var displayButton = displayButton = $('objectRenommeeButton' + object.objectID);

			// show spinner
			var oldRenommeeImage = displayButton.down('img').src;
			displayButton.down('img').src = RELATIVE_WCF_DIR + 'images/renommeeSpinner.gif';

			// get smallButtons container
			smallButtons = displayButton.up('.smallButtons');

			var url = fixURL('index.php?page=ObjectRenommee&objectType=' + this.objectType + '&objectID=' + object.objectID + '&inline=1' + SID_ARG_2ND);
			loadingInlineRenommee = true;
			new Ajax.Request(url, {
				method: 'get',
				onSuccess: function(transport) {
					if (transport.responseText != '') {
						smallButtons.up().insert('<div class="inlineObjectRenommee" id="inlineObjectRenommee' + object.objectID + '" style="display: none;">' + transport.responseText + '</div>');
						new Effect.Parallel([
							new Effect.BlindDown('inlineObjectRenommee' + object.objectID, {
								duration: 0.5
							}),
							new Effect.Appear('inlineObjectRenommee' + object.objectID, {
								duration: 0.5
							})],
							{
								duration: 0.5,
								afterFinish: function() { displayButton.down('img').src = oldRenommeeImage; }.bind(this)
							});
						loadingInlineRenommee = false;
					}
				}.bind(this),
				onFailure: function () {
					document.location.href = fixURL('index.php?page=ObjectRenommee&objectType=' + this.objectType + '&objectID=' + object.objectID + SID_ARG_2ND)
				}.bind(this)
			});
		}

		return false;
	},

	/**
	 * Calculcates a new renommee value
	 */
	calculateRenommee: function(state, modifier) {
		value = 0;
		if (state == -1) {
			value = Math.round(state * modifier * (negativeRenommeeFactor / 100));
		}
		else value = state * modifier;

		return value;
	}
});
