/**
 * Download basket
 *
 * @author: Bruno Babic
 * @copyright: BotW
 */

/*
 * Adds specified item to download basket
 *
 * @param string type - item type to add (one of 'BRAND', 'PHOTO', 'FONT')
 * @param int id - ID of item to add
 * @param string callback - callback function for XmlHttpRequest object (onreadystatechange)
 * @returns XmlHttpRequest object or null on error
 */
function addToDLBasket(type, id, callback)
{
	var uri = '/download-basket/add';

	switch (type)
	{
		case 'BRAND':
			uri += '/brand';
			break;
		case 'PHOTO':
			uri += '/photo';
			break;
		case 'FONT':
			uri += '/font';
			break;
		default:
			alert('Unhandled item type! [' + type + ']');
			return null;
	}
	
	uri += '/' + id;

	var http = getXmlHttpObject();
	if (http == null)
		return null;

	http.onreadystatechange = callback;
	if (!sendHTTPRequest(http, 'GET', uri))
	{
		alert('Failed to send HTTP request!');
		return null;
	}		
	
	return http;
}

/*
 * Removes specified item from download basket
 *
 * @param string type - item type to remove (one of 'BRAND', 'PHOTO', 'FONT')
 * @param int id - ID of item to remove
 * @param string callback - callback function for XmlHttpRequest object (onreadystatechange)
 * @returns XmlHttpRequest object or null on error
 */
function removeFromDLBasket(type, id, callback)
{
	var uri = '/download-basket/remove';

	switch (type)
	{
		case 'BRAND':
			uri += '/brand';
			break;
		case 'PHOTO':
			uri += '/photo';
			break;
		case 'FONT':
			uri += '/font';
			break;
		default:
			alert('Unhandled item type! [' + type + ']');
			return null;
	}
	
	uri += '/' + id;

	var http = getXmlHttpObject();
	if (http == null)
		return null;

	http.onreadystatechange = callback;
	if (!sendHTTPRequest(http, 'GET', uri))
	{
		alert('Failed to send HTTP request!');
		return null;
	}
	
	return http;
}

/*
 * Sends HTTP request
 *
 * @param object xmlHttp - XmlHttpRequest object to use
 * @param string method - HTTP method to use ('GET', 'POST', ...)
 * @param string uri - URI to request
 * @returns true if ok, false on error
 */
function sendHTTPRequest(xmlHttp, method, uri)
{
	if (xmlHttp == null)
		return false;
		
	xmlHttp.open(method, uri, true);
	xmlHttp.send(null);
	
	return true;
}

/*
 * Gets new instance of XmlHttpRequest object
 *
 * @returns instance of XmlHttpRequest object or null if AJAX not supported
 */
function getXmlHttpObject()
{
	var xmlHttp = null;
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch (e)
		{
			try
			{
				xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
			}
			catch (e)
			{
				return null;
			}
		}
	}

	return xmlHttp;
}
