//<!--
//1@@w25

/* 
* COPYRIGHT AND LICENCE
* Copyright (C) 2007 eBay Inc. All Rights Reserved.
*
* This library is licensed under the terms of the Common Development 
* and Distribution License ("CDDL").  A copy of the CDDL is included 
* below.
*
* Reference the following two links for more information:
* http://www.sun.com/cddl/
* http://www.opensource.org/licenses/cddl1.php 
*/

/**
 * This represents an ItemService class. It retrieves Items
 * and related information from eBay API server using REST style API 
 * with JSON format using callback.
 * This is the primary class which should be
 * be used by a widget developer to interact with eBay API
 * to get eBay related content.
 * @constructor
 * @param appName   {String} Identifier for the developer/application
 * @param affiliateDetails {AffiliateTrackingDetailsType} 
 *        Used for tracking affiliate information.
 */

function ItemService(appName, affiliateDetails){
    /**
     * Application Developer Name 
     * @type String
     */
    this.appName = appName;
    /**
     * Tracking Details for Affiliate.
     * @type AffiliateTrackingDetailsType
     */
    this.affiliateDetails = affiliateDetails;
    /**
     * Type of Response from eBay API
     * @type String
     */
    this.responseEncodingType="JSON";
    /**
     * eBay API Version.
     * @type int
     */
    this.version = 513;

     /**
     * Calls JSON format REST style eBay API - GetSingleItem
     * with specified detail level.
     * The item is retrieved using item id search criterion
     * and the passed in widget developer callback is asynch
     * ronously invoked with SimpleItemType object, return status
     * and optionally error code. The return status can be used
     * by the caller to detect if there was any error(s), with
     * the actual error details encapsulated in the error object of
     * ErrorType.
     * @param itemID {int} ID of item to search for
     * @param includeSelectors {ArrayStrings} Value for IncludeSelector
     * (governs the read set for Item). Based on this, different
     * attributes of SimpleItemType are populated.
     * @param userCallback {String} Widget developer call back
     */
    this.getItem = function(itemID, 
                            includeSelectors,
                            userCallback) 
    {
           
           // get the URL string to use in the API request
           // URL for IncludeSelector
           var includeURLStr = ItemService._getIncludeSelectorURLString
                                  (includeSelectors);
           
           //construct the full API URL using item id & includeSelector
	   var apiUrl  = ItemService.EBAY_API_BASE_URL+
              ItemService.API_GETSINGLEITEM +"&ItemID="
              +itemID+includeURLStr+this._getStaticURL(userCallback);

          // to use JSON call back with cross domain,
          // inject the API call into the document
          injectScript(apiUrl);   
          
    }
    /**
     * Calls JSON format REST style eBay API - FindItems by Keywords. 
     * Asynchronously gets a list of items
     * , with items containing pertinent affiliate
     * tracking information as specified in the request
     * satisfying keywords search criterion.
     * At some point of time, the browser
     * will invoke the passed in user call back
     * with SearchItemResultType Object
     * @param query {String} Query Keywords search criterion
     * @param maxEntries {int} Number of items to retrieve
     * @param itemSort {String} Specifies how to sort the items
     * @param sortOrder {String} Sort order, ascending/descending
     * @param userCallback {String} Widget developer call back
     */
    this.findItemsByQuery = function(query,
                              maxEntries, 
                              itemSort,
                              sortOrder,
                              userCallback) {
       var itemsCount =  (maxEntries == null)?3:maxEntries;
	 var itemSortStr = (itemSort == null)?"":"&ItemSort="+itemSort;
       var sortOrderStr = (sortOrder == 
               null)?"":"&SortOrder="+sortOrder;
       
       var apiUrl  = ItemService.EBAY_API_BASE_URL+
            ItemService.API_FINDITEMS+"&QueryKeywords="+query.replace(/\s/g,"+")+
            "&MaxEntries="+ itemsCount + itemSortStr + sortOrderStr+    
           ItemService._getAffiliateURLString(this.affiliateDetails) +
           this._getStaticURL(userCallback);

          // inject the API request into the DOM using SRC 
          injectScript(apiUrl);
          
    }
    /**
     * Calls JSON format REST style eBay API - FindItems by Seller. 
     * Asynchronously gets a list of items
     * satisfying keywords search criterion.
     * At some point of time, the browser
     * will invoke the passed in user call back
     * with SearchItemResultType Object
     * @param sellerID{String} Id of the seller who listed the items
     * @param maxEntries {int} Number of items to retrieve
     * @param itemSort {String} Specifies how to sort the items
     * @param sortOrder {String} Sort order, ascending/descending
     * @param userCallback {String} Widget developer call back
     */
    this.findItemsBySellerID = function(sellerID, 
                                  maxEntries,                                           					    itemSort,
                                  sortOrder,
                                  userCallback) 
    {
          
        var itemsCount =  (maxEntries == null)?3:maxEntries;
	  var itemSortStr = (itemSort == null)?"":"&ItemSort="+itemSort;   
        var sortOrderStr = (sortOrder == 
               null)?"":"&SortOrder="+sortOrder;
        var apiUrl  =ItemService.EBAY_API_BASE_URL + 		      ItemService.API_FINDITEMS+
           "&SellerID(0)="+sellerID +
           "&MaxEntries="+ itemsCount + itemSortStr + sortOrderStr+    
           ItemService._getAffiliateURLString(this.affiliateDetails)+
           this._getStaticURL(userCallback);

          // inject the API request into the DOM using SRC 
          injectScript(apiUrl);
    }
          
    /**
     * Calls JSON format REST style eBay API - GetItemStatus.
     * Asynchronously gets statuses of items
     * for the specified item ids.
     * At some point of time, the browser
     * will invoke the passed in user call back
     * with ItemStatusType Object
     * @param itemIDs {Array of ints} IDs of items to retrieve the 
     * status for      
     * @param userCallback {String} Widget developer call back
     */
    this.getItemStatus = function(itemIDs, userCallback) {
          //construct the full API URL using item id
	  var apiUrl  = ItemService.EBAY_API_BASE_URL +ItemService.API_GETITEMSTATUS  
              +ItemService._getItemIDsURLString(itemIDs)+this._getStaticURL(userCallback);

          // inject the API request into the Type using SRC 
          injectScript(apiUrl);
          
    }
    /**
     * Calls JSON format REST style eBay API - GetShippingCosts.
     * Asynchronously gets Shipping Cost details
     * for a item as specified by the item id.
     * At some point of time, the browser
     * will invoke the passed in user call back
     * with ShippingCostSummaryType Object
     * @param itemID {int} ID of item to retrieve the status for
     * @param qtySold {int} Number of items sold to a single buyer and to be shipped together
     * @param destinationPostalCode {String} Destination country postal code (or zipcode, for US)
     * @param destinationCountryCode {String} Destination country code
     * @param includeDetails {boolean}Indicates whether to return the ShippingDetails container in 
     *        the response
     * @param userCallback {String} Widget developer call back
     */
    this.getItemShippingCosts= function(itemID,
                                        qtySold, 
                                        destinationPostalCode, 
                                        destinationCountryCode,
                                        includeDetails,
                                        userCallback) {
          //construct the full API URL using item id
	  var apiUrl  = ItemService.EBAY_API_BASE_URL +ItemService.API_GETSHIPPINGCOSTS 
              +"&ItemID="+itemID+"&QuantitySold="+qtySold
              +"&DestinationPostalCode="+destinationPostalCode
              +"&DestinationCountryCode="+destinationCountryCode
              +"&IncludeDetails="+includeDetails
              +this._getStaticURL(userCallback);

          // inject the API request into the Type using SRC 
          injectScript(apiUrl);
          
    }
   /** 
    * Helper function to construct the common part of API URL
    * @param userCallback {String} Widget Developer call back
    * @private
    */
   this._getStaticURL = function(userCallback){
     return "&appname="+this.appName+"&version="+this.version+
             "&responseencoding="+this.responseEncodingType+
             "&callback=true&MessageID="+userCallback;
   }
}
/** 
 * Helper function to construct an API http requeststring from affiliate tracking detail type object
 * @private
 */
