//
//  Licensed Materials - Property of IBM
//  5724I83
//  (C) Copyright IBM Corp. 1995, 2008 All Rights Reserved.
//
// ***** DO NOT EDIT THIS FILE *****

utf = new function()
{
    this.unpackUTF16 = function(_str)
    {
        var i, utf16=[];
        for (i=0; i<_str.length; i++)
        {
            utf16[i] = _str.charCodeAt(i);
        }
        return utf16;
    }
    
    this.unpackChar = function(_str) 
    {
        var utf16 = this.unpackUTF16(_str);
        var i,n, tmp = [];
        for (n=i=0; i<utf16.length; i++)
        {
            if (utf16[i]<=0xff) tmp[n++] = utf16[i];
            else {
                tmp[n++] = utf16[i] >> 8;
                tmp[n++] = utf16[i] &  0xff;
            }
        }
        return tmp;
    }
    
    this.packChar  =
    this.packUTF16 = function(_utf16)
    {
        var i, str = "";
        for (i in _utf16)
        {
            str += String.fromCharCode(_utf16[i]);
        }
        return str;
    }

    this.unpackUTF8 = function(_str)
    {
       return this.toUTF8( this.unpackUTF16(_str) );
    }

    this.packUTF8 = function(_utf8)
    {
        return this.packUTF16( this.toUTF16(_utf8) );
    }
    
    this.toUTF8 = function(_utf16)
    {
        var utf8 = [];
        var idx = 0;
        var i, j, c;
        for (i=0; i<_utf16.length; i++)
        {
            c = _utf16[i];
            if (c <= 0x7f)
            {
                utf8[idx++] = c;
            }
            else if (c <= 0x7ff)
            {
                utf8[idx++] = 0xc0 | (c >>> 6 );
                utf8[idx++] = 0x80 | (c & 0x3f);
            }
            else if (c <= 0xffff)
            {
                utf8[idx++] = 0xe0 | (c >>> 12 );
                utf8[idx++] = 0x80 | ((c >>> 6 ) & 0x3f);
                utf8[idx++] = 0x80 | (c & 0x3f);
            }
            else
            {
                j = 4;
                while (c >> (6*j)) j++;
                utf8[idx++] = ((0xff00 >>> j) & 0xff) | (c >>> (6*--j) );
                while (j--) 
                utf8[idx++] = 0x80 | ((c >>> (6*j)) & 0x3f);
            }
        }
        return utf8;
    }
    
    this.toUTF16 = function(_utf8)
    {
        var utf16 = [];
        var idx = 0;
        var i,s;
        for (i=0; i<_utf8.length; i++, idx++)
        {
            if (_utf8[i] <= 0x7f)
            {
                utf16[idx] = _utf8[i];
            }
            else 
            {
                if ( (_utf8[i]>>5) == 0x6)
                {
                    utf16[idx] = ( (_utf8[i] & 0x1f) << 6 )
                                 | ( _utf8[++i] & 0x3f );
                }
                else if ( (_utf8[i]>>4) == 0xe)
                {
                    utf16[idx] = ( (_utf8[i] & 0xf) << 12 )
                                 | ( (_utf8[++i] & 0x3f) << 6 )
                                 | ( _utf8[++i] & 0x3f );
                }
                else
                {
                    s = 1;
                    while (_utf8[i] & (0x20 >>> s) ) s++;
                    utf16[idx] = _utf8[i] & (0x1f >>> s);
                    while (s-->=0) utf16[idx] = (utf16[idx] << 6) ^ (_utf8[++i] & 0x3f);
                }
            }
        }
        return utf16;
    }
    
    this.URLencode = function(_str)
    {
        return _str.replace(/([^a-zA-Z0-9_\-\.])/g, function(_tmp, _c)
            { 
                if (_c == "\x20") return "+";
                var tmp = utf.toUTF8( [_c.charCodeAt(0)] );
                var c = "";
                for (var i in tmp)
                {
                    i = tmp[i].toString(16);
                    if (i.length == 1) i = "0"+ i;
                    c += "%"+ i;
                }
                return c;
            } );
    }

    this.URLdecode = function(_dat)
    {
        _dat = _dat.replace(/\+/g, "\x20");
        _dat = _dat.replace( /%([a-fA-F0-9][a-fA-F0-9])/g, 
                function(_tmp, _hex){ return String.fromCharCode( parseInt(_hex, 16) ) } );
        return this.packChar( this.toUTF16( this.unpackUTF16(_dat) ) );
    }
}//-->

