/**
 * @class Item Badge
 * @constructor
 * @param {Object} props include config, keywork, and itemID
 */
function ItemBadgeWidget (props) {
		
    /**
     * config object includes appId, affiliate tracking information, and siteId etc.
     * @type Object
     */
	this.config = props.config;
		
	/**
     * query word.
     * @type String
     */
	this.keyword = props.keyword;
	
	/**
     * item id.
     * @type String
     */
	this.itemID = props.item;
	
	/**
     * error message.
     * @type String
     */
	this.errorMesage = "";
			

	/**
	 * Call GetSingleItem shopping api to get item by itemid;
	 */		
	this.getItem = function () {

		var service = new com.ebay.shoppingservice.Shopping(this.config);
		service.location = "http://open.api.ebay.com/shopping";
		
		var fiRequest = new com.ebay.shoppingservice.GetSingleItemRequestType({itemID: this.itemID, 
			includeSelector: "Details"});	
		var url = service.getSingleItem(fiRequest, {object: this, success: this.displayItem, failure: this.displayError});
				
	};
	
	/**
	 * Call FindItems shopping api to get items by queryKeywords;
	 */		
	this.findItems = function()
	{
    	if (typeof(this.keyword) !== undefined && this.keyword !== "")
    	{			
			var service = new com.ebay.shoppingservice.Shopping(this.config);
			service.location = "http://open.api.ebay.com/shopping";
		
			var fiRequest = new com.ebay.shoppingservice.FindItemsRequestType({queryKeywords: this.keyword, 
				itemSort: com.ebay.shoppingservice.SimpleItemSortCodeType.EndTime,
				maxEntries:10});	
			var url = service.findItems(fiRequest, {object: this, success: this.filterResults,  failure: this.displayError});        
			
    	}
	};

	/**
	 * callback function for processing returned items
	 * @param {com.ebay.shoppingservice.FindItemResponseType} data FindItemsResponse data
	 */	
 	this.filterResults = function(findItemsResponse)
	{   
    	var items = findItemsResponse.item;   
		if(items.length === 0) {
		 	alert("no items found!");
		 	return;
		}   
    	for (i=0;i<items.length;i++)
    	{
        	if (items[i].listingStatus != 'Ended')
        	{
            	this.itemID = items[i].itemID;
            	this.getItem();
            	break;
        	}
    	}
	};
	
	/**
	 * callback function for error handling.
	 * @param {Array} errors error messages (com.ebay.shoppingservice.ErrorType)
	 */	
	this.displayError = function(error) {

		if (!this.errorMesage) {
			this.errorMessage = error[0].longMessage;
		} else {
			this.errorMessage = this.errorMessage + "<br>" + error[0].longMessage;
		}
		
    	var bLyr = document.getElementById('badgeContent');
		
       	bStr = "<table cellpadding='0' cellspacing='0' width='300' height='90'>";
       	bStr = bStr + "<tr><td width='300' colspan='3'><img src='" + imgPath + "tpimg.gif'></td></tr>";
       	bStr = bStr + "<tr><td width='7'><img src='" + imgPath + "ltimg.gif'></td>";
       	bStr = bStr + "<td width='286' background='" + imgPath + "bgwin.gif' align='center'>";
       	bStr = bStr + "<font face='tahoma,arial' size='3' color='#ffffff'>" + this.errorMessage + "</font></td>";
       	bStr = bStr + "<td width='7'><img src='" + imgPath + "rtimg.gif'></td></tr>";
       	bStr = bStr + "<tr><td width='300' colspan='3'><img src='" + imgPath + "btimg.gif'></td></tr></table>";
        
       	bLyr.innerHTML = bStr;    
	}   

	/**
	 * constructing HTML to display item badge
	 * @param {com.ebay.shoppingservice.FindItemResponseType} data FindItemsResponse data
	 */	  
	this.displayItem = function(singleItemResponse)
	{
		var item = singleItemResponse.item;
    	var bNoItem = false;
		var bStr = null;
		if (item === null) {
            bNoItem = true;			
		} else if (item.listingStatus == 'Ended')
    	{
        	if(typeof(this.keyword) != "undefined")
        	{
            	this.findItems();
        	} else {
            	bNoItem = true;
        	}   
    	}
    
    	var bLyr = document.getElementById('badgeContent');
    
    	if (!bNoItem)
    	{
        	var gallery = item.galleryURL;
        	if (typeof(gallery) === undefined) {
            	gallery = image;
			}
            
        	var picture = item.pictureURL;
        	if (typeof(picture) != "undefined")
        	{
            	var loc = picture.toString().search(/[,]/);
            	if (loc > 1) {
                	picture = picture.toString().slice(0,loc);
				}
        	}
        	if (typeof(picture) === undefined) {
            	picture = image;        
			}          
         
        	bStr = "<table cellpadding='0' cellspacing='0' width='300' height='90' onmouseover='showDetails();' onmouseout='hideDetails();'>";
        	bStr = bStr + "<tr height='7'><td width='300' colspan='3' background='" + imgPath + "tpimg.gif' align='center'></td></tr><tr><td width='7' background='" + imgPath + "ltimg.gif' align='center'></td><td width='286' background='" + imgPath + "bgwin.gif'>";
			bStr = bStr + "<table cellpadding='0' cellspacing='0' width='286' height='76'><tr><td width='95' rowspan='2'><img src='" + gallery + "' height='76px' width='95px'></td>";
			bStr = bStr + "<td width='4' rowspan='2'></td><td width='185' height='30' valign='top'><font face='tahoma,arial' size='2' color='#000000' title='" + item.title + "'>" 
			+ eBayUtils.toBreakWord(eBayUtils.truncate(item.title, 29), 15)  + "<br/>item id: " + item.itemID + "</font></td></tr>";
			bStr = bStr + "<tr><td width='185' valign='middle'><font face='tahoma,arial' size='3' color='#000000'><div id='timeLeft'  style='visibility:hidden;'></div><span id='currentPrice'  style=''>Current Price:"
			+ item.convertedCurrentPrice.currencyID + "&nbsp;$" + 
				+  item.convertedCurrentPrice.value.toFixed(2) + "</span></font></td></tr></table></td>";
        	bStr = bStr + "<td width='7' background='" + imgPath + "rtimg.gif'></td></tr><tr height='7'><td width='300' colspan='3' background='" + imgPath + "btimg.gif'></td></tr></table>";
        
        	var dStr = "<div id='detailContent' style='visibility:hidden;position:absolute;'><table cellpadding='0' cellspacing='0' width='248' height='335' border='0' onmouseover='showDetails();' onmouseout='hideDetails();'>";
        	dStr = dStr + "<tr><td colspan='3'><img src='" + imgPath + "hover01.gif'></td></tr><tr><td width='1'><img src='" + imgPath + "1x1.gif' width='1' height='350'></td>";
        	dStr = dStr + "<td  background='" + imgPath + "hoverbg01.gif' height='350' align='center' valign='top'><img src='" + picture + "' height='181px' width='200px'>";
        	dStr = dStr + "<table cellpadding='2' cellspacing='0'><tr><td width='80'><font face='tahoma,arial' size='1' color='#222222'>Starting Bid:</font></td>";
        	dStr = dStr + "<td><font face='tahoma,arial' size='1' color='#222222'><font size='3'>" + item.convertedCurrentPrice.currencyID + "&nbsp;$" + item.convertedCurrentPrice.value.toFixed(2) + "</font></font></td></tr>";
        	dStr = dStr + "<tr><td width='80' valign='top'><font face='tahoma,arial' size='1' color='#222222'>Item location:</font></td>";
        	dStr = dStr + "<td><font face='tahoma,arial' size='1' color='#222222'>" + item.location + "</font></td></tr>";
        	dStr = dStr + "<tr><td width='80'><font face='tahoma,arial' size='1' color='#222222'>Ships to:</font></td>";
        	dStr = dStr + "<td><font face='tahoma,arial' size='1' color='#222222'>" + item.shipToLocations + "</font></td></tr>";
        	dStr = dStr + "<tr><td colspan='2' height='10'><img src='" + imgPath + "1x1.gif' width='205' height='1'></td></tr>";
        	dStr = dStr + "<tr><td width='80'><font face='tahoma,arial' size='1' color='#222222'>Seller: </font></td>";
        	dStr = dStr + "<td><font face='tahoma,arial' size='1' color='#222222'>" + item.seller.userID + "</font></td></tr>";
        	dStr = dStr + "<tr><td width='80'><font face='tahoma,arial' size='1' color='#222222'>Feedback:</font></td>";
        	dStr = dStr + "<td><font face='tahoma,arial' size='1' color='#222222'>" + item.seller.feedbackScore + "</font></td></tr>";
        	dStr = dStr + "<tr><td colspan='2' height='10'><img src='" + imgPath + "1x1.gif' width='205' height='1'></td></tr>";
        	dStr = dStr + "<tr><td width='80'><a href='" + item.viewItemURLForNaturalSearch + "' target='_blank'><img src='" + imgPath + "bidnow.gif' border='0'></a></td><td align='right'><img src='" + imgPath + "ebay.gif'></td></tr>";
        	dStr = dStr + "<tr><td colspan='2' align='center'><font face='tahoma,arial' size='2' color='#104396'><a href='http://developer.ebay.com/developercenter/javascript/widgets/ItemBadge.aspx' target='_blank'>Click here to get this widget</a></font></td></tr>";
        	dStr = dStr + "</table></td><td width='1'><img src='" + imgPath + "1x1.gif' width='1' height='350'></td></tr>";
        	dStr = dStr + "<tr><td colspan='3'><img src='" + imgPath + "hoverbt01.gif'></td></tr></table></div>";
       
        	bLyr.innerHTML = bStr + dStr;   
        
        	//var tl = new cdtime("timeLeft",item.endTime);
        	//tl.display();
        	
        	//this.refreshCurrentPrice(document.getElementById('currentPrice'), item.convertedCurrentPrice);
        	//highlightCurrentPrice(item.convertedCurrentPrice.value.toFixed(2));
        
    	} else {
        
        	bStr = "<table cellpadding='0' cellspacing='0' width='300' height='90'>";
        	bStr = bStr + "<tr><td width='300' colspan='3'><img src='" + imgPath + "tpimg.gif'></td></tr>";
        	bStr = bStr + "<tr><td width='7'><img src='" + imgPath + "ltimg.gif'></td>";
        	bStr = bStr + "<td width='286' background='" + imgPath + "bgwin.gif' align='center'>";
        	bStr = bStr + "<font face='tahoma,arial' size='5' color='#ffffff'>Item is ended</font></td>";
        	bStr = bStr + "<td width='7'><img src='" + imgPath + "rtimg.gif'></td></tr>";
        	bStr = bStr + "<tr><td width='300' colspan='3'><img src='" + imgPath + "btimg.gif'></td></tr></table>";
        
        	bLyr.innerHTML = bStr;    
    	}
	};

		
}