ItemService._getAffiliateURLString = function(affiliateDetails){
  var apiURL= "";
  if (affiliateDetails == null)
     return "";
  if (affiliateDetails.getTrackingID() != null)
     apiURL= apiURL+ "&AffiliateTrackingDetails.TrackingID="
             +affiliateDetails.getTrackingID();
  if (affiliateDetails.getTrackingPartnerCode() != null)
     apiURL= apiURL+ "&AffiliateTrackingDetails.TrackingPartnerCode="
             +affiliateDetail.getTrackingPartnerCode();
  if (affiliateDetails.getApplicationDeviceType() != null)
     apiURL= apiURL+ "&AffiliateTrackingDetails.ApplicationDeviceType="
             +affiliateDetails.getApplicationDeviceType();
  if (affiliateDetails.getTrackingPartnerCode() != null)
     apiURL= apiURL+ "&AffiliateTrackingDetails.AffiliateUserID="
             +affiliateDetails.getAffiliateUserID();
  return apiURL;

}
/** 
 * Helper function to construct an API http request string from an array of IncludeSelectors
 * @private
 */
ItemService._getIncludeSelectorURLString = function(inclSelectors)
{
  var includeSelectorURL = "&IncludeSelector=";
  if ((inclSelectors == null)
      || 
      (inclSelectors == "")
      ||
      (inclSelectors.length == 0)) 
  {
     return "";
  }else{
      var y=0; 
      for (y=0; y<inclSelectors.length; y++)
      {
         // check if the include selector is VALID
     if(inclSelectors[y] != ItemService.INCLUDE_SELECTOR_DEFAULT &&
        inclSelectors[y] != ItemService.INCLUDE_SELECTOR_DETAILS &&
        inclSelectors[y] != ItemService.INCLUDE_SELECTOR_DESCRIPTION &&
        inclSelectors[y] != ItemService.INCLUDE_SELECTOR_ITEM_SPECIFICS)
     {
        throw new Error("Invalid value passed for Include Selector");
     } 
         includeSelectorURL = ((y==0)? "":",")
               + includeSelectorURL + inclSelectors[y] ;
      }
   return includeSelectorURL;
  }
}
/** 
 * Helper function to construct an API http request
 * string from a list of Item IDs
 * @private
 */
ItemService._getItemIDsURLString = function(itemIDs)
{
  var itemsIDsURL = "";
  if ((itemIDs == null)
      || 
      (itemIDs == "")
      ||
      (itemIDs.length == 0)) 
  {
     return "";
  }else{
      var y=0; 
      for (y=0; y<itemIDs.length; y++)
      { 
         itemsIDsURL = "&ItemID("+y+ ")="+itemIDs[y] + itemsIDsURL; 
      }
   return itemsIDsURL;
  }
}
// static constants
/**
 * API call name for retrieving a single item by item id
 * @private
 */
ItemService.API_GETSINGLEITEM = "GetSingleItem";
/**
 * API call name for retrieving items by item id or seller id
 * @private
 */
ItemService.API_FINDITEMS = "FindItems";
/**
 * API call name for retrieving item status by item id
 * @private
 */
ItemService.API_GETITEMSTATUS = "GetItemStatus";
/**
 * API call name for retrieving shipping costs of an item
 * by item id
 * @private
 */
ItemService.API_GETSHIPPINGCOSTS = "GetShippingCosts";
/**
 * eBaY API Base URL
 * @private
 */
ItemService.EBAY_API_BASE_URL = "http://open.api.ebay.com/shopping?callname=";
/**
 * Default count for FindItems API call
 * @private
 */
ItemService.DEFAULT_MAX_ENTRIES = 3;
/**
 * eBaY API GetSingleItem's IncludeSelector's default value 
 * @private
 */
ItemService.INCLUDE_SELECTOR_DEFAULT = "None";
/**
 * eBaY API GetSingleItem's IncludeSelector's details value
 */
ItemService.INCLUDE_SELECTOR_DETAILS = "Details";
/**
 * eBaY API GetSingleItem's IncludeSelector's description value
 */
ItemService.INCLUDE_SELECTOR_DESCRIPTION = "Description";
/**
 * eBaY API GetSingleItem's IncludeSelector's item specifics value
 * 
 */
ItemService.INCLUDE_SELECTOR_ITEM_SPECIFICS = "ItemSpecifics";
/**
 * Constant to denote a successful API call.
 * 
 */
ItemService.CALL_SUCCESS = "Success";
/**
 * Constant to denote a failure during API call.
 */
ItemService.CALL_FAIL = "Fail";
/**
 * eBaY API Item Sort by End Time
 */
ItemService.ITEM_SORT_END_TIME = "EndTime";
/**
 * eBaY API Item Sort by Best Match
 */
ItemService.ITEM_SORT_BEST_MATCH = "BestMatch";
/**
 * eBaY API Sort Order for FindItems
 */
ItemService.SORT_ORDER_ASC = "Ascending";
/**
 * eBaY API Sort Order for FindItems
 */
ItemService.SORT_ORDER_DESC = "Descending";

// eBay API call back which is called when
// API has completed execution. In other words
// it is the response handler.
// it invokes the widget developer call back
// with a SimpleItemType object, return status
// and optionally error object of ErrorType
function _cb_GetSingleItem(_itemJSONObj){
     // check if there was error. if yes create
     // an error and raise one (e.g missing parameter
     // for API call
     var itemObj = null;
     var eBayAPIError = null;
     var retCode = ItemService.CALL_SUCCESS;  
     if (isAPIError(_itemJSONObj)){
        eBayAPIError =APIError.createAPIError(_itemJSONObj.Errors, 
                                     ItemService.getItemAPIName);
        retCode = ItemService.CALL_FAIL;
        
     }
     else{
      itemObj = SimpleItemType.parseItem(_itemJSONObj.Item);
     }
     var returnedUserCallBack = _itemJSONObj.CorrelationID;
     var callback = returnedUserCallBack +"(itemObj, retCode, eBayAPIError)";
     eval(callback);
}