var hpb=new Object();

  hpb.ContentLoader=function(div
        , devId
        , affeId
        , NumOfshowItems
        , apiName
        , keyword
        , strFormat
        , imageType
        , bMediumImage
        , strSort
        , strMinPrice
        , strMaxPrice
        , strCategory
        , strAvailability
        , strPrice
        , strShop
        , nDesMaxLen
        , callBackFuncName
        , nUpdatingInterval
        , nPage) {

  if( this.div != null)
  {
    document.body.removeChild(this.div);
  }							
  this.div = div;
  this.devId = devId;
  this.affeId = affeId;
  this.NumOfshowItems = NumOfshowItems;
  this.paramString = "";
  this.showPrice = true;
  this.postage = true;
  this.showTax = true;
  this.showCaptions = true;
  this.mediamImage = true;
  this.apiName = apiName;
  this.keywordOrd = keyword;
  this.keyword = utf.URLencode(keyword);
  this.request=null;
  this.strFormat = strFormat;
  this.bHorizontal = true;
  if( strFormat == 'vertical')
	this.bHorizontal = false;
  this.imageType = imageType;
  this.bMediumImage = bMediumImage;
  this.nDescriptionMaxLen = nDesMaxLen;
  this.strSort = strSort;
  this.strMinPrice = strMinPrice;
  this.strMaxPrice = strMaxPrice;
  this.strCategory = strCategory;
  this.strAvailability = strAvailability;
  this.strPrice = strPrice;
  this.strShop = strShop;
  this.callBackFuncName = callBackFuncName;
  this.nUpdatingInterval = nUpdatingInterval;
  this.nPage = nPage;
  
  if( strSort != "" && strSort != null) {
    this.paramString += '&sort=' + utf.URLencode(strSort);
  }

  if( strMinPrice != "" && strMinPrice != null) {
    this.paramString += '&minPrice=' + strMinPrice;
  }
  
  if( strMaxPrice != "" && strMaxPrice != null) {
    this.paramString += '&maxPrice=' + strMaxPrice;
  }
  
  if( strCategory != "" && strCategory != null) {
    this.paramString += '&genreId=' + strCategory;
  }

  if( strAvailability != "" && strAvailability != null) {
    this.paramString += '&availability=' + strAvailability;
  }

  this.showAffeliate();
}

var loader;
hpb.ContentLoader.prototype={
  showAffeliate:function(){
    var httpPost = false;
    loader=this;
    var reqString = 'http://api.rakuten.co.jp/rws/1.7/json?'
        + 'developerId=' + this.devId 
        + '&affiliateId=' + this.affeId 
        + '&operation=' + this.apiName 
        + '&version=2007-04-11'
        + '&keyword=' + this.keyword
        + '&callBack=' + this.callBackFuncName
        + '&hits=' + this.NumOfshowItems
        + '&page=' + this.nPage;

    if(this.paramString.length>0)
    {
      reqString += this.paramString;
    }

    var script = document.createElement( 'script' );
    script.type = 'text/javascript';
    script.charset = 'UTF-8';
    script.src = reqString;
    document.getElementsByTagName("head").item(0).appendChild( script );
  }
}	

function getImage(imageFormat, item) {
    var begin;
    var end;
    var strOutput;
    if( imageFormat == 'no')
    {
        return '';
    } else if( imageFormat == 'large') {
        strOutput = '<IMG align="left" class="hpb-affiliate-image" src="' +
            item.mediumImageUrl +
            '" border="0" align="left">';
    } else { // imageFormat == 'small'
        strOutput = '<IMG align="left" class="hpb-affiliate-image" src="' +
            item.smallImageUrl +
            '" border="0">';
    }
    return strOutput;
}

function getName(item) {
    var begin;
    var end;
    var strOutput;
    begin = '<SPAN class="hpb-affiliate-name">';
    end = '</SPAN><BR>';
	
    var strValue = item.itemName;
    
    if( strValue != '')
    {
        strOutput = begin;
        strOutput += strValue;
        strOutput += end;
    }
    return strOutput;
}

function getPrice(item) {
    var begin;
    var end;
    var strOutput = '';
    begin = '<SPAN class="hpb-affiliate-price">';
    end = '</SPAN><BR>';

    var strValue = '';
    if(item!=null){
        if(item.itemPrice!=null && item.itemPrice!=''){
            strValue = item.itemPrice + '円';
        }
        if(item.taxFlag!=null && item.taxFlag=='0'){
            strValue += ' (消費税込)';
        }
    }
    
    if( strValue != '')
    {
        strOutput = begin;
        strOutput += strValue;
        strOutput += end;
    }
    return strOutput;
}

