/**
 * @class this function class gets seller's profile and items by seller id from ebay site  
 * using getUserProfile and findItemsAdvanced shopping api,
 * Top 5 items of seller's items are listed 
 * @constructor
 * @param {Object} config includes appId, affiliate tracing information,
 *        and siteId.
 */
function GetUserProfileSample(config)
{

    /**
     * config object includes appId, affiliate tracking information, and siteId etc.
     * @type Object
     */
	this.config = config;
		
    /**
     * seller's profile
     * @type Object
     */
	this.profile = null;

    /**
     * seller's items (top 5)
     * @type Array
     */
	this.items = null;
	
    /**
     * the URL to ebay.com that shows all of this seller's items.
     * @type String
     */
	this.sellerItemsURL = null;

    /**
     * seller's id
     * @type String
     */
	this.userID = null;

    /**
     * div to display seller's profile and items
     * @type Element
     */
	this.div = document.getElementById("userContent");
	
    /**
     * if the call fails
     * @type Boolean
     */
	this.hasError = false;
	
	/**
	 * callback function for processing returned user profile
	 * @param {com.ebay.shoppingservice.GetUserProfileResponseType} data GetUserProfileResponse data
	 */	
	this.getUserProfile = function(data) {
		if (data.user === null) {
			this.displayNoSeller();
		}
		this.profile = this.convertData4ProfileUI(data);
		this.sellerItemsURL = this.getSellerURL(data);
		if (this.profile!==null && this.items!==null ) {
			this.displaySeller();
		}		
	};
	
	/**
	 * callback function for error handling.
	 * show error messages and search input. 
	 * @param {Array} errors error messages (com.ebay.shoppingservice.ErrorType)
	 */		
	this.onCallbackFailed = function(error) {
		
		var src = this.div.innerHTML;		
		if (!this.hasError) {
			this.hasError = true;
			src = "<input id='query' type='text' size='22' maxlength='30'><input onclick='GetUserProfileSample.goSearch()'; type='image' src='http://w-1.ebay.com/images/go.gif'>";
		}
		
		src = "<div>" + error[0].longMessage + "</div>" + src;
		this.div.innerHTML = src; 
	};	

		
	/**
	 * callback function for processing returned items
	 * @param {com.ebay.shoppingservice.FindItemAdvancedResponseType} data FindItemAdvancedRespons data
	 */	
	this.onSomeItemsReturned = function(data) {
		this.items = this.convertData4ItemListUI(data);
		if (this.profile!==null && this.items!==null ) {
			this.displaySeller();
		}		 
	};
		
	/**
	 * call getUserProfile shopping api to get seller's profile 
	 * call findItemsAdvanced shopping api to get seller's items;
	 * @param {String} productID
	 */		
	this.findUser = function(userID) {	
		this.userID = userID;
		// new Shopping service	
		var service = new com.ebay.shoppingservice.Shopping(this.config);

		// new GetUserProfileRequestType
		// IncludeSelector is Details,FeedbackHistory, inlcude feedback history and details.		
		var fiRequest = new com.ebay.shoppingservice.GetUserProfileRequestType({userID: userID, 
			includeSelector: "Details,FeedbackHistory"});	
		// call service function, getUserProfile is callback function on success, and onCallbackFailed is callback function on failure			
		var url = service.getUserProfile(fiRequest, {object: this, success: this.getUserProfile, failure: this.onCallbackFailed});

		// new FindItemsAdvancedRequestType
		// itemSort is EndTime ,sort by endtime.		
		// itemType is AllItemTypes, return all types
		// maxEntries is 5, top 5 items
		var request = new com.ebay.shoppingservice.FindItemsAdvancedRequestType({sellerID: userID, 
			itemSort: com.ebay.shoppingservice.SimpleItemSortCodeType.EndTime,
			itemType: com.ebay.shoppingservice.ItemTypeCodeType.AllItemTypes, 
			maxEntries: 5});			
		// call service function, onSomeItemsReturned is callback function on success, and onCallbackFailed is callback function on failure			
		url = service.findItemsAdvanced(request,{object: this, success: this.onSomeItemsReturned, failure: this.onCallbackFailed});
		
	};

	/**
	 * constructing HTML when no seller is found.
	 * Only display the search input for search again. 
	 */		
	this.displayNoSeller = function() {
		var newLine = "\n";
		var src = "<div id='products' style='float: left;width: 650px;padding: 10px 0;font-family: Arial, sans-serif; font-size: small; border: 1px solid #D9E0E6; background: #edeac9'>" + newLine;
		src = src + "<table width='100%' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		src = src + "<tr><td colspan='2'>" + newLine;
		src = src + this.displaySearch();
		src = src + "</td>" + newLine;	
		src = src + "</tr>" + newLine;
		src = src + "</table>" + newLine;
		src = src + "</div>" + newLine;	
		this.div.innerHTML = src;					
	};
	
	/**
	 * constructing HTML to display seller's profile and items
	 */	
	this.displaySeller = function() {
		var newLine = "\n";
		var src = "<div id='products' style='float: left;width: 650px;padding: 10px 0;font-family: Arial, sans-serif; font-size: small; border: 1px solid #D9E0E6; background: #edeac9'>" + newLine;
		src = src + "<table width='100%' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		src = src + "<tr><td colspan='2' style='font-size: 150%; padding: 4px; font-weight:bold;'>Items for Sale by " + this.userID + ":<br></td></tr>" + newLine;
		src = src + "<tr><td colspan='2'>" + newLine;	
		// display seller's profile, picture, seller id and feedbacks	
		profileSrc = new ProfileUI(this.profile).display();
		src = src + profileSrc;
		src = src + "<tr><td colspan='2'><hr></td></tr>" + newLine;
		src = src + "<tr><td colspan='2' style='font-size: 150%; padding: 4px;'>Top 5 Listings Ending Soon:</td></tr>" + newLine;
		src = src + "<tr><td colspan='2'>" + newLine;
		// display seller's top 5 items
		src = src + (new ItemListUI(this.items, true).display());
		src = src + "</td></tr>" + newLine;
		src = src + "<tr><td colspan='2'><br></td></tr>" + newLine;
		src = src + "<tr><td colspan='2'>" + newLine;
		// display search input
		src = src + this.displaySearch();
		src = src + "</td>" + newLine;	
		src = src + "</tr>" + newLine;
		src = src + "</table>" + newLine;
		src = src + "</div>" + newLine;		
		this.div.innerHTML = src;			
	};

	/**
	 * constructing HTML to display search input
	 * @return {String} constructed HTML
	 */	
	this.displaySearch = function () {
		var newLine = "\n";
		var src = "<table width='100%' cellspacing='0' cellpadding='0' border='0'>" + newLine;
		src = src + "<tr>" + newLine;
		src = src + "<td style='font-size: 150%; padding: 4px;'><a href='" + this.sellerItemsURL + "'>See All Items for this Seller</a></td>" + newLine;
		src = src + "<td style='padding: 0 4px 0 0;' bgcolor='#edeac9' align='right' valign='bottom'>" + newLine;
		src = src +	"<input id='query' type='text' size='22' maxlength='30'><input onclick='GetUserProfileSample.goSearch()'; type='image' src='http://w-1.ebay.com/images/go.gif'>" + newLine;
		src = src + "</td>" + newLine;
		src = src + "</table>" + newLine;
		return src;		
	}	
	/**
	 * get seller url of ebay.com 
	 * @param {com.ebay.shoppingservice.GetUserProfileResponseType} data GetUserProfileResponse data
	 * @return {int} item count
	 */			
	this.getSellerURL = function(data) {
		return data.user.sellerItemsURL;
	};
	
	/**
	 * get datas from com.ebay.shoppingservice.GetUserProfileResponseType to create the object for profile ui.
	 * @param {com.ebay.shoppingservice.GetUserProfileResponseType} data GetUserProfileResponse data
	 * @return {Object} the object for profile ui
	 */			
	this.convertData4ProfileUI = function(data) {
		var args = {};
		var user = data.user;
		if (user.myWorldSamllImage) {
			args.imageURL = user.myWorldSamllImage;
		} else {
			args.imageURL = image;
		}
		var title = {};
		title.value = "Seller: " + user.userID;
		if (user.myWorldURL) {
			title.url = user.myWorldURL;
		} 
		var titles = [];
		titles.push(title);
		args.titles = titles;
				
		var specs = [];
		nameValue = {};
		var score = user.feedbackScore;
		if (data.feedbackHistory) {
			score = data.feedbackHistory.uniqueNegativeFeedbackCount + data.feedbackHistory.uniquePositiveFeedbackCount;
			nameValue = {};
			nameValue.key = "Feedback Count";
			nameValue.value = "<a href='" + user.feedbackDetailsURL + "' >" + score  + "</a>";
			specs.push(nameValue); 
			percentage = (data.feedbackHistory.uniquePositiveFeedbackCount/score* 100.0).toFixed(2) ;			
			nameValue = {};
			nameValue.key = "Positive Feedback Percentage: ";
			nameValue.value = percentage + '%';
			specs.push(nameValue); 
		} else {
			nameValue = {};
			nameValue.key = "Feedback Count";
			nameValue.value = "<a href='" + user.feedbackDetailsURL + "' >" + score  + "</a>";
			specs.push(nameValue); 
		}
		nameValue = {};
		nameValue.key = "Member Since";
		nameValue.value = eBayUtils.toDateString(user.registrationDate);
		specs.push(nameValue); 
		if (user.storeName) {
			nameValue = {};
			nameValue.key = "Store Name";
			if (user.storeURL) {
				nameValue.value = "<a href='" + user.storeURL + "' >" + user.storeName + "</a>";
			} else {
				nameValue.value = user.storeName;
			}
			specs.push(nameValue); 			
		}
		args.specs = specs;
		return args;		
	};

	/**
	 * get datas from com.ebay.shoppingservice.FindItemsAdvancedResponseType to create item array (5 elements).
	 * @param {com.ebay.shoppingservice.FindItemsAdvancedResponseType} data
	 * @return {Array} Array for item list ui, the element is com.bey.shoppingservice.SimpleItemType
	 */			
	this.convertData4ItemListUI = function(data) {
		if (data.searchResult !== null) {
			var itemArray = data.searchResult[0].itemArray;
		}
		var items = [];
		if (itemArray) {			
			var count = itemArray.item.length > 5? 5: itemArray.item.length;			
			for (var i = 0; i< count; ++i) {
				var item = itemArray.item[i];
				items.push(item);
			}
		}
		return items;
	};
}

/**
 * static entry function for search 
 * @param {Object} params.g_userID seller id.
 */
GetUserProfileSample.goSearch = function(params) {
		userID = "";
		var query = document.getElementById('query');
		
		if (query) {
			userID = query.value;
		} else {
			// userId needs to be set in GetUserProfileSample.html
			userID = params.g_userID;				
		}				
			
		// Replace it with your own app id and your affiliate information, you also can change siteid						
		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"] = "eBayAPID-73f4-45f2-b9a3-c8f6388b38d8" ;
		var config = new com.ebay.shoppingservice.ShoppingConfig(props);
		
		new GetUserProfileSample(config).findUser(userID);		
};