// eBay API call back which is called when
// API has completed execution. In other words
// it is the response handler.
// it invokes the widget developer call back
// with a SearchItemResultType object
function _cb_FindItems(searchItemResultJSONObj){ 
     var searchItemResult = null;
     var eBayAPIError = null;
     var retCode = ItemService.CALL_SUCCESS; 
     if (isAPIError(searchItemResultJSONObj)){
        eBayAPIError = APIError.createAPIError 
        (searchItemResultJSONObj.Errors, ItemService.findItemsAPIName);                                                                       
        retCode = ItemService.CALL_FAIL;
     }
     else{
       searchItemResult = SearchItemResultType.parseSearchItemResult
                 (searchItemResultJSONObj);
     }
     var returnedUserCallBack = searchItemResultJSONObj.CorrelationID;
     var callback = returnedUserCallBack +"(searchItemResult, retCode, eBayAPIError)";
                            
     eval(callback);
}

// eBay API call back which is called when
// API has completed execution. In other words
// it is the response handler.
// it invokes the widget developer call back
// with ItemStatusType object

function _cb_GetItemStatus(itemStatusJSONObj){

     var itemsStatus = null;
     var eBayAPIError = null;
     var retCode = ItemService.CALL_SUCCESS; 
     if (isAPIError(itemStatusJSONObj)){
        g_eBayAPIError =APIError.createAPIError		(itemStatusJSONObj.Errors,                                                                      	 ItemService.findItemsAPIName);
       retCode = ItemService.CALL_FAIL;
     }
     if(itemStatusJSONObj.Item != null && itemStatusJSONObj.Item.length != 0) {
       var y = 0;
       var returnedUserCallBack = itemStatusJSONObj.CorrelationID;
       var callback = returnedUserCallBack +"(itemStatusResult)";
       var itemsStatus = new Array(itemStatusJSONObj.Item.length);
       for (y=0; y < itemStatusJSONObj.Item.length; y++) {
         itemsStatus[y] = ItemStatusType.parseItemStatus(itemStatusJSONObj.Item[y]);
       }
       var callback = returnedUserCallBack +"(itemsStatus, retCode, eBayAPIError)";
       eval(callback);
    }

}
// eBay API call back which is called when
// API has completed execution. In other words
// it is the response handler.
// it invokes the widget developer call back
// with a ShippingCostSummaryType object

function _cb_GetShippingCosts(shippingCostsJSONObj){
     var itemShippingCostsResult = null;
     var eBayAPIError = null;
     var retCode = ItemService.CALL_SUCCESS; 
     if (isAPIError(shippingCostsJSONObj)){
        g_eBayAPIError =APIError.createAPIError(shippingCostsJSONObj.Errors,                                                                 ItemService.API_GETSHIPPINGCOSTS);
        retCode = ItemService.CALL_FAIL;
     }
     else{
       itemShippingCostsResult = ShippingCostsType.parseShippingCosts
                 (shippingCostsJSONObj);


     }

     var returnedUserCallBack = shippingCostsJSONObj.CorrelationID;
     var callback = returnedUserCallBack +"(itemShippingCostsResult, retCode, eBayAPIError)";
     
     eval(callback);
}





//2@@w2
/* 
* COPYRIGHT AND LICENCE
* Copyright (C) 2007 eBay Inc. All Rights Reserved.
*
* This library is licensed under the terms of the Common Development 
* and Distribution License ("CDDL").  A copy of the CDDL is included 
* below.
*
* Reference the following two links for more information:
* http://www.sun.com/cddl/
* http://www.opensource.org/licenses/cddl1.php 
*/
// Constructor -- pass a REST request URL to the constructor
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
   // this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'JscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");
    
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("charset", "utf-8");
     this.scriptObj.setAttribute("src", this.fullUrl);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}

function injectScript(apiUrl){
           aObj = new JSONscriptRequest(apiUrl );
           // Build the script tag
           aObj.buildScriptTag();
          // Execute (add) the script tag
           aObj.addScriptTag();
           //alert("Done injecting URL SRC: "+ apiUrl);
}

// checks if there was any error in 
function isAPIError(ebayAPIJSONObj){
  if (ebayAPIJSONObj.Ack == "Failure"){
     return true;
  }else{
     return false;
  }
}





//3@@w1
/**
 * This represents an ebay API Error Object.  
 * @constructor
 * @param id    {Number}     Unique identifier of the Item.
 */
function APIError(apiName){
  this.callName = apiName;
  this.shortMessage;
  this.longMessage;
  this.errorCode;
  this.severityCode;
  this.errorClassification;
  this.errorParameter;
  
  // setter methods


}
APIError.createAPIError = function(APIErrorsJSONObj, apiName){
   errObject  = new APIError(apiName);

   errObject.shortMessage = APIErrorsJSONObj[0].ShortMessage;
   errObject.longMessage = APIErrorsJSONObj[0].LongMessage;
   errObject.errorCode = APIErrorsJSONObj[0].ErrorCode;
   errObject.severityCode= APIErrorsJSONObj[0].SeverityCode;
   errObject.errorClassification= APIErrorsJSONObj[0].ErrorClassification;
   if (APIErrorsJSONObj[0].ErrorParameters != null){
     errObject.errorParameters =  ErrorParameterType.createErrorParameter(APIErrorsJSONObj[0].ErrorParameters[0]);
   }
   return errObject;
}
/**
 * This represents a Cost Object. More specifically, it is the       
 * of the eBay item's current price, shipping cost and so on
 * to a JavaScript Object. 
 * 
 * @constructor
 * @param id    {Number}     Currency Identifier/Code.
 */
function ErrorParameterType(){
  this.value;
  this.ParamID;

  // getter methods

  this.getValue = function(){
       return this.value;
  }

  this.getParamID = function(){
     return this.paramID;
  }

  // setter methods

  this.setParamID = function(_paramID){
       this.currencyId = _paramID;
  }
  this.setValue = function(_value){
     this.value = _value;
  }
}
ErrorParameterType.createErrorParameter = function(APIErrorParameterJSONObj){
   errParamObject  = new ErrorParameterType();
   errParamObject.setValue(APIErrorParameterJSONObj.Value);
     errParamObject.setParamID(APIErrorParameterJSONObj.ParamID);
  return errParamObject  ;
}


//4@@w6
/**
 * this represents a SimpleItemType Object. More specifically, it is 
 * mapping of the eBay light weight SimpleItemType object returned by 
 * GetSingleItem and FindItems calls. 
 * Note: Not all fields of Item Data Object are populated with values.
 *       Depending on the API return object, certain values will be
 *       populate. Refer to API schema for details. 
 * @constructor
 * @param id    {Number}     Unique identifier of the Item.
 */
