/**
* JavaScript file jquery.yahoo-shopping-search.js v0.1 last modified 11/08/29
*/
var yahoosuggestcallback;
(function(jQuery) {
var settings, self, content, width, developerId, keywords, shoppingTags, control, slider, position, limit, shoppingUl, currentID, cookies, searchControl, deleteButton, autoCompleteResponse;
jQuery.fn.yahooShoppingSearch = function() {
self = this;
var args = jQuery.makeArray(arguments),
options = jQuery.isPlainObject(args[args.length - 1]) ? args.pop() : {};
developerId = args.pop();
keywords = jQuery.trim(args.join(' '));
settings = jQuery.extend({}, jQuery.fn.yahooShoppingSearch.defaults, options);
position = 0;
currentID = 1000;
shoppingTags = [];
cookies = getCookie('shopping-tags');
cookies = cookies != '' ? jQuery.trim(cookies).split(',') : [];
cookies = unique( cookies.concat(settings.defaultKeywords || []) );
return this.each(function() {
jQuery(this)
.append(
content = jQuery('
', { id: 'shopping_content' }).css({ fontSize: settings.baseFontSize })
.append(
jQuery('', { id: 'shopping_top' })
.append( jQuery('', { id: 'shopping_loading', html: '読み込み中……' }) )
.append(
control = jQuery('', { id: 'shopping_search_form' })
.append(jQuery('', { id: 'shopping_label', htmlFor: 'shopping_keyword', html: '追加キーワード ' }))
.append(jQuery('', { id: 'shopping_keyword', name: 'shopping_keyword' }))
)
)
.append(
jQuery('', { id: 'shopping_tags_form' })
.append( shoppingTags[shoppingTags.length] = jQuery('', { 'class': 'shopping_tags' }) )
)
.append( jQuery('', { 'class': 'clear_float' }) )
.append(
jQuery('', { id: 'shopping_showcase' })
.append(
slider = jQuery('', { id: 'shopping_slider' })
.append( shoppingUl = jQuery('') )
)
.append(
jQuery('', { id: 'shopping_slider_left', 'class': 'slider_button', html: '<' })
.button({ disabled: true })
.click(function() {
if (position > 0) {
position--;
shoppingUl.animate({ left: position * -175 });
jQuery('#shopping_slider_right').button('enable');
}
if (position === 0) {
jQuery(this).button('disable');
}
})
)
.append(
jQuery('', { id: 'shopping_slider_right', 'class': 'slider_button', html: '>' })
.button()
.click(function() {
if (position < limit) {
position++;
shoppingUl.animate({ left: position * -175 });
jQuery('#shopping_slider_left').button('enable');
}
if (position == limit) {
jQuery(this).button('disable');
}
})
)
)
);
jQuery('#shopping_slider_left').css({ left: 0, textIndent: '-0.6em' });
jQuery('#shopping_slider_right').css({ left: (content.width() - 18), textIndent: '-0.5em' });
deleteButton = jQuery('', { id: 'delete_shopping_tag', html: 'タグ削除' });
if (cookies.length) {
jQuery.each(cookies, function(index, value) {
addShoppingTag(value);
});
}
requestShoppingInfo(keywords);
jQuery('#shopping_search_form').submit(function(event) {
event.preventDefault();
var value = jQuery('#shopping_keyword').val();
jQuery('#shopping_loading').html('読み込み中……').show();
addShoppingTag(value);
requestShoppingInfo(value);
jQuery('#shopping_keyword').autocomplete('close');
});
deleteButton.button({
icons: { primary: 'ui-icon-closethick' },
text: false
})
.click(function(event) {
event.preventDefault();
var element = jQuery(this).closest('label').prev('input'),
parent = element.parent('div'),
pIndex = parent.index();
if (element.length) {
var v = element.val();
cookies = jQuery.map(cookies, function(value, index) {
if (v == value) return null;
else return value;
});
setCookie('shopping-tags', cookies.join(','), getExpDate(30, 0, 0));
deleteButton.detach();
element.button('destroy')
.next('label').andSelf().remove();
if (!parent.children().length) {
parent.remove();
shoppingTags = jQuery.map(shoppingTags, function(element, index) {
if (index == pIndex) return null;
else return element;
});
}
jQuery('.shopping_tags').buttonset();
}
});
jQuery('#shopping_keyword').autocomplete({
delay: 100,
source: function(request, response) {
autoCompleteResponse = response;
jQuery.ajax({
url: 'http://asprov.search.yahoo.co.jp/AssistSearchService/V2/webassistSearch',
data: {
'p': request.term,
'output': 'iejson',
'callback': 'yahoosuggestcallback'
},
dataType: 'jsonp',
success: function(data, status, xhr) {
//console.log(data, status, xhr);
}
});
},
minLength: 1,
select: function(event, ui) {
var label = ui.item.label;
jQuery('#shopping_loading').html('読み込み中……').show();
addShoppingTag(label);
requestShoppingInfo(label);
},
open: function() {
jQuery( this ).removeClass( 'ui-corner-all' ).addClass( 'ui-corner-top' );
},
close: function() {
jQuery( this ).removeClass( 'ui-corner-top' ).addClass( 'ui-corner-all' );
}
}).focus();
});
};
jQuery.fn.yahooShoppingSearch.defaults = {
defaultKeywords: ['ファッション', '腕時計', 'DVD', 'ゲーム'],
baseFontSize: '12px',
size: 10,
affiliateId: '',
affiliateType: 'yid',
categoryId: 1,
offset: 0,
sort: '-score'
};
yahoosuggestcallback = function (data) {
if (jQuery.isArray(data) && data[1] && autoCompleteResponse) {
autoCompleteResponse(data[1]);
}
};
function requestShoppingInfo(query) {
jQuery.getJSON(
'http://shopping.yahooapis.jp/ShoppingWebService/V1/json/itemSearch?callback=?',
{
'appid': developerId,
'affiliate_type': settings.affiliateType,
'affiliate_id': settings.affiliateId,
'category_id': settings.categoryId,
'offset': settings.offset,
'hits': settings.size,
'sort': settings.sort,
'query': query
},
function(data, status) {
var result, index, item, items = [];
if (status == 'success') {
if (data && data.ResultSet && data.ResultSet.totalResultsReturned > 0 && data.ResultSet[0] && data.ResultSet[0].Result) {
result = data.ResultSet[0].Result;
for (index in result) {
if (result.hasOwnProperty(index) && !isNaN(Number(index))) {
item = result[index];
items[items.length] = {
itemName: item.Name,
catchcopy: item.Headline,
itemCaption: item.Description,
itemPrice: item.Price._value,
itemCode: item.Code,
shopCode: item.Store.id,
taxFlag: item.PriceLabel._attributes.taxIncluded == 'true' ? true : false,
postageFlag: item.Shipping.Code,
reviewCount: item.Review.Count,
itemUrl: item.Url,
imageURL: item.Image.Medium
};
}
}
yahooShoppingSearchComplete(items);
}
else {
jQuery('#shopping_loading').html('商品が見つかりませんでした').show();
}
}
}
);
}
function yahooShoppingSearchComplete(items) {
if (items && items.length > 0) {
jQuery('#shopping_loading').html(items.length + ' 件の商品がヒットしました');
jQuery('#yahoo_credit').remove();
jQuery('div#shopping_slider ul').children().remove();
shoppingUl.css({ left: 0 });
jQuery('#shopping_slider_left').button('disable');
position = 0;
limit = items.length - Math.floor(slider.width() / 175);
if (limit <= 0) {
jQuery('#shopping_slider_right').button('disable');
}
else {
jQuery('#shopping_slider_right').button('enable');
}
var dialog = [], array = [], offsetLeft = 0;
for (var i = 0, l = items.length; i < l; i++) {
var shopping = items[i],
name = shopping.itemName,
catchcopy = shopping.catchcopy,
caption = shopping.itemCaption,
price = shopping.itemPrice.toString(),
code = shopping.itemCode,
shop = shopping.shopCode,
tax = shopping.taxFlag ? '税込' : '税別',
postage = shopping.postageFlag == 2 ? '送料無料' : '送料別',
reviewCount = shopping.reviewCount,
url = shopping.itemUrl,
image = shopping.imageURL,
array = [];
if (name.length > 26) name = name.slice(0, 26) + '...';
while (price.length > 0) {
array[array.length] = price.slice(-3);
price = price.slice(0, -3);
}
price = array.reverse().join(',');
dialog[i] = jQuery('', { 'class': 'shopping_caption' });
content.append(
dialog[i]
.append(
jQuery('')
.append( jQuery('', { href: url, html: shopping.itemName, target: '_blank' }) )
)
.append( jQuery('', { html: catchcopy, css: { color: '#F00' } }) )
.append( jQuery('', { html: caption }) )
);
dialog[i]
.dialog({
autoOpen: false,
title: '商品詳細',
width: 500,
height: 300,
open: function(event, ui) {
jQuery(event.target).find('a').blur();
}
});
shoppingUl.append( shoppingList = jQuery('', { 'class': 'shopping_list' }) );
shoppingList.css({ left: offsetLeft });
offsetLeft += 175;
if (image) {
shoppingList
.append(
jQuery('', { href: url, title: name, target: '_blank' })
.append( jQuery('', { src: image, alt: name }) )
)
.append( jQuery('
') );
}
shoppingList
.append(
jQuery('', { href: url, html: name, data: { index: i }, target: '_blank' })
.mouseover(function() {
//console.log(jQuery(this).data('index'));
})
)
.append(
jQuery('', { 'class': 'shopping_data' })
.append(
jQuery('', { 'class': 'shopping_info', html: '商品詳細', data: { index: i } })
.click(function() {
dialog[jQuery(this).data('index')].dialog('open');
})
)
.append( jQuery('
') )
.append( jQuery('', { html: tax + '/' + postage + ' ' }) )
.append( jQuery('', { 'class': 'shopping_price', html: price + '円' }) )
)
.append( jQuery('', { 'class': 'clear_float' }) );
}
jQuery('').appendTo(content);
}
}
function addShoppingTag(value) {
if (value == '') return;
var radioID = 'shopping_' + currentID,
width = content.width(),
tIndex = -1,
input, label;
input = jQuery('', { id: radioID, name: 'shopping_tags', type: 'radio', value: value });
label = jQuery('', { htmlFor: radioID, html: value })
.click(function() {
jQuery('#shopping_loading').html('読み込み中……').show();
deleteButton.detach();
jQuery(this).children('span').append(deleteButton);
requestShoppingInfo(value);
});
deleteButton.detach();
jQuery.each(shoppingTags, function(index, element) {
element.append(input).append(label);
jQuery('.shopping_tags').buttonset();
if (element.width() + 35 <= width) {
tIndex = index;
return false;
}
input.next().andSelf().detach();
});
if (tIndex == -1) {
jQuery('#shopping_tags_form').append(
shoppingTags[shoppingTags.length] = jQuery('', { 'class': 'shopping_tags' })
.append(input).append(label)
);
jQuery('.shopping_tags').buttonset();
}
cookies.push(value);
cookies = unique(cookies);
setCookie('shopping-tags', cookies.join(','), getExpDate(30, 0, 0));
currentID++;
return radioID;
}
function unique(array) {
var storage = {}, uniqueArray = [], i, value;
for (i = 0; i < array.length; i++) {
value = array[i];
if (!(value in storage)) {
storage[value] = true;
uniqueArray.push(value);
}
}
return uniqueArray;
}
/* クッキー管理用ユーティリティ */
function getExpDate(days, hours, minutes) {
var expDate = new Date();
if (typeof days == 'number' && typeof hours == 'number' && typeof minutes == 'number') {
expDate.setDate(expDate.getDate() + parseInt(days));
expDate.setHours(expDate.getHours() + parseInt(hours));
expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
return expDate.toGMTString();
}
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf(';', offset);
if (endstr == -1) {
endstr = document.cookie.length;
}
return unescape(document.cookie.substring(offset, endstr));
}
function getCookie(name) {
var arg = name + '=';
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal(j);
}
i = document.cookie.indexOf(' ', i) + 1;
if (i === 0) break;
}
return '';
}
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + '=' + escape(value) +
((expires) ? '; expires=' + expires : '') +
((path) ? '; path=' + path : '') +
((domain) ? '; domain=' + domain : '') +
((secure) ? '; secure=' + secure : '');
}
function deleteCookie(name, path, domain) {
if (getCookie(name)) {
document.cookie = name + '=' +
((path) ? '; path=' + path : '') +
((domain) ? '; domain=' + domain : '') +
'; expires=Thu, 01-Jan-70 00:00:01 GMT';
}
}
})(jQuery);