/**
* class bonusRental
* Toggle rental for bonus copies
* Required files - http_request.js, xmlhelper.js, utilities.js
*
* @author Flash 
*/
bonusRental._xmlFile = '/xml/bonusrental.php';
bonusRental._objects = {};

/**
* Constructor
* Note: when accessing use bonusRental.toggle()
*
* @param integer dtId			Id of title to display
* @param string imageId			Id tag of image to toggle
* @return bonusRental
*/
function bonusRental(dtId, imageId) {
	var self = this;

	this._dtId = dtId;
	this._imageElement = utilities.getElement(imageId);
	
	//http request setup
	var request = new HTTPRequest();
	request.onupdate = function(){self._process();}
	request.timeout = 60000;	//dont want to timeout so requests done queue up at server
	this._request = request;
}

/**
* Toggles a title between rented and queued states
*
* @param integer dtId			Id of title to display
* @param string imageId			Id tag of image to toggle
*/
bonusRental.toggle = function(dtId, imageId) {

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

	//send the request, default to non js version if we couldn't use http request
	var success = bonusRental._objects[dtId]._request.send(bonusRental._xmlFile + '?dt_id=' + dtId);
	if (! success) {
		window.location = '/bonus-rental-process.php?dt_id=' + dtId + '&redirect=' + escape(utilities.currentUrl(1));
	}
}

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

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

	//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');

	if (imageSrc) {
		this._imageElement.src = imageSrc;
	}

	if (imageAlt) {
		this._imageElement.alt = imageAlt;
	}

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

	//popup message if we have one
	var message = xml.getValue('message');
	if (message) {
		alert(message);
	}

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

/**
* Removes the current http request
*/
bonusRental.prototype.removeRequest = function() {
	this._request.abort();
}