function SimpleItemType(id){
  /**
   * Item Identifier.
   * @type int
   */
  this.itemID = id;

  /**
   * Flag to indicate if best offer is enabled.
   * @type boolean
   */
  this.bestOfferEnabled;

  /**
   * For Chinese auction listings, Buy It Now allows a user to purchase the item at 
   * a fixed price and end the auction immediately. 
   */
  this.buyItNowPrice;

  /**
   * Indicates whether an optional hit counter is displayed on the item's listing 
   * page and, if so, what type.
   */
  this.hitCounter;

  /**
   * Description of the item. The Description field is in all listings, 
   * except certain listings that include Pre-filled Item Information.
   */					
  this.description;

  /**
   * Indicates whether, for a Dutch Auction, there is a Buy It Now option.
   * Germany site (site ID 77) and China site (site ID 223) only.
   */
  this.buyItNowAvailable;

  /**
   * Converted value of the BuyItNowPrice in the currency of the site that returned 
   * this response.
   */
  this.convertedBuyItNowPrice;

  /**
   * Time stamp (in GMT) that eBay recorded as the moment that the listing 
   * became available for bidding or buying.
   */
  this.startTime;

  /** 
   * Time stamp (in GMT) when the listing is scheduled to end or the actual end time 
   * if the item has ended.
   */
  this.endTime;

  /**
   * Specifies the selling format used for a listing.
   */
  this.listingType;

  /**
   * Location of the item.
   */
  this.location;

  /**
   * Identifies payment methods used by a buyer to pay a seller.
   */
  this.paymentMethods;

  /**
   * URL for a picture used as the Gallery thumbnail. The image used for the Gallery 
   * thumbnail is in one of the following graphics formats: JPEG, BMP, TIF, or GIF.					
   */
  this.galleryURL;

  /** 
   * Contains the URL for an image associated with the item. Images can be hosted by 
   * eBay Picture Services (EPS) (or by eBay Picture Manager) or they can be self-hosted. 
   */
  this.pictureURL;

  /** 
   * Postal Code of the item. 
   */
  this.postalCode;

  /** 
   * Contains the URL for an image associated with the item. Images can be hosted by 
   * eBay Picture Services (EPS) (or by eBay Picture Manager) or they can be self-hosted. 
   */
  this.primaryCategoryID;

  /** 
   * Contains the URL for an image associated with the item. Images can be hosted by 
   * eBay Picture Services (EPS) (or by eBay Picture Manager) or they can be self-hosted. 
   */
  this.primaryCategoryName;

  /** 
   * Contains the URL for an image associated with the item. Images can be hosted by 
   * eBay Picture Services (EPS) (or by eBay Picture Manager) or they can be self-hosted. 
   */
  this.quantity;

  /** 
   * this URL is optimized to support natural search. This URL is designed to 
   * make items on eBay easier to find via popular Internet search engines.
   * For example, this URL specifies the item title, and it is optimized for natural search:
   * "_W0QQ" is like "?" (question mark),"QQ" is like "&amp;" (ampersand),
   * and "Z" is like "=" (equals sign).You should not modify the query syntax. For example,					   * eBay won't recognize the URL if you change QQ to ?.
   */
  this.viewItemURLForNaturalSearch;

  /** 
   * Contains the URL for an image associated with the item. Images can be hosted by 
   * eBay Picture Services (EPS) (or by eBay Picture Manager) or they can be self-hosted. 
   */
  this.seller;

  /** 
   * Bid count if the item is an auction item and has bids.
   */
  this.bidCount;

  /** 
   * Contains the URL for an image associated with the item. Images can be hosted by 
   * eBay Picture Services (EPS) (or by eBay Picture Manager) or they can be self-hosted. 
   */
  this.convertedCurrentPrice;

  /** 
   * For competitive-bidding listings (Chinese and Dutch auctions), current minimum
   * asking price (start price) or the current highest bid for the item if bids have
   * been placed. 
   */
  this.currentPrice;

  /** 
   * Current Highest Bidder.
   */
  this.highBidder;

  /** 
   * Specifies an active or ended listing's status in eBay's processing workflow.
   */
  this.listingStatus;

  /** 
   * Specifies the number of items sold for given item listing, if any.
   */
  this.quantitySold;

  /** 
   * Indicates if reserve is met.
   */
  this.reserveMet;

  /** 
   * eBay sites (by the country in which each resides) on which a user is registered and 
   * on which items can be listed.   
   */
  this.site;

  /** 
   * Time left before the listing ends. The duration is represented in the ISO 8601 duration 
   * format (PnYnMnDTnHnMnS). For ended listings, the time left is PT0S (zero seconds).
   */
  this.timeLeft;

  /** 
   * Name of the item as it appears in the listing or the Gallery. Required for most items. 
   */
  this.title;

  /** 
   * Name of the item as it appears in the listing or the Gallery. Required for most items. 
   */
  this.shipToLocations;

  /** 
   * Shipping-related details for an item or transaction.
   */
  this.shippingCostSummary;

  /** 
   * Key Value pairs showing item related information. 
   */
  this.itemSpecifics;

  // getter methods
  /**
   * Retrieves Item Identifier.
   * @returns Item's Unique Identifier 
   * @type int
   */
  this.getItemID = function(){
       return this.itemID;
  }

  /**
   * Get the Flag to indicate if best offer is enabled.
   * @returns Boolean flag indicating if best offer is enabled. 
   * @type boolean
   */
  this.getBestOfferEnabled = function(){
       return this.bestOfferEnabled;
  }

  /**
   * Get the the price, which allows a user to purchase the item at 
   * a fixed price and end the auction immediately.
   * @returns Buy It Now Price, price at which the item can be bought. 
   * @type AmountType
   */
  this.getBuyItNowPrice = function(){
       return this.buyItNowPrice;
  }

  /**
   * Get hit counter, which indicates whether an optional hit counter is displayed 
   * on the item's listing page and, if so, what type
   * @returns Type of hit counter for the item's listing page. 
   * @type String
   */
  this.getHitCounter = function(){
       return this.hitCounter;
  }

  /**
   * Gets bid count if the item is an auction item and has bid.
   * @returns Number of bids for an auction item.
   * @type int
   */
  this.getBidCount = function(){
       return this.bidCount;
  }

  /**
   * Gets Description of the item.
   * @returns Description of the item.
   * @type String
   */
  this.getDescription = function(){
       return this.description;
  }

  /**
   * Gets the seller for the item
   * @returns User who listed the item.
   * @type SimpleUserType
   */
  this.getSeller = function(){
     return this.seller;
  }

  /**
   * Gets the boolean flag indicating if the item can be bought
   * at a current fixed price.
   * @returns true or false, depending on if the item can be bought
   *          at a fixed price.
   * @type boolean
   */
  this.getBuyItNowAvailable = function(){
       return this.buyItNowAvailable;
  }

  /**
   * Gets the converted value of the BuyItNowPrice in the currency of the site that returned 
   * this response.
   * @returns The converted value of buy it now price.
   * @type AmountType
   */
  this.getConvertedBuyItNowPrice = function(){
       return this.convertedBuyItNowPrice;
  }

  /**
   * Gets the time when the auction for the item began.
   * @returns The start time of auction of this item
   * @type String
   */
  this.getStartTime = function(){
       return this.startTime;
  }

  /**
   * Gets the time when the auction for the item has ended or scheduled to end.
   * @returns The time when auction is scheduled to end or actually ended.
   * @type String
   */
  this.getEndTime = function(){
     return this.endTime;
  }

  /**
   * Gets the selling format used for a listing.
   * @returns The listing's selling format.
   * @type String
   */
  this.getListingType = function(){
       return this.listingType;
  }

  /**
   * Gets the location of the seller's site at which he/she is registered.
   * @returns The location of the seller
   * @type String
   */
  this.getLocation = function(){
       return this.location;
  }

  /**
   * Gets the payment methods used by a buyer to pay a seller
   * @returns Payment methods used to make payment.
   * @type Array of Strings
   */
  this.getPaymentMethods = function(){
       return this.paymentMethods;
  }

  /**
   * Gets the URL for a picture used as the Gallery thumbnail.
   * @returns URL for a picture used as the Gallery thumbnail.
   * @type String
   */
  this.getGalleryURL = function(){
     return this.galleryURL;
  }

  /**
   * Gets the URL for an image associated with the item. Images can be hosted by 
   * eBay Picture Services (EPS) (or by eBay Picture Manager) or they can be self-hosted. 
   * @returns URL for an image associated with the item.
   * @type String
   */
  this.getPictureURL = function(){
       return this.pictureURL;
  }

  /**
   * Gets the Postal Code.
   * @returns Postal Code associated with the item.
   * @type String
   */
  this.getPostalCode = function(){
       return this.postalCode;
  }

  /**
   * Gets the title of the item
   * @returns Title associated with the item.
   * @type String
   */
  this.getTitle = function(){
     return this.title;
  }

  /**
   * Gets the current minimum asking price (start price) or the
   * current highest bid for the item if bids have been placed. 
   * @returns Current Minimum Asking price or current highest bid for the item.
   * @type AmountType
   */
  this.getCurrentPrice = function(){
     return this.currentPrice;
  }
	
  /**
   * Gets the converted value of the CurrentPrice in the currency of the site that
   * returned this response. For active items, refresh the listing's data every 24
   * hours to pick up the current conversion rates. 
   * @returns Current Minimum Asking price in the current of the response's site.
   * @type AmountType
   */						
  this.getConvertedCurrentPrice = function(){
     return this.convertedCurrentPrice;
  }

  /**
   * Gets the flag which indicates if reserve has been met for the item.
   * @returns true or false depending on whether the reserve has been met for the item.
   * @type boolean
   */
  this.getReserveMet = function(){
     return this.reserveMet;
  }

  /**
   * Gets the eBay site (by the country in which each resides) on which a user is registered and 
   * on which item can be listed.   
   * @returns Site on which item is listed and the seller is registered.
   * @type String
   */
  this.getSite = function(){
     return this.site;
  }

  /**
   * Gets the Time left before the listing ends. The duration is represented in the ISO 8601 duration 
   * format (PnYnMnDTnHnMnS). For ended listings, the time left is PT0S (zero seconds).
   * @returns Time left before the listing or the auction ends.
   * @type String
   */
  this.getTimeLeft = function(){
     return this.timeLeft;
  }

  /**
   * Gets the Item's category id.
   * @returns Category ID of the listed item.
   * @type int
   */
  this.getPrimaryCategoryID = function(){
     return this.primaryCategoryID;
  }

  /**
   * Gets the category for the item.
   * @returns Category Name of the listed item.
   * @type String
   */
  this.getPrimaryCategoryName= function(){
     return this.primaryCategoryName;
  }

  /**
   * Gets the URL that is optimized to support natural search. This URL is designed to make items 
   * on eBay easier to find via popular Internet search engines.					
   * @returns URL that is optimized to support natural search for the item.
   * @type String
   */
  this.getViewItemURLForNaturalSearch= function(){
     return this.viewItemURLForNaturalSearch;
  }

  /**
   * Gets the URL that is optimized to support natural search. This URL is designed to make items 
   * on eBay easier to find via popular Internet search engines.					
   * @returns URL that is optimized to support natural search for the item.
   * @type String
   */
  this.getItemSpecifics = function(){
     return this.itemSpecifics;
  }

  /**
   * Gets the item's listing status.					
   * @returns Status of item's listing.
   * @type String
   */
  this.getListingStatus = function(){
     return this.listingStatus;
  }

  /**
   * Gets the quantity of items sold.					
   * @returns Quantity Sold for this item.
   * @type int
   */
  this.getQuantitySold = function(){
     return this.quantitySold;
  }

  /**
   * Gets the shipping details related to the item.			
   * @returns Shipping Details of the item
   * @type ShippingCostSummaryType
   */
  this.getShipToLocations = function(){
     return this.shipToLocations;
  }

  /**
   * Gets the shipping details related to the item.			
   * @returns Shipping Details of the item
   * @type ShippingCostSummaryType
   */
  this.getShippingCostSummary = function(){
     return this.shippingCostSummary;
  }

  // setter methods

  this.setTitle = function(_title){
     this.title = _title;
  }

  this.setCurrentPrice = function(_currentPrice){
     this.currentPrice = _currentPrice;
  }

  this.setShippingCostSummary = function(_shippingCostSummary){
     this.shippingCostSummary = _shippingCostSummary;
  }

  this.setEndTime = function(_endTime){
     this.endTime = _endTime;
  }

  this.setTimeLeft = function(_timeLeft){
     this.timeLeft= _timeLeft;
  }

  this.setPrimaryCategoryId= function(_primaryCategoryId){
     this.primaryCategoryId = _primaryCategoryId;
  }

  this.setPrimaryCategoryName= function(_primaryCategoryName){
    this.primaryCategoryName = _primaryCategoryName;
  }

  /**
   * Sets the item's listing status.					
   * @param {String} _listingStatus Item Listing's status.
   */
  this.setListingStatus = function(_listingStatus){
     this.listingStatus = _listingStatus;
  }
}
// this function is used to convert a JSON Item object
// to JS SimpleItemType Object.
// It is called in ItemService object in the _cb_GetSingleItem
// method. It is a public method for JS toolkit developer
// but it is not exposed to a widget developer or user of 
// of js toolkit.
/**
 * @private
 */
