/**
* class rent
* Interactive handling of renting/unrenting
* Required files - http_request.js, xmlhelper.js, utilities.js
*
* @author Flash 
*/

//location of processing script
rent._rentFile = '/xml/rent.php';
rent._priorityFile = '/xml/rent-priority.php';

//name of image to show when processing
rent._processingImage = '/images/button_processing.gif';

//list of active rent objects
rent._objects = {};

rent._confirmedPlatforms = {};

/**
* Constructor
* Note: when accessing use rent.toggle()
*
* @param integer dtId			Id of title to display
* @param boolean isBoxset		Whether rent button is for boxset
* @return rent
*/
function rent(dtId, isBoxset) {
	var self = this;

	this._id = (isBoxset ? 'b' : '') + dtId;
	this._dtId = dtId;
	this._isBoxset = isBoxset;

	this._rentButton = utilities.getElement('rentButtonImg_' + this._id);
	this._priorityBox = utilities.getElement('rentPriorityBox_' + this._id);
	this._inOrderCheckbox = utilities.getElement('rentInOrder_' + this._id);

	//temporarily image state before processing
	this._prevButtonSrc;
	this._prevButtonAlt;
	
	this._quId = null;
	this._fasttrakable = null;

	//http request setup
	var request = new HTTPRequest();
	request.onupdate = function(error){self._process(error);}
	//request.timeout = 3000;	//dont want to timeout as button could get out of sync with server
	this._request = request;

	//hold the request type so we know how to process it
	this._requestType;
}

/**
* Toggles a title between rented and queued states
*
* @param integer dtId				Id of title to display
* @param boolean isBoxset			Whether rent button is for boxset
* @param integer confirmPlatform	Platform that needs to be confirmed before renting
*/
rent.toggle = function(dtId, isBoxset, confirmPlatform) {

	if (! dtId) { 
		return;
	}

	//check if we need to confirm platform before renting
	var platformConfirmed = 0;
	if (confirmPlatform && ! rent._confirmedPlatforms[confirmPlatform]) {
		var confirmMsg;

		switch (confirmPlatform) {
		//umd/dvd
		case 2:
			confirmMsg = "This film is a PSP/UMD title and only playable on a Sony PlayStation Portable (PSP).\n" +
						"Click OK to continue to rent this film?\n" +
						"If you click OK you will not be asked this question again.";
			break;
		}

		if (confirmMsg) {
			//if user confirms, flag this so it doesn't show again
			if (confirm(confirmMsg)) {
				rent._confirmedPlatforms[confirmPlatform] = true;
				platformConfirmed = 1;
			}
			//else don't do any more processing
			else {
				return;
			}
		}
	}

	isBoxset = isBoxset ? 1 : 0;

	var key = (isBoxset ? 'b' : '') + dtId;

	//we have one object per title so we cant send 2 requests for same title at same time
	if (! rent._objects[key]) {
		rent._objects[key] = new rent(dtId, isBoxset);
	}

	var rentItem = rent._objects[key];

	//only one request at a time
	if (rentItem._request.inProgress()) {
		return;
	}

	rentItem._hideBucketSelect();

	//if we have a processing image, use it
	if (rent._processingImage) {
		rentItem._updateRentButton(rent._processingImage, 'Processing');
	}

	//send the request, default to non js version if we couldn't use http request
	rentItem._requestType = 'rent';
	var success = rentItem._request.send(rent._rentFile + '?dt_id=' + dtId + '&boxset=' + isBoxset + '&in_order=' + rentItem._inOrder() + '&platform_confirmed=' + platformConfirmed);
	if (! success) {
		window.location = '/rent.php?dt_id=' + dtId + '&boxset=' + isBoxset +  '&redirect=' + escape(utilities.currentUrl(1));
	}
}

/**
* Returns whether to send the series in order
*
* @return boolean		Whether to send series in order
*/
rent.prototype._inOrder = function() {
	return !this._inOrderCheckbox ? 1 : (this._inOrderCheckbox.checked ? 1 : 0);
}

/**
* Processes the request response
*
* @param errorObject?? error		JS error passed from HTTPRequest itself
*/
rent.prototype._process = function(error) {
	//don't do anything if there was an error
	if (error) {
		this._cancelProcess();
		return;
	}

	//get the base xml parsed object
	var xml = new XMLHelper(this._request.getResponseXML());
	
	if (! xml.isValid()) {
		this._cancelProcess();
		return;	
	}

	//call the appropriate process routine
	switch(this._requestType) {
	case 'rent':
		this._processRent(xml);
		break;

	case 'priority': 
		this._processPriority(xml);
		break;

	default:
		break;
	}
}

