// include all the required library scripts
LibManager.require('Scheduler');
LibManager.require('frame.prototype.ajax');
LibManager.require('frame.prototype.form');
LibManager.require('frame.scriptaculous.effects');

var HolidayReviewRatingController = {
	/**
	* holds the ajax request object
	* @var obj
	*/
	ajaxRequest: null,

	/**
	* holds the timeout for ajax requests
	* @var obj
	*/
	ajaxTimeout: null,

	/**
	* holds the total time for the current ajax request
	* @var int
	*/
	ajaxReqTime: null,

	/**
	* holds the maximum amount of time (in ms) that we'll allow for the ajax requests
	* @var int
	*/
	ajaxMaxReqTime: 10000,

	/**
	* holds the intervals (in ms) we'll check the status of the ajax request on
	* @var int
	*/
	ajaxCheckInterval: 500,

	/**
	* holds the base url for use with ajax requests
	* @var string
	*/
	ajaxBaseUrl: '/HolidayReview/AddRatingToReview',

	init: function() {
		Scheduler.schedule('reviewListingEnd', 'HolidayReviewRatingController.attach()')
	},

	attach: function() {
		// Loop through all review rating forms on review listing page attaching observer to submit event handler	
		for (i = 0; i <= document.forms.length - 1; i++) {

			if (document.forms[i].className == 'reviewRating') {
				Event.observe(document.forms[i], 'submit', this.validate.bindAsEventListener(this));
			}
		}
	},

	validate: function(e) {
		var form = Event.element(e);
		var ratingResponse = Form.getInputs(form, "radio", "rating");
		var reviewId = Form.getInputs(form, "hidden", "reviewId")[0].value;
		var rating = 0;
		var wrapper = $("ratingWrapper_" + reviewId);
		var msgBox = $("ratingMsg_" + reviewId);

		if (ratingResponse[0].checked || ratingResponse[1].checked) {
			if (ratingResponse[0].checked) { rating = ratingResponse[0].value; }
			else { rating = ratingResponse[1].value; }

			this.rateReview(reviewId, rating, msgBox, wrapper);
		}
		else {
			msgBox.firstChild.nodeValue = "You have not selected whether the review was helpful or not helpful.";
			this.doHighlight(wrapper);
			this.styleMsgBox(msgBox);
		}

		Event.stop(e);
	},

	/**
	* Checks to see if the ajaxRequest is currently processing a call (readyState 1,2 or 3)
	*
	* @return boolean
	*/
	callInProgress: function() {
		switch (this.ajaxRequest.transport.readyState) {
			case 1:
			case 2:
			case 3:
				return true;
				break;
			// Case 4 and 0 
			default:
				return false;
				break;
		}
	},

	/**
	* Calls rateHolidayReviewAjax event which registers the users review rating 
	* and displays the appropriate status message
	* 
	* @access public
	* @param reviewId int
	* @param rating int
	* @param msgBox HtmlDivElement
	* @param wrapper HtmlDivElement
	* @return void
	*/
	rateReview: function(reviewId, rating, msgBox, wrapper) {
		var errMsg = 'Error: no data received. Please try again.';
		var requestVars = {
			content: 'rateHolidayReviewAjax',
			rating: rating,
			reviewId: reviewId,
			reviewType: "holiday"
		};
		this.styleMsgBox(msgBox);
		this.createAjaxUpdater(wrapper, msgBox, requestVars, errMsg);
	},

	/**
	* Checks the current ajax request to see if it has a response if 
	* not and it's currently processing and has reached the timeout limit
	* then abort the request and notify the user
	*
	* @return void
	*/
	checkResponse: function() {
		var thisObj = this;
		this.ajaxReqTime += this.ajaxCheckInterval;
		if (this.callInProgress() && (this.ajaxReqTime >= this.ajaxMaxReqTime)) {
			this.ajaxRequest.transport.abort();
			if (this.ajaxRequest.options['onFailure']) {
				this.ajaxRequest.options['onFailure']();
			}
		} else {
			this.ajaxTimeout = window.setTimeout(
				function() {
					thisObj.checkResponse();
				},
				this.ajaxCheckInterval
			);
		}
	},

	doHighlight: function(wrapper) {
		new Effect.Highlight(wrapper,
    	{ startcolor: '#ffffff',
    		endcolor: '#ffffcc',
    		duration: 0.5
    	})
	},

	styleMsgBox: function(msgBox) {
		msgBox.style.padding = "1em 0 1em 0";
	},

	createAjaxUpdater: function(wrapper, container, reqVars, errorMsg) {
		var thisObj = this;
		this.ajaxReqTime = 0;
		this.ajaxTimeout = window.setTimeout(
			function() {
				thisObj.checkResponse();
			},
			thisObj.ajaxCheckInterval
		);
		this.ajaxRequest = new Ajax.Updater(
			container,
			thisObj.ajaxBaseUrl,
			{ method: 'get',
				parameters: $H(reqVars).toQueryString(),
				onComplete:

				function(request) {
					window.clearTimeout(thisObj.ajaxTimeout);
					if (!request.responseText.length || request.status != 200) {
						alert(errorMsg);
					}
					else {
						thisObj.doHighlight(wrapper);
					}
				},

				onFailure: function(request) {
					window.clearTimeout(thisObj.ajaxTimeout);
					alert('Error: Cannot contact database. Please try again.');
				}
			}
		);
	}
}

LibManager.isLoaded(
    ['scheduler'],
	HolidayReviewRatingController.init()
);