%#encoding: UTF-8%>
// Product autocompletion
image_html = function(item){
return "";
}
format_product_autocomplete = function(item){
var html = "";
var product = item.data['product'];
if(item.data['variant']==undefined){
if(product['images'].length!=0){
html = image_html(product);
}
html += "
" + product['name'] + "
";
if (product['master']) {
html += "" + Spree.translations.sku + ":" + product['master']['sku'] + "";
}
html += "" + Spree.translations.on_hand + ":" + product['count_on_hand'] + "";
}else{
// variant
var variant = item.data['variant'];
var name = item.data.product['name'];
if(variant['images'].length!=0){
html = image_html(variant);
}else{
if(product['images'].length!=0){
html = image_html(product);
}
}
name += " - " + $.map(variant['option_values'], function(option_value){
return option_value["option_type"]["presentation"] + ": " + option_value['presentation'];
}).join(", ")
html += "" + name + "
";
html += "" + Spree.translations.sku + ":" + variant['sku'] + "";
html += "" + Spree.translations.on_hand + ":" + variant['count_on_hand'] + "";
}
return html
}
prep_product_autocomplete_data = function(data){
return $.map(eval(data), function(row) {
var product = row['product'];
if(product['variants'].length>0 && ['expand_variants']){
//variants
return $.map(product['variants'], function(variant){
var name = product['name'];
name += " - " + $.map(variant['option_values'], function(option_value){
return option_value["option_type"]["presentation"] + ": " + option_value['presentation'];
}).join(", ");
return {
data: {product: product, variant: variant},
value: name,
result: name
}
});
}else{
return {
data: {product: product},
value: product['name'],
result: product['name']
}
}
});
}
$.fn.product_autocomplete = function(){
return this.each(function() {
$(this).autocomplete({
source: function(request, response) {
$.get(Spree.routes.product_search + '?' + jQuery.param({ q: $('.product_autocomplete').val(), authenticity_token: encodeURIComponent($('meta[name=csrf-token]').attr("content"))}), function(data) {
result = prep_product_autocomplete_data(data)
response(result);
});
},
minLength: 4,
focus: function(event, ui) {
$('.product_autocomplete').val(ui.item.label);
return false;
},
select: function(event, ui) {
$('.product_autocomplete').val(ui.item.label);
product = ui.item.data;
if (product['variant'] == undefined) {
// product
$('#add_variant_id').val(product['product']['master']['id']);
} else {
// variant
$('#add_variant_id').val(product['variant']['id']);
}
return false;
}
}).data("autocomplete")._renderItem = function(ul, item) {
$(ul).addClass('ac_results');
html = format_product_autocomplete(item);
return $("")
.data("item.autocomplete", item)
.append("" + html + "")
.appendTo(ul);
}
$(this).data("autocomplete")._resizeMenu = function() {
var ul = this.menu.element;
ul.outerWidth(this.element.outerWidth());
}
});
}