/**
 * 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 FindItemsAdvancedModel(config)
{
	/**
	 * storing items for each price range
	 * @type Array
	 */
	this.items = new Array(1);
	/**
	 * storing items number for each price range
	 * @type Array
	 */
	this.itemcount = new Array(1);
	/**
	 * keyword for query
	 * @type String
	 */	
	this.queryKeyWords= null;	
	
	this.priceLow=0;
	this.priceHigh=100;
	this.searchSizeMax=100;
    /**
     * 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='FindItemsAdvancedModel.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,sizeSearch) {	
		this.queryKeywords = queryKeywords;		
		var service = new com.ebay.shoppingservice.Shopping(this.config);
				
		var request1 = this.getFiaRequest(priceLow,priceHigh,sizeSearch);			
		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, sizeSearch){
		var fiaRequest = new com.ebay.shoppingservice.FindItemsAdvancedRequestType({
			priceMax: {currencyID: com.ebay.shoppingservice.CurrencyCodeType.USD, Value: pmax},
			priceMin: {currencyID: com.ebay.shoppingservice.CurrencyCodeType.USD, Value: pmin},
			itemSort: com.ebay.shoppingservice.SimpleItemSortCodeType.BestMatchPlusPrice,
			QueryKeywords: this.queryKeywords,
			itemType: com.ebay.shoppingservice.ItemTypeCodeType.FixedPricedItem,
			maxEntries:  sizeSearch
			});
		return fiaRequest;
	};
	/**
	 * construct HTML and display items.
	 */
	this.displayItems = function() {
		
		
		var userDiv = document.getElementById("itemContent");		
		var newLine = "\n";
		var src = "<div id='products' style='float: left;width: 100%; padding: 5px 0;font-family: Arial, sans-serif; font-size: small;  '>" + newLine;
		src = src + "<table width='100%' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		
		for (var i= 0; i< 1; i++) {
			if (this.itemcount[i] == 0) {
				//0 items
		    } else {
				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' class='textSmall' style='color:blue;'>"  + " (" + this.itemcount[i] + " items found)</td></tr>" + newLine;
				//src = src + "<tr><td colspan='2'><br></td></tr>" + newLine;
			}
		}
		src = src + "<tr><td colspan='2'>" + 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 < this.searchSizeMax && 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
 */
FindItemsAdvancedModel.goSearch = function(params,lowp,highp,size) {				
	queryKeyword = null;
	priceLow = lowp;
	priceHigh = highp;
	var query = document.getElementById('query');
	if (query) {
		queryKeyword = query.value;
	}			

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

	var props = {};
	props["appId"] = 'naf8120ea-11df-45f5-bb4d-1988ad7d7df';
	props["trackingId"] = '5336218803';
	props["trackingPartnerCode"] = '9';
	props["siteId"] = '0';
	props["affiliateUserId"] = 'eric';
	/* 
	 * Place your appId here
	 * props["appId"] = <Your AppID> ;
	 * Place your affiliate information
	 * props["trackingId"] = <Your trackingId>;
	 * props["trackingPartnerCode"] = <Your trackingPartnerCode>;
	 * props["affiliateUserId"] = <Your affiliateUserId>;
	 * Place site id, default is 0 if you don't set
	 * props["siteId"] = <Site ID>; 
	 */
	
	var config = new com.ebay.shoppingservice.ShoppingConfig(props);

	new FindItemsAdvancedModel(config).findItems(queryKeyword,size);
};