function getShop(item) {
    var begin;
    var end;
    var strOutput = '';
    begin = '<SPAN class="hpb-affiliate-shop">';
    end = '</SPAN><BR>';

    var strValue = '';
    if(item!=null){
        if(item.shopName!=null && item.shopName!=''){
            strValue = item.shopName;
        }
    }
    
    if( strValue != '')
    {
        strOutput = begin;
        strOutput += strValue;
        strOutput += end;
    }
    return strOutput;
}

function getDescription(item, nMaxLen) {
    if( nMaxLen == 0)
    {
        return '';
    }
    var begin;
    var end;
    var strOutput;
    begin = '<SPAN class="hpb-affiliate-description">';
    end = '</SPAN>';
    var strValue = item.itemCaption;

    strOutput = begin;
    if( strValue != '')
    {
        var strTemp = '';
        strTemp = strValue;
        if( strTemp.length > nMaxLen) {
            strTemp	= strTemp.substr( 0, nMaxLen);
            strTemp += '...';
        }
        strOutput +=  strTemp;
    }
    strOutput += end;
    return strOutput;
}

function getText(node) {
    if( node == null)
        return '';
    if (typeof node.textContent != 'undefined') {
        return node.textContent;
    }
    else if (typeof node.innerText != 'undefined') {
        return node.innerText;
    }
    else if (typeof node.text != 'undefined') {
        return node.text;
    }
    else {
        switch (node.nodeType) {
        case 3:
        case 4:
            return node.nodeValue;
            break;
        case 1:
        case 11:
            var innerText = '';
            for (var i = 0; i < node.childNodes.length; i++) {
                innerText += getText(node.childNodes[i]);
            }
            return innerText;
            break;
        default:
            return '';
        }
    }
}

function getJLink(item)
{
    var strValue = item.affiliateUrl;
    var nPos = strValue.indexOf("?");
    if(nPos > 0) {
        strValue = strValue.substring(0, nPos) + "_RTihpb12000002" + strValue.substring(nPos, strValue.length);
    }

    if( strValue != '')
    {
        var strOutput = ' onclick="hpbGoTo(';
        strOutput += "'";
        strOutput += strValue;
        strOutput += "'";
        strOutput += ')"';
        return strOutput;
    }
    return "";
}

function getItem(nItem, item, bHorizontal, imageType, imageFormat, nDesMaxLen, nItemWidth, bPrice, bShop){
  var strItem;
  var itemBegin;
  var itemMid;
  var itemEnd;
  var strWidth = '';
  if(nItemWidth > 0)
      strWidth = ' width="'+ nItemWidth +'"';

  var strOutput;
  if( bHorizontal) {
     itemBegin = '<TD valign="top"' + strWidth ;
     itemMid = '><DIV class="hpb-affiliate-block" style="cursor : pointer;">';
     itemEnd = '</DIV></TD>';
  } else {
     itemBegin = '<TR><TD' + strWidth;
     itemMid = '><DIV class="hpb-affiliate-block" style="height : 100px;cursor : pointer;">';
     itemEnd = '</DIV></TD></TR>';
  }
  
  strItem = itemBegin;
  strItem += getJLink( item);
  strItem += itemMid;
  strItem += getName(item);
  strItem += getImage( imageFormat, item);
  if(bPrice){
    strItem += getPrice(item);
  }
  if(bShop){
    strItem += getShop(item);
  }
  strItem += getDescription(item, nDesMaxLen);
  strItem += itemEnd;
  return strItem;
}