SimpleItemType.parseItem = function(_itemJSONObj){

     ebayItem = new SimpleItemType(_itemJSONObj.ItemID);
     ebayItem.setTitle(_itemJSONObj.Title);
     ebayItem.endTime = _itemJSONObj.EndTime;
     ebayItem.timeLeft = _itemJSONObj.TimeLeft;
     ebayItem.primaryCategoryID = _itemJSONObj.PrimaryCategoryID;
     ebayItem.primaryCategoryName = _itemJSONObj.PrimaryCategoryName;

     if (_itemJSONObj.BuyItNowPrice!= null){
         ebayItem.buyItNowPrice = AmountType.parseAmount
                 (_itemJSONObj.BuyItNowPrice);
     }
     
     if (_itemJSONObj.CurrentPrice != null){
         ebayItem.setCurrentPrice(AmountType.parseAmount
                 (_itemJSONObj.CurrentPrice));
     }

     if (_itemJSONObj.ConvertedCurrentPrice!= null){
         ebayItem.convertedCurrentPrice = AmountType.parseAmount
                 (_itemJSONObj.ConvertedCurrentPrice);
    }
    
    if (_itemJSONObj.ShippingCostSummary != null){
       ebayItem.setShippingCostSummary(
           ShippingCostSummaryType.parseShippingCostSummary
                (_itemJSONObj.ShippingCostSummary));
    }

    if (_itemJSONObj.Seller!= null){
       ebayItem.seller = SimpleUserType.parseUser(_itemJSONObj.Seller);           
    }

    if (_itemJSONObj.HighBidder != null){
       ebayItem.highBidder = SimpleUserType.parseUser(_itemJSONObj.HighBidder);           
    }

    ebayItem.viewItemURLForNaturalSearch =  _itemJSONObj.ViewItemURLForNaturalSearch;

    ebayItem.galleryURL = _itemJSONObj.GalleryURL;
    ebayItem.pictureURL = _itemJSONObj.PictureURL;
    ebayItem.bidCount = _itemJSONObj.BidCount;
    ebayItem.listingStatus = _itemJSONObj.ListingStatus;
    ebayItem.quantitySold = _itemJSONObj.QuantitySold;
    ebayItem.reserveMet = _itemJSONObj.ReserveMet;
    ebayItem.site = _itemJSONObj.Site;
    ebayItem.postalCode = _itemJSONObj.PostalCode;
    ebayItem.location = _itemJSONObj.Location;
    ebayItem.listingType = _itemJSONObj.ListingType;
    ebayItem.paymentMethods = _itemJSONObj.PaymentMethods;
    ebayItem.description = _itemJSONObj.Description;
    ebayItem.bestOfferEnabled = _itemJSONObj.BestOfferEnabled;
    ebayItem.startTime = _itemJSONObj.StartTime;

    if (_itemJSONObj.ItemSpecifics != null){
       ebayItem.itemSpecifics = NameValueType.parseNameValues(_itemJSONObj.ItemSpecifics.NameValueList);
    }

    if (_itemJSONObj.ShipToLocations != null){
       ebayItem.shipToLocations = _itemJSONObj.ShipToLocations;
    }
    return ebayItem;
}



