/**
 * this function class searches ebay site for fixed price 
 * items using findItemsAdvanced shopping api,
 * 3 items for each price range are listed. 
 * @constructor
 * @param config includes appId, affiliate tracking information
 *        and siteId.
 */
function FindItemsAdvancedSample(config)
{
	/**
	 * storing items for each price range
	 * @type Array
	 */
	this.items = new Array(50);
	/**
	 * storing items number for each price range
	 * @type Array
	 */
	this.itemcount = new Array(50);
	/**
	 * keyword for query
	 * @type String
	 */	
	this.queryKeyWords= null;	
    /**
     * config object includes appId, affiliate tracking information, etc
     * @type Object
     */
	this.config = config;
	/**
	 * number of errors
	 * @type int
	 */
	this.errorCount = 0;

	/**
	 * function for error handling
	 * @param {ErrorType} error
	 */
	this.onSomeItemsReturnedFailed = function(error) {
		var userDiv = document.getElementById("itemContent");
		if(this.errorCount == 0) {
			var search = "<div><input id='query' type='text' size='22' maxlength='30'>";
			search += "<input onclick='FindItemsAdvancedSample.goSearch();'; type='image' src='http://w-1.ebay.com/images/go.gif'>";
			search += "<br></div>";
			userDiv.innerHTML = search;
		}
		var errorHTML = "<div>" + error[0].longMessage + " please try again!</div>";
	    userDiv.innerHTML = errorHTML + userDiv.innerHTML;
		this.errorCount ++;
	};	
	/**
	 * callback function for processing returned items
	 * @param {int} index
	 */
	this.onSomeItemsReturned = function (index) {
		return function (data) {
			this.items[index] = this.convertData4ItemListUI(data);
			this.itemcount[index] = data.totalItems;
	        //waiting until items for all 3 price rangs are received.
			for (var i = 0; i < 1; i++) {
				if (this.items[i] == null) {
					return;
				}
			}
			this.displayItems();
		};
	}
	/**
	 * call findItemsAdvanced shopping api 3 times for each price range
	 * @param {String} queryKeywords
	 */
	this.findItems = function(queryKeywords) {	
		this.queryKeywords = queryKeywords;		
		var service = new com.ebay.shoppingservice.Shopping(this.config);
				
		var request1 = this.getFiaRequest(0,9999);			
		var callback1 = new com.ebay.shoppingservice.ShoppingCallback({object: this, success:this.onSomeItemsReturned(0), failure:this.onSomeItemsReturnedFailed});
		var url = service.findItemsAdvanced(request1,callback1);
		
		
	};
	/**
	 * getting FindItemsAdvanced requests 
	 * @param {int} pmax, the upper limit of the price
	 * @param {int} pmin, the lower limit of the price
	 * @return {FindItemsAdvancedRequestType} 
	*/
	this.getFiaRequest = function (pmax, pmin){
		var fiaRequest = new com.ebay.shoppingservice.FindItemsAdvancedRequestType({
			priceMax: {currencyID: com.ebay.shoppingservice.CurrencyCodeType.GBP, Value: pmax},
			priceMin: {currencyID: com.ebay.shoppingservice.CurrencyCodeType.GBP, Value: pmin},
			itemSort: com.ebay.shoppingservice.SimpleItemSortCodeType.EndTime,
			QueryKeywords: this.queryKeywords,
			itemType: com.ebay.shoppingservice.ItemTypeCodeType.FixedPricedItem,
			maxEntries: 50
			});
		return fiaRequest;
	};
	/**
	 * construct HTML and display items.
	 */
	this.displayItems = function() {
		
		var priceRanges = ["£0-£999"];

		var userDiv = document.getElementById("itemContent");		
		var newLine = "\n";
		var src = "<div id='products' style='float: left;width: 629px; padding: 10px 0;font-family: Arial, sans-serif; font-size: small; border: 2px solid #D9E0E6; background: #e0e040'>" + newLine;
		src = src + "<table width='629' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		src = src + "<tr><td colspan='2' style='font-size: 100%; padding: 4px; font-weight:bold;'>Search Results for \"" + this.queryKeywords + "\"<br></td></tr>" + newLine;
		for (var i= 0; i< 1; i++) {
			src = src + "<tr><td colspan='2' style='font-size: 100%; padding: 4px;'>" + " (Up to 50 items shown):</td></tr>" + newLine;
			src = src + "<tr><td colspan='2'>" + newLine;
			src = src + (new ItemListUI(this.items[i], false).display());
			src = src + "</td></tr>" + newLine;
			//src = src + "<tr><td colspan='2'><br></td></tr>" + newLine;
		}
		src = src + "<tr><td colspan='2'>" + newLine;
		src = src + "<table width='629' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		src = src + "<tr><td style='padding: 0 4px 0 0;' bgcolor='#e0e040' align='right' valign='bottom'>" + newLine;	
		src = src +	"<input id='query' type='text' size='22' maxlength='30'><input onclick='FindItemsAdvancedSample.goSearch();'; type='image' src='http://w-1.ebay.com/images/go.gif'>" + newLine;
		src = src + "</td>" + newLine;
		src = src + "</table>" + newLine;
		src = src + "</td>" + newLine;	
		src = src + "</tr>" + newLine;
		src = src + "</table>" + newLine;
		src = src + "</div>" + newLine;		
		userDiv.innerHTML = src;			
	};
	/**
	 * convert returned items into format suitable for display on UI
	 * @param {FindItemsAdvancedResponseType} data
	 * @return {Array}, converted items
	 */	
	this.convertData4ItemListUI = function(data) {
		if (data.searchResult !== null) {
			var itemArray = data.searchResult[0].itemArray;
		}
		var items = [];
		if (itemArray) {			
			var count = itemArray.item.length ;

			var i = 0;
			while (items.length < 50 && i < count) {
				
				if (!itemArray.item[i].buyItNowAvailable 
					&& itemArray.item[i].listingType.value == com.ebay.shoppingservice.ListingTypeCodeType.Chinese.value) {
					continue;
				}
				var item = itemArray.item[i];
				items.push(item);
																			
				i++;
			}			
		}
		return items;
	};
}
/**
 * main static entry function for search 
 * @param {Object} params
 */
FindItemsAdvancedSample.goSearch = function(params) {				
	queryKeyword = null;
	var query = document.getElementById('query');
	if (query) {
		queryKeyword = query.value;
	}			

	if (queryKeyword === null && params) {
		queryKeyword = params.g_queryKeyword;
	}
	if (queryKeyword === null) {		
		queryKeyword = "tickets";
	}

	var props = {};
	/* 
	 * Place your appId here */
	 props["appId"] = "PeterFar-b0c1-4d0b-90bb-e33ef762c9de";
	 /* Place your affiliate information
	 * props["trackingId"] = <Your trackingId>;
	 * props["trackingPartnerCode"] = <Your trackingPartnerCode>; */
	 props["affiliateUserId"] = "2910493";
/*	 * Place site id, default is 0 if you don't set */
	 props["siteId"] = 3; 
	 
	
	var config = new com.ebay.shoppingservice.ShoppingConfig(props);

	new FindItemsAdvancedSample(config).findItems(queryKeyword);
};

