/**
 * 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 FindItemsAdvanced(config)
{
	/**
	 * storing items for each price range
	 * @type Array
	 */
	this.items = new Array(3);
	/**
	 * storing items number for each price range
	 * @type Array
	 */
	this.itemcount = new Array(3);
	/**
	 * keyword for query
	 * @type String
	 */	
	this.queryKeyWords= null;	
	this.dist = 50;
	this.zip  = null;
    /**
     * config object includes appId, affiliate tracking information, etc
     * @type Object
     */
	this.config = config;
	/**
	 * number of errors
	 * @type int
	 */
	this.errorCount = 0;
	
	this.itemSearchURL = null;

	/**
	 * 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='FindItemsAdvanced.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 < 3; i++) {
			if (data.totalItems == 0)
			    return;
			if (this.items == null || this.items[0] == null) {
				return;
			}
			//}
			this.displayItems();
		};
	}
	/**
	 * call findItemsAdvanced shopping api 3 times for each price range
	 * @param {String} queryKeywords
	 */
	this.findItems = function(queryKeywords, zip, dist) {	
		this.queryKeywords = queryKeywords;		
		this.zip = zip;
		this.dist = dist;		
		var service = new com.ebay.shoppingservice.Shopping(this.config);

		var request = this.getFiRequest(); 	
		var callback = new com.ebay.shoppingservice.ShoppingCallback({object: this, success:this.onSomeItemsReturned(0), failure:this.onSomeItemsReturnedFailed});
		url = service.findItemsAdvanced(request,callback);
		
	};
	
	this.getFiRequest = function (){
		var fiRequest = new com.ebay.shoppingservice.FindItemsAdvancedRequestType({	
			itemSort: com.ebay.shoppingservice.SimpleItemSortCodeType.BestMatch,
			//itemSort: com.ebay.shoppingservice.SimpleItemSortCodeType.Distance,
			QueryKeywords: this.queryKeywords,
			itemType: com.ebay.shoppingservice.ItemTypeCodeType.FixedPricedItem,
			//itemType: com.ebay.shoppingservice.ItemFilterType.LocalPickupOnly,
			searchFlag: com.ebay.shoppingservice.SearchFlagCodeType.FreeShipping,
			MaxDistance: this.dist,
			PostalCode:  this.zip,
			IncludeSelector: "SearchDetails",
			maxEntries: 10
			});
		return fiRequest;
		//LocalPickupOnly
		//itemFilter.name   	ItemFilterType  	Optional
	};
	/**
	 * 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.USD, Value: pmax},
			priceMin: {currencyID: com.ebay.shoppingservice.CurrencyCodeType.USD, Value: pmin},
			//itemSort: com.ebay.shoppingservice.SimpleItemSortCodeType.BestMatch,
			itemSort: com.ebay.shoppingservice.SimpleItemSortCodeType.Distance,			
			QueryKeywords: this.queryKeywords,
			itemType: com.ebay.shoppingservice.ItemTypeCodeType.FixedPricedItem,
			MaxDistance: this.dist,
			PostalCode:  this.zip,
			maxEntries: 10
			});
		return fiaRequest;
	};
	/**
	 * construct HTML and display items.
	 */
	this.displayItems = function() {
	
		if (this.items.length <= 0) return;
		
		var dtt = new Date();
		var userDiv = document.getElementById("itemContent");		
		var newLine = "\n";
		//var src = "<div id='products' style='float: left;width: 600px; padding: 10px 0;font-family: Arial, sans-serif; font-size: small; border: 2px solid #D9E0E6; background: #e0e040'>" + newLine;
		var src = "<div id='productsprod'> " + newLine;
		src = src + "<table width='100%' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		//src = src + "<tr><td colspan='4' style='font-size: 100%; padding: 4px; font-weight:bold;'>" + this.itemcount[0] + " items available from eBay for \"" + this.queryKeywords + "\"<br></td></tr>" + newLine;		
		src = src + "<tr><td colspan='4'>" + newLine;

		//src = src + "<table style='padding: 3px 3px 3px 3px; background: #efefff;' width='99%' cellspacing='0' cellpadding='1'  >" + newLine;
		src = src + "<table style='padding: 3px 3px 3px 3px;' width='99%' cellspacing='0' cellpadding='1'  >" + newLine;
		////src = src + "<table width='100%' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		src = src + "<tr style='background: #f0f0f0; font-family: Calibri; font-weight:bold;'> " + newLine;
		//<hr style='color:#c0c0c0;background-color: #c0c0c0;height: 1px;'>
		src = src + "<td style='border-top:1px solid #c0c0c0;'><strong>If you didn't find what you're looking for on Kijiji, please take a look at these items from eBay</strong></td>";
		src = src + "<td style='border-top:1px solid #c0c0c0;'><strong><a href='";
		src = src + "http://altfarm.mediaplex.com/ad/ck/10302-82987-2357-1?mpt="+dtt.getTime()+"&mpro="+this.itemSearchURL;
		src = src + "' Target='_new'>See more on eBay</a><img src='http://altfarm.mediaplex.com/ad/tr/10302-82987-2357-1?mpt="+dtt.getTime()+"' border='0'></td>";
		src = src + "</tr>" + newLine;
		src = src + "<td colspan='3' style='border-top:1px solid #c0c0c0;'>&nbsp;</td>";
		src = src + "</tr>" + newLine;
		
		//“If you didn’t find you’re looking for on Kijiji, please take a look at these items from
		//for (var i= 0; i< 3; i++) {
			//src = src + "<tr><td colspan='2' style='font-size: 150%; padding: 4px;'>" + " (" + this.itemcount[0] + " items found):</td></tr>" + newLine;
			src = src + "<tr><td colspan='2'>" + newLine;
			src = src + (new ItemListUI(this.items[0], 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='100%' 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='FindItemsAdvanced.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 + "</tr>" + newLine;
		
		src = src + "<tr style='background: #f0f0f0; font-family: Calibri; font-weight:bold;'> " + newLine;
		src = src + "<td colspan='4' style='border-top:1px solid #c0c0c0;'>&nbsp;</td>";		
		src = src + "</tr>" + newLine;
		
		src = src + "</table>" + 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;
			this.itemSearchURL = data.itemSearchURL;
		}
		var items = [];
		if (itemArray) {			
			var count = itemArray.item.length ;

			var i = 0;
			while (items.length < 5 && i < count) {
			//while (items.length < 1 && 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
 */
FindItemsAdvanced.goSearch = function(params) {				
	queryKeyword = null;
	//var query = document.getElementById('query');
	//if (query) {
//		queryKeyword = query.value;
	//}			

	if (queryKeyword === null && params) {
		queryKeyword = params.g_queryKeyword;
	}
	
	dist = params.g_dist;
	zip  = params.g_zip;

	var props = {};
	/* 
	 * 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>; 
	 */
	props["appId"] = "kijiji666-ef76-4667-88ff-048e2c3ef9a" ;
	var config = new com.ebay.shoppingservice.ShoppingConfig(props);

	new FindItemsAdvanced(config).findItems(queryKeyword, zip, dist);
};