//5@@w1
/**
 * This represents a name value Object. More specifically, it 
 * is the mapping of the eBay light weight NamevalueType
 * to a JavaScript object. It contains key value paiers
 *
 * 
 * @constructor
 */
function NameValueType(){
  this.name
  this.value;

  // getter methods
  this.getName = function(){
       return this.name;
  }

  this.getValue = function(){
     return this.value;
  }

}
NameValueType.parseNameValue = function(_nameValueJSONObj){

     ebayNameValue= new NameValueType();
 
     ebayNameValue.setName(_nameValueJSONObj.Name);
     ebayNameValue.setValue(_nameValueJSONObj.Value);

     return ebayNameValue;
}
NameValueType.parseNameValues = function(_nameValueListJSONObj){

     var y  = 0;
     var nameValues = new Array(_nameValueListJSONObj.length);
     for (y=0; y < _nameValueListJSONObj.length; y++){
       nameValues[y] =  NameValueType.parseNameValue(_nameValueListJSONObj[y]);
     }
     
     return nameValues;
}

//6@@w1
/**
 * This represents ebay API Amount Type Object.
 * E.g. Current Price of Item is of AmountType type.
 * @constructor
 * @param id    {Number}     Currency Identifier/Code.
 */
function AmountType(id){
  this.currencyID= id;
  this.price;

  // getter methods

  this.getCurrencyID = function(){
       return this.currencyID;
  }

  this.getPrice = function(){
     return this.price;
  }

  // setter methods

  this.setCurrencyID = function(_currencyID){
       this.currencyID = _currencyID;
  }
  this.setPrice = function(price){
     this.price = price;
  }

}

AmountType.parseAmount = function(_amountJSONObj){

     ebayAmount = new AmountType(_amountJSONObj.CurrencyID);
     ebayAmount.setPrice(_amountJSONObj.Value);
  
     return ebayAmount;
}

//7@@w1
/**
 * This represents a simple user JS Object. More specifically, it is the       
 * of the eBay item's data type for high bidder, seller, user
 * 
 * @constructor
 * @param id    {Number}     Currency Identifier/Code.
 */
function SimpleUserType(id){
  this.userID = id;
  this.feedbackPrivate;
  this.feedbackRatingStar;
  this.feedbackScore;
  this.userAnonymized;

  // getter methods

  this.getUserID = function(){
       return this.userID;
  }

  this.getFeedbackPrivate = function(){
     return this.feedbackPrivate;
  }

  this.getFeedbackRatingStar = function(){
     return this.feedbackRatingStar;
  }

  this.getFeedbackScore = function(){
     return this.feedbackScore;
  }

  this.getUserAnonymous = function(){
     return this.userAnonymous;
  }

  // setter methods

}

SimpleUserType.parseUser = function(_userJSONObj){

     ebayUser = new SimpleUserType(_userJSONObj.UserID);
     
     ebayUser.feedbackPrivate = _userJSONObj.FeedbackPrivate ;
     ebayUser.feedbackRatingStar = _userJSONObj.FeedbackRatingStar ;
     ebayUser.feedbackScore = _userJSONObj.FeedbackScore ;
     ebayUser.userAnonymized = _userJSONObj.UserAnonymized;
  
     return ebayUser;
}

//8@@w2
/**
 * This represents shpping information about an item. More
 * specifically, it is the mapping of the eBay light weight 
 * GetShippingDetails response to a JavaScript object. 
 * Note: It refers Cost Object for converted current price.
 *
 * 
 * @constructor
 * 
 */
function ShippingCostSummaryType(){
  this.shippingServiceName;
  this.shippingServiceCost;
  this.insuranceCost;
  this.shippingType;

  // getter methods
  this.getShippingServiceName = function(){
     return this.shippingServiceName;
  }
 
  this.getShippingServiceCost= function(){
     return this.shippingServiceCost;
  }

  this.getInsuranceCost = function(){
     return this.insuranceCost;
  }

  this.getShippingType = function(){
     return this.shippingType;
  }

}

ShippingCostSummaryType.parseShippingCostSummary = function(shippingCostSummaryJSONObj){

     ebayShippingCostSummary = new ShippingCostSummaryType();

     ebayShippingCostSummary.shippingServiceName = shippingCostSummaryJSONObj.ShippingServiceName;

    if (shippingCostSummaryJSONObj.ShippingServiceCost != null){
     ebayShippingCostSummary.shippingServiceCost = AmountType.parseAmount(shippingCostSummaryJSONObj.ShippingServiceCost);
    }

    if (shippingCostSummaryJSONObj.InsuranceCost != null){
     ebayShippingCostSummary.insuranceCost =  AmountType.parseAmount(shippingCostSummaryJSONObj.InsuranceCost);
    }

    ebayShippingCostSummary.shippingType = shippingCostSummaryJSONObj.ShippingType;

    return ebayShippingCostSummary;
}