function getCredit(bHorizontal, imageFormat) {
    var strOutput;

    if(imageFormat == 'large') {
        if(bHorizontal) {
            strOutput = '<!-- Rakuten Web Services Attribution Snippet FROM HERE --><a href="http://webservice.rakuten.co.jp/" target="_blank"><img src="http://webservice.rakuten.co.jp/img/credit/200709/credit_31130.gif" border="0" alt="楽天ウェブサービスセンター" title="楽天ウェブサービスセンター" width="311" height="30"/></a><!-- Rakuten Web Services Attribution Snippet TO HERE -->';
        } else {
            strOutput = '<!-- Rakuten Web Services Attribution Snippet FROM HERE --><a href="http://webservice.rakuten.co.jp/" target="_blank"><img src="http://webservice.rakuten.co.jp/img/credit/200709/credit_7052.gif" border="0" alt="楽天ウェブサービスセンター" title="楽天ウェブサービスセンター" width="70" height="52"/></a><!-- Rakuten Web Services Attribution Snippet TO HERE -->';
        }
    } else if(imageFormat == 'small') {
        if(bHorizontal) {
            strOutput = '<!-- Rakuten Web Services Attribution Snippet FROM HERE --><a href="http://webservice.rakuten.co.jp/" target="_blank"><img src="http://webservice.rakuten.co.jp/img/credit/200709/credit_22121.gif" border="0" alt="楽天ウェブサービスセンター" title="楽天ウェブサービスセンター" width="221" height="21"/></a><!-- Rakuten Web Services Attribution Snippet TO HERE -->';
        } else {
            strOutput = '<!-- Rakuten Web Services Attribution Snippet FROM HERE --><a href="http://webservice.rakuten.co.jp/" target="_blank"><img src="http://webservice.rakuten.co.jp/img/credit/200709/credit_4936.gif" border="0" alt="楽天ウェブサービスセンター" title="楽天ウェブサービスセンター" width="49" height="36"/></a><!-- Rakuten Web Services Attribution Snippet TO HERE -->';
        }
    } else {
        strOutput = '<!-- Rakuten Web Services Attribution Snippet FROM HERE --><a href="http://webservice.rakuten.co.jp/" target="_blank">Supported by 楽天ウェブサービス</a><!-- Rakuten Web Services Attribution Snippet TO HERE -->';
    }

    return strOutput;
}

function getStatus(xmlData)
{
    var numberStatusMsgs = xmlData.getElementsByTagName("Status");
    var strStatusMsg = numberStatusMsgs.length > 0 ? numberStatusMsgs[0] : null;
    var strsStatus = getText(strStatusMsg);
    return strsStatus;
}

function getErrorMsg(xmlData)
{
    var numberStatusMsgs = xmlData.getElementsByTagName("StatusMsg");
    var strStatusMsg = numberStatusMsgs.length > 0 ? numberStatusMsgs[0] : null;
    var strMsg = getText(strStatusMsg);
    var strStatus = getStatus(xmlData)
    strMsg = strStatus +' :' +strMsg;
    return strMsg;
}

function showTable(partId, result){
// callback sub function for JSONP 
    try
    {
        var form = document.getElementById(partId);
        if( form == null) return;
        var bHorizontal = true;
        if( form.productformat.value == 'vertical') bHorizontal = false;
        var bMedium = true;
 
        var apiName = form.type.value;
        var retData = null;

        if(apiName == 'ItemSearch') {
            retData = result.Body.ItemSearch;
        } else if(apiName == 'BookSearch') {
            retData = result.Body.BookSearch;
        } else if(apiName == 'CDSearch') {
            retData = result.Body.CDSearch;
        } else if(apiName == 'DVDSearch') {
            retData = result.Body.DVDSearch;
        }

        if (retData == null) return;
        if (retData.Items == null) return;

        var numberItems = retData.Items.Item;
        var len = form.number.value;

        if( numberItems.length == 0) {
            this.div.innerHTML = result.Header.StatusMsg;
            nPage = 1;
            form.page.value = nPage;
            if( form.updatinginterval.value > 0)
            {	
                var nCount = form.updatinginterval.value;
                self.setTimeout('OnRefresh(\"'+partId+'\")', 1000 * nCount);
            }
            return;
        }
        var tableBegin;
        var tableEnd;
        var strOutput;

        if( bHorizontal) {
            tableBegin = '<TABLE border="0"><TBODY><TR>';
            tableEnd = '</TR></TBODY></TABLE>';
        } else {
            tableBegin = '<TABLE border="0"><TBODY>';
            tableEnd = '</TBODY></TABLE>';
        }

        var bPrice = false;
        var bShop = false;
        if(form.showPrice != null && form.showPrice.value=='1'){
             bPrice = true;
        }
        if(form.showShop != null && form.showShop.value=='1'){
             bShop = true;
        }
        strOutput = tableBegin;
        for (i=0; i<len && i<numberItems.length; i++) {
            strOutput += getItem( i, numberItems[i]
                , bHorizontal
                , form.imagetype.value
                , form.imageformat.value
                , form.descriptionmaximum.value
                , form.itemwidth.value
                , bPrice
                , bShop);
        }
        strOutput += tableEnd;

        if(form.showCredit.value == 'true')
            strOutput += getCredit(bHorizontal, form.imageformat.value);
		
        var partdiv=document.getElementById(partId + "_div");
        partdiv.innerHTML = strOutput;
		
        var nPage = eval(retData.page) + 1 ;
        var nTotalPage = eval(retData.pageCount) ;
        if(nPage > nTotalPage || nPage > 100) {
            nPage = 1;
        }
        form.page.value = nPage;

        if( form.updatinginterval.value > 0)
        {	
            var nCount = form.updatinginterval.value;
            self.setTimeout('OnRefresh(\"'+partId+'\")', 1000 * nCount);
        }
        return;
    }
    catch(e)
    {
        var partdiv=document.getElementById(partId + "_div");
        if(partdiv!=null && partdiv.div!=null){
           partdiv.div.innerHTML = e;
        }
        alert(e);
    }
}