/**
 * static entry function for search 
 * @param {Object} params.g_queryKeywords query key words, params.g_itemID item id.
 */
ItemBadgeWidget.goSearch = function(params)
{
	var item = params.g_itemID;
	var keyword = item ? params.g_backupQueryKeywords: params.g_queryKeywords;

	var props = {};
	props["appId"] = 'eBay3e085-a78c-4080-ac24-a322315e506'; 
	
	/* 
	 * 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);

	if(item) 
	{
		new ItemBadgeWidget({config:config, item: item, keyword: keyword}).getItem();
   	} else {
       	new ItemBadgeWidget({config:config, item: item, keyword: keyword}).findItems();
   	}
};

function resetCurrentPriceColor()
{
   var lyr = document.getElementById('currentPrice');
  	lyr.style.backgroundColor = "";
};

function highlightCurrentPrice(currencyID, price)
{
	var lyr = document.getElementById('currentPrice');
	var lastUpdateStr= "";
	
	lastUpdateStr = "<br> last update: " + new Date().toLocaleTimeString();
	lyr.innerHTML = "Current Price: " + currencyID + "&nbsp;$"  + price + lastUpdateStr ;

   	lyr.style.backgroundColor = "#E46062";
   	setTimeout(resetCurrentPriceColor, 2000);
}

function showDetails()
{
   	var lyr = document.getElementById('detailContent');
   	lyr.style.visibility = "visible";
}

function hideDetails()
{
   	var lyr = document.getElementById('detailContent');
   	lyr.style.visibility = "hidden";    
}


function cdtime(pId, pDate)
{
    if (!document.getElementById || !document.getElementById(pId)){
		 return;
	}
    this.lyr = document.getElementById(pId);
    this.curTime = new Date();
    this.endDate = pDate;
    this.timesUp = false;
    this.updateTime();
}

cdtime.prototype.updateTime = function()
{
    var thisObj = this;
    this.curTime.setSeconds(this.curTime.getSeconds()+1);
    //update time every second
    setTimeout(function(){thisObj.updateTime();}, 1000); 
};

cdtime.prototype.display = function()
{
    this.format = format;
    this.showresults();
};

cdtime.prototype.showresults = function()
{
    var thisObj = this;
    //difference btw target date and current date, in seconds
    var td = (this.endDate-this.curTime)/1000;
    td = td - (this.endDate.getTimezoneOffset()*60);
    //if time is up
    if (td<0){ 
        this.timesUp = true;
    this.lyr.innerHTML = this.format();
    return;
    }
    //minute unit in seconds
    var m = 60; 
    //hour unit in seconds
    var h = 60*60; 
    //day unit in seconds
    var d = 60*60*24; 
    var day = Math.floor(td/d);
    var hour = Math.floor((td-day*d)/h);
    var minute = Math.floor((td-day*d-hour*h)/m);
    var second = Math.floor((td-day*d-hour*h-minute*m));
    this.lyr.innerHTML = this.format(day, hour, minute, second);
    //update results every second
    setTimeout(function(){thisObj.showresults();}, 1000);
};

function format()
{
    var tlStr="";
    var intId;
    //if target date/time not yet met
    if (this.timesUp === false)
    {
        if (arguments[0] > 0){
            tlStr = arguments[0] + "d ";
        }
		if (arguments[1] < 10) {
            tlStr = tlStr + "0" + arguments[1];
        } else  {
            tlStr = tlStr + arguments[1];
        }
		if (arguments[2] < 10) {
            tlStr = tlStr + ":0" + arguments[2];
        } else {
            tlStr = tlStr + ":" + arguments[2];
        }
		if (arguments[3] < 10) {
            tlStr = tlStr + ":0" + arguments[3];
        } else {
            tlStr = tlStr + ":" + arguments[3];
		}
    }
    //else if target date/time met
    else 
    { 
        tlStr = "<font size='5'>Item Ended</font>";
    }
    
    if (arguments[0] > 10) {
        tlStr = "<font size='5'>" + tlStr + "</font>";
    }
    return tlStr;
}

function loadItemBadge(itemID) {
        if (itemID == null)
        {
        	return;
        }
		// replace it with correct path to your images
		// e.g http://mywebsite.com/images/badge/
		imgPath = 'http://w-1.ebay.com/images/';
		image = 'http://w-1.ebay.com/images/stockimage1.jpg';
		//"160000741384"
		ItemBadgeWidget.goSearch({g_itemID: itemID});
	}
	
com.ebay.widgets.needs({
	baseUrl: 'http://w-1.ebay.com/js/2.0/min/',
	files: ['GetSingleItem.js', 'FindItems.js'],
	resources: [].concat(com.ebay.shoppingservice.Shopping.getSingleItem, com.ebay.shoppingservice.Shopping.findItems),
	callback: loadItemBadge
});

/**
 * @class utils functions for ebay samples
 */
function eBayUtils(){}

/**
 * convert date to date string
 * @param {Date} date 
 * @return {String} String of "Month, day, year"
 */
eBayUtils.toDateString = function (date) {
	var thisDate = date ;
	if (thisDate === null) {
		return "";
	}
	var months = [ "January", "February", "March", "April", "May", "June", "July", "August", 
		"September", "October", "November", "December"];
	return months[thisDate.getMonth()] + "," + thisDate.getDate() + " " + thisDate.getFullYear(); 
};
	
/**
 * truncate a string if its length is larger than the specified length 
 * @param {String} str input string 
 * @param {int} len length 
 * @return {String} truncated string
 */
eBayUtils.truncate = function(str, len) {
	if(typeof(str) == "undefined") return "";
	if(str == null) return "";
	if(len <= 0) return str;
	if (str.length > len) {
		return str.substring(0, len - 3) + "...";
	}
	return str.substring(0, len);
}

/**
 * use blank to split a string,
 * if the length of any word in this string is larger than the specified length,
 * then break the word into halves
 * @param {String} str1 input string 
 * @param {int} intLen length 
 * @return {String} string after breaking word
 */
eBayUtils.toBreakWord = function(str1, intLen) {
	if(typeof(str1) == "undefined") return "";
	if (str1 == null) return "";
	if(intLen <= 0) return str1;
	var ss = str1.split(" ");
	var temp = "";
	for(var i in ss) {
		if (typeof(ss[i]) == 'function' ) {
			continue;
		}
		if (ss[i].length > intLen) {
			var middle = parseInt(intLen / 2);
			temp += eBayUtils.breakWord(ss[i], middle) + " ";
		} else {
			temp += ss[i] + " ";
		}
	}
	return temp;
}

/**
 * break the word according to the specified length
 * @param {String} str1 input string 
 * @param {int} intLen length 
 * @return {String} string after breaking word
 */
eBayUtils.breakWord = function(str2, intLen) {
    if(typeof(str2) == "undefined") return "";
	if(str2 == null) return "";
	if(intLen <= 0) return str2;
	var strContent = str2;
	var strTemp = "";
	while(strContent.length>intLen) {
		var subStr = strContent.substr(0, intLen)
		strTemp +=(subStr +" ");
		strContent=strContent.substr(intLen, strContent.length);
	}
	strTemp += strContent;
	return strTemp;
}