//9@@w1
/**
 * This represents a Search Item Object. More specifically, it is the           
 * mapping of a list of items returned by eBay light weight 
 * FindItems call to a JavaScript Object. 
 * 
 * @constructor
 */
function SearchItemResultType(){

     this.items = new Array();
     this.totalItems;
     this.itemSearchURL;
	//this.totalPages;
	//this.currentPage;;

     // getter methods
     this.getItems = function(){
        return this.items;
     }

     this.getTotalItems = function(){
        return this.totalItems;
     }

     this.getItemSearchURL = function(){
        return this.itemSearchURL;
     }
     // setter methods

    this.setItems = function(_items){
       this.items = _items;
    }
}
/**
 * This represents a Cost Object. More specifically, it is the       
 * of the eBay item's current price, shipping cost and so on
 * to a JavaScript Object. 
 * 
 * @constructor
 * @param id    {Number}     Currency Identifier/Code.
 */

SearchItemResultType.parseSearchItemResult = function(JSONSearchItemResult){
     var searchItemsResult = new SearchItemResultType();
 
     // if there is no item for the search query, send an empty list
     var jsonItems = JSONSearchItemResult.Item;
     if (jsonItems != null){
   	//  alert("Total number of actual items :" + jsonItems.length);
    	 var itemIndex = 0;
    	 var itemsResults = new Array(jsonItems.length);
    	 for (itemIndex = 0; itemIndex < jsonItems.length; itemIndex++){
     		 ebayItem = SimpleItemType.parseItem(JSONSearchItemResult.Item[itemIndex]);
      	itemsResults[itemIndex] = ebayItem;
       }
       searchItemsResult.items = itemsResults;
       searchItemsResult.totalItems = jsonItems.length;
     }
     else{
        searchItemsResult.totalItems= 0;
        searchItemsResult.items = new Array(0);
     }
     
     return searchItemsResult;
}



//10@@w1
/**
 * This represents an Item Status Object. More specifically, it 
 * is the mapping of the eBay light weight GetItemStatus response 
 * to a JavaScript object. It contains item fields that are usually updated several
  * times during the item lifecycle. 
  * Note: It refers Cost Object for converted current price.
 *
 * 
 * @constructor
 * @param id    {Number}     Unique identifier of the Item.
 */
function ItemStatusType(id){
  this.itemId = id;
  this.buyItNowAvailable;
  this.endTime;
  this.bidCount;
  this.convertedCurrentPrice;
  this.listingStatus;
  this.timeLeft;

  // getter methods
  this.getItemId = function(){
       return this.itemId;
  }

  this.getBuyItNowAvailable = function(){
     return this.buyItNowAvailable;
  }

  this.getBidCount = function(){
     return this.bidCount;
  }

  this.getEndTime = function(){
     return this.endTime;
  }

  this.getTimeLeft = function(){
     return this.timeLeft;
  }

  this.getConvertedCurrentPrice = function(){
     return this.convertedCurrentPrice;
  }

  this.getListingStatus = function(){
     return this.listingStatus;
  }
  
  // setter methods

  this.setItemId = function(_id){
       this.itemId = _id;
  }

  this.setBuyItNowAvailable = function(_buyItNowAvailable){
     this.buyItNowAvailable = _buyItNowAvailable;
  }


  this.setBidCount = function(_bidCount){
     this.bidCount = _bidCount;
  }

  this.setEndTime = function(_endTime){
     this.endTime = _endTime;
  }

  this.setTimeLeft = function(_timeLeft){
     this.timeLeft = _timeLeft;
  }

  this.setConvertedCurrentPrice = function(_convertedCurrentPrice){
     this.convertedCurrentPrice = _convertedCurrentPrice;
  }

  this.setListingStatus = function(_listingStatus){
     this.listingStatus = _listingStatus;
  }

}
ItemStatusType.parseItemStatus = function(_itemStatusJSONObj){

     ebayItemStatus= new ItemStatusType(_itemStatusJSONObj.ItemID);
     ebayItemStatus.setBuyItNowAvailable(_itemStatusJSONObj.BuyItNowAvailable );
     ebayItemStatus.setBidCount(_itemStatusJSONObj.BidCount);
     ebayItemStatus.setEndTime(_itemStatusJSONObj.EndTime);
     ebayItemStatus.setTimeLeft(_itemStatusJSONObj.TimeLeft);
     if(_itemStatusJSONObj.ConvertedCurrentPrice != null){
     	ebayItemStatus.setConvertedCurrentPrice(AmountType.parseAmount(_itemStatusJSONObj.ConvertedCurrentPrice));
     }
     ebayItemStatus.setListingStatus(_itemStatusJSONObj.ListingStatus);

     return ebayItemStatus;
}


//11@@w1
/**
 * This represents a AffiliateTrackingDetailsType Object. More specifically, it is the           
 * Container for fields related to affiliate tracking.  
 * FindItems call to a JavaScript Object. 
 * 
 * @constructor
 */
function AffiliateTrackingDetailsType(){

     this.trackingID;
     this.trackingPartnerCode;
     this.applicationDeviceType;
     this.affiliateUserID;


     // getter methods
     this.getTrackingID = function(){
        return this.trackingID;
     }

     this.getTrackingPartnerCode = function(){
         this.trackingPartnerCode;
     }

     this.getApplicationDeviceType = function(){
        return this.applicationDeviceType;
     }
     // setter methods

    this.getAffiliateUserID = function(){
       return this.affiliateUserID;
    }
}


//12@@w8
var s = document.getElementsByTagName('script');
var sp = s[ s.length - 1 ];
var qs = sp.src.replace(/^[^\?]+\??/,'');

function parseQuery(pQuery) 
{
   var rv = new Object();
   if (!pQuery) return rv;
   var str = pQuery.split(/[;&]/);
   for (var i=0;i < str.length;i++) 
   {
      var kv = str[i].split('=');
      if (!kv || kv.length != 2) continue;
      var k = unescape(kv[0]);
      var v = unescape(kv[1]);
      v = v.replace(/\+/g, ' ');
      rv[k] = v;
   }
   return rv;
}