function hpbGoTo(strURL) {
    if (strURL != "" ) {
        document.location.href = strURL;
    }
};


function affeliateItems(div, devId, affeId, NumOfshowItems, apiName, keyword, bHorizontal, imageType, bMediumImage, strSort, strMinPrice, strMaxPrice, strCategory, strAvailability, strPrice, strShop, nDesMaxLen, callBackFuncName, nUpdatingInterval, nPage) {
    div.innerHTML = "検索...";
	
    new hpb.ContentLoader(div, devId, affeId, NumOfshowItems, apiName, keyword, bHorizontal, imageType, bMediumImage, strSort, strMinPrice, strMaxPrice, strCategory, strAvailability, strPrice, strShop, nDesMaxLen, callBackFuncName, nUpdatingInterval, nPage);
}

function OnSearchButton(strFormName) {
    var form = document.getElementById(strFormName);
    if( form == null
        || form.page == null
        || form.keyword == null
        || form.keyword.value == ""
        || form.thread == null)
    {
        return;
    }
    form.page.value = 1;  // reset to start page
    form.thread.value = eval(form.thread.value) + 1; // count up thread number
    doSearchNext(strFormName);

    return false;
}

function OnRefresh(strFormName){
    // process for timer refresh
	
    var form = document.getElementById(strFormName);
    if( form == null || form.thread == null) returh;

    if(form.thread.value > 1) { // stop thread over than one thread
       form.thread.value = eval(form.thread.value) -1;
       return;
    }
    doSearchNext(strFormName);
}

function doSearchNext(strFormName){
    var form = document.getElementById(strFormName);
    if( form == null) return;
    if( form.developid == null
        || form.affiliateid == null
        || form.number == null
        || form.type == null
        || form.keyword == null
        || form.productformat == null
        || form.imageformat == null
        || form.imagetype == null
        || form.sort == null
        || form.descriptionmaximum == null
        || form.updatinginterval == null
        || form.page == null
        )
    {
        alert('アフィリエイト部品の設定が正しくありません');
        return;
    }
	
    var div=document.getElementById(strFormName + "_div");
    if( div == null)
    {
        div = document.createElement("div");
        div.setAttribute("id", strFormName + "_div");
        form.appendChild(div);
    }

    var callBackName = "showTable_" + strFormName;

    var strMinPrice = "";
    var strMaxPrice = "";
    var categoryId = "";
    var sAvailability = "";
    var sPrice = "";
    var sShop = "";
    if(form.showShop != null){
        sShop = form.showShop.value;
    }
    if(form.showPrice != null){
        sPrice = form.showPrice.value;
    }
    if(form.availability != null){
        sAvailability = form.availability.value;
    }
    if(form.category_id != null){
        categoryId = form.category_id.value;
    }
    if(form.maxPrice != null){
        strMaxPrice = form.maxPrice.value;
    }
    if(form.minPrice != null){
        strMinPrice = form.minPrice.value;
    }
    if(form.maxPrice != null){
        strMaxPrice = form.maxPrice.value;
    }
    if(form.category_id != null){
        categoryId = form.category_id.value;
    }
    if(form.showShop != null){
        sShop = form.showShop.value;
    }
    if(form.showPrice != null){
        sPrice = form.showPrice.value;
    }
    if(form.availability != null){
        sAvailability = form.availability.value;
    }

    affeliateItems( div
        , form.developid.value
        , form.affiliateid.value
        , form.number.value
        , form.type.value
        , form.keyword.value
        , form.productformat.value
        , form.imageformat.value
        , form.imagetype.value
        , form.sort.value
        , strMinPrice
        , strMaxPrice
        , categoryId
        , sAvailability
        , sPrice
        , sShop
        , form.descriptionmaximum.value
        , callBackName
        , form.updatinginterval.value
        , form.page.value);
}