/**
* Processes the rent request response
*
* @param XMLHelper xml		XML object containing response
*/
rent.prototype._processRent = function(xml) {

	//redirect if needed
	var url = xml.getAttribute('redirect', 'url');
	if (url) {
		//hack so we can get add current page to the url
		url = url.replace('{LOCATION}', escape(utilities.currentUrl(1)));
		window.location = url;
		return;
	}

	//update rent button image
	var imageSrc = xml.getAttribute('image', 'src');
	var imageAlt = xml.getAttribute('image', 'alt');

	this._updateRentButton(imageSrc, imageAlt);

	//update the num items text
	var numItemsAdded = parseInt(xml.getAttribute('itemsadded', 'num'));
	if (numItemsAdded) {
		updateNumItemsQueued(numItemsAdded);	
	}

	//if we have a series, try to update button of any titles
	var boxset = xml.getElement('boxset');
	if (boxset) {
		var imageSrc = xml.getAttribute(boxset, 'src');
		var imageAlt = xml.getAttribute(boxset, 'alt');

		if (imageSrc) {
			var boxsetTitles = xml.getElements('boxset_title', boxset);

			for(var i = 0; i < boxsetTitles.length; i++) {
				var boxsetTitle = boxsetTitles[i];
				var dtId = xml.getAttribute(boxsetTitle, 'id');

				if (dtId) {
					var rentButton = utilities.getElement('rentButtonImg_' + dtId);

					if (rentButton) {
						rentButton.src = imageSrc;
						rentButton.alt = imageAlt;
					}
				}
			}
		}
	}

	//popup message if we have one
	var message = xml.getValue('message');
	if (message) {
		alert(message);
	}
	else {
		//show bucket select if we have a queue item
		this._quId = parseInt(xml.getAttribute('queue', 'id'));
		this._fasttrakable = parseInt(xml.getAttribute('queue', 'fasttrakable'));

		if (this._quId) {
			this._showBucketSelect();
		}
	}

	//clean up the request
	this._removeRequest();
}

/**
* Cancels the current processing 
*/
rent.prototype._cancelProcess = function() {
	this._removeRequest();

	//if we have a previous image, update it (in the case of processing image)
	if (this._prevButtonSrc) {
		this._updateRentButton(this._prevButtonSrc, this._prevButtonAlt);
	
		this._prevButtonSrc = null;
		this._prevButtonAlt = null;
	}

	//cancel bucket
	this._hideBucketSelect();
}

/**
* Removes the current http request
*/
rent.prototype._removeRequest = function() {
	this._request.abort(true);
}

/**
* Updates the rent button image
*
* @param string src		Filename of new image
* @param string alt		Alternate text to display
*/
rent.prototype._updateRentButton = function(src, alt) {

	if (! this._rentButton)
		return;

	if (src) {
		this._prevButtonSrc = this._rentButton.src;
		this._rentButton.src = src;
	}

	if (alt) {
		this._prevButtonAlt = this._rentButton.alt;
		this._rentButton.alt = alt;
	}
}

/**
* Displays the bucket selection
*/
rent.prototype._showBucketSelect = function() {
	if (! this._priorityBox || ! this._quId)
		return;

	var html = '<div class="pybox">';

	//add each priority
	for (var pri = 1; pri <= 3; pri++) {	
		html += '<a href="" onclick="rent._objects[\''+this._id+'\']._updatePriority('+pri+');return false" title="Add item at Priority '+pri+'" class="pyhover"><img src="/images/queue/priority-'+pri+'.gif" width="29" height="29" alt="Priority '+pri+'" /></a>';
	}

	//add fasttrak button
	if (this._fasttrakable) {
		html += '<a href="" onclick="rent._objects[\''+this._id+'\']._updatePriority(\'ft\');return false" title="Add item to your FastTrak queue" class="pyhover"><img src="/images/queue/priority-0.gif" width="29" height="29" alt="FastTrak" /></a>';
	}

	html += ' \
		<br /> \
		<span class="pymsg"><strong>Please select a priority for this item</strong></span> \
		<p class="pyclose"><small>[<a href="" onclick="rent._objects[\''+this._id+'\']._hideBucketSelect();return false" title="Close">Close</a>]</small></p> \
		</div>';

	this._priorityBox.innerHTML = html;
	this._priorityBox.style.display = 'block';
}

/**
* Removes the bucket selection
*/
rent.prototype._hideBucketSelect = function() {
	if (this._priorityBox) {
		this._priorityBox.style.display = 'none';
	}
}

/**
* Update the priority of the newly added queue item
*
* @param integer priority		New priority to update to
*/
rent.prototype._updatePriority = function(priority) {
	this._hideBucketSelect();

	//need a queue and priority to update
	if (! this._quId || ! priority) {
		this._hideBucketSelect();
		return;
	}
	
	//send the request
	this._requestType = 'priority';
	var success = this._request.send(rent._priorityFile + '?qu_id=' + this._quId + '&priority=' + priority);
}

/**
* Processes the priority request response
*
* @param XMLHelper xml		XML object containing response
*/
rent.prototype._processPriority = function(xml) {

	//we currently only need to clean up the request
	this._removeRequest();
}