function parseTimeLeft(pTime) 
{
    var rv = new Object();
    if (!pTime) return rv;
    var str = pTime.replace("T","=date,");
    str = str.replace(".000Z","=time");
    var pv = str.split(/[,]/);
    for (var i=0;i < pv.length;i++)
    {
        var kv = pv[i].split('=');
        var k = unescape(kv[1]);
        var v = unescape(kv[0]);
        v = v.replace(/\+/g,' ');
        rv[k] = v;
    }
    
    var d = rv['date'].split(/[-]/);
    var year = d[0];
    var month = d[1];
    var day = d[2];
    
    var a = new Array();
    a['01'] = "January";
    a['02'] = "February";
    a['03'] = "March";
    a['04'] = "April";
    a['05'] = "May";
    a['06'] = "June";
    a['07'] = "July";
    a['08'] = "August";
    a['09'] = "September";
    a['10'] = "October";
    a['11'] = "November";
    a['12'] = "December";

    var dstr =  a[month] + ' ' + day + ', ' + year + ' ' + rv['time'];
    
    return dstr;  
}

function cdtime(pId, pDate)
{
    var tl = parseTimeLeft(pDate);
    if (!document.getElementById || !document.getElementById(pId)) return;
    this.lyr = document.getElementById(pId);
    this.curTime = new Date();
    this.endDate = new Date(tl);
    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;
}

var bIE;
var browser = navigator.appName;
var ver = navigator.appVersion;
var ver = ver.substring(0,1);
bIE = (browser == "Microsoft Internet Explorer"  && ver <= 5) ? true:false;

function showDetails()
{
    var lyr = document.getElementById('detailContent');
    lyr.style.visibility = "visible";
}

function hideDetails()
{
    var lyr = document.getElementById('detailContent');
    lyr.style.visibility = "hidden";    
}

function swapItems(pId)
{
    var lyr1_t, lyr1_m, lyr2_t, lyr2_m, lyr2_b, lyr3_m, lyr3_b;
        
    lyr1_t = document.getElementById('item1_t');
    lyr1_m = document.getElementById('item1_m');
    lyr2_t = document.getElementById('item2_t');
    lyr2_m = document.getElementById('item2_m');
    lyr2_b = document.getElementById('item2_b');
    lyr3_m = document.getElementById('item3_m');
    lyr3_b = document.getElementById('item3_b');    
    
    if (pId == 'item1_t')
    {
        lyr1_t.style.visibility = "hidden";
        lyr1_m.style.visibility = "visible";
        
        lyr2_t.style.visibility = "hidden";
        lyr2_m.style.visibility = "hidden";         
        lyr2_b.style.visibility = "visible";
        
        if (lyr3_m != null && lyr3_b != null)
        {
            lyr3_m.style.visibility = "hidden";
            lyr3_b.style.visibility = "visible";
        }
    }
    
    if (pId == 'item2_t')
    {
        lyr2_t.style.visibility = "hidden";
        lyr2_m.style.visibility = "visible";
        lyr2_b.style.visibility = "hidden"; 
        
        lyr1_m.style.visibility = "hidden";
        lyr1_t.style.visibility = "visible";
        
        lyr3_m.style.visibility = "hidden";
        lyr3_b.style.visibility = "visible";       
    }
    
    if (pId == 'item2_b')
    {
        lyr2_b.style.visibility = "hidden";
        lyr2_m.style.visibility = "visible";
        lyr2_m.style.top = (bIE) ? '127px':'120px';
        
        lyr1_m.style.visibility = "hidden"; 
        lyr1_t.style.visibility = "visible";       
    } 
    
    if (pId == 'item3_b')
    {
        lyr3_b.style.visibility = "hidden";
        lyr3_m.style.visibility = "visible";
        lyr3_m.style.top = (bIE) ? '238px':'232px';
        
        lyr1_m.style.visibility = "hidden";
        lyr1_t.style.visibility = "visible"; 
        
        lyr2_m.style.visibility = "hidden";
        lyr2_b.style.visibility = "hidden"; 
        lyr2_t.style.visibility = "visible";
        lyr2_t.style.top = (bIE) ? '127px':'120px';             
    }        
}

//13@@w19
// Replace it with your own app id
var g_appID = "eBay3e085-a78c-4080-ac24-a322315e506";
//var g_appID = "ACPapp";

// replace it with correct path to your images
// e.g http://mywebsite.com/images/badge/
var imgPath = 'http://w-1.ebay.com/images/';
var image = 'http://w-1.ebay.com/images/stockimage1.jpg';
var params = parseQuery(qs);
var item = params['g_itemID'];
var keyword = (typeof(item) != "undefined") ? params['g_backupQueryKeywords']:params['g_queryKeywords'];
var pubId = params['g_publisherID'];
var aId = params['g_AID'];


function GetItem()
{
    if (typeof(item) != "undefined" && item != "")
    {
        var itemCaller = new ItemService(g_appID);
        var details = new Array(1);
        details[0] = ItemService.INCLUDE_SELECTOR_DETAILS;
        itemCaller.getItem(item,details,"displayItem");
     } else {
        FindItems();
     }
}
GetItem();

function FindItems()
{
    if (typeof(keyword) != "undefined" && keyword != "")
    {
        var itemCaller = new ItemService(g_appID, null);
        itemCaller.findItemsByQuery(keyword,10,ItemService.ITEM_SORT_END_TIME,null,"filterResults");
    }
}

function filterResults(searchItemsResult)
{   
    var items = searchItemsResult.getItems();   
    for (i=0;i<items.length;i++)
    {
        if (items[i]['listingStatus'] != 'Ended')
        {
            item = items[i]['itemID'];
            GetItem();
            break;
        }
    }
}
     
function displayItem(ItemResult)
{
    var bNoItem = false;
    if (ItemResult.listingStatus == 'Ended')
    {
        if(typeof(keyword) != "undefined")
        {
            FindItems();
        } else {
            bNoItem = true;
        }   
    }
    
    var bLyr = document.getElementById('badgeContent');
    
    if (!bNoItem)
    {
        var gallery = ItemResult.galleryURL;
        if (typeof(gallery) == "undefined")
            gallery = image;
            
        var picture = ItemResult.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;                  
         
        var bStr = "<table cellpadding='0' cellspacing='0' width='300' height='90' onmouseover='showDetails();' onmouseout='hideDetails();'>";
        bStr = bStr + "<tr><td width='300' colspan='3'><img src='" + imgPath + "tpimg.gif'></td></tr><tr><td width='7'><img src='" + imgPath + "ltimg.gif'></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='#ffffff'>" + ItemResult.title + "</font></td></tr>";
        bStr = bStr + "<tr><td width='185' valign='bottom'><font face='tahoma,arial' size='6' color='#ffffff'><span id='timeLeft'></span></font></td></tr></table></td>";
        bStr = bStr + "<td width='7'><img src='" + imgPath + "rtimg.gif'></td></tr><tr><td width='300' colspan='3'><img src='" + 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'>" + ItemResult.getConvertedCurrentPrice().getCurrencyID() + "&nbsp;$" + ItemResult.getConvertedCurrentPrice().getPrice().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'>" + ItemResult.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'>" + ItemResult.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'>" + ItemResult.seller.getUserID() + "</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'>" + ItemResult.seller.getFeedbackScore() + "</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='" + ItemResult.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",ItemResult.endTime);
        tl.display();
        
    } else {
        
        var 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;    
    }
}
// b=4689496 -->