aboutsummaryrefslogtreecommitdiffstats
path: root/public/admin/view/template/extension/openbay/amazon_listing_advanced.twig
blob: 13a5d0608a264af3de1ae8ebd17470052124e5a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
{{ header }}{{ column_left }}
<div id="content">
  <div class="page-header">
    <div class="container-fluid">
      <div class="pull-right">
        {% if has_listing_errors %}
        <a href="{{ url_remove_errors }}" data-toggle="tooltip" title="{{ button_remove_error }}" class="btn btn-danger"><i class="fa fa-reply"></i></a>
        {% endif %}
        <a href="{{ cancel_url }}" data-toggle="tooltip" title="{{ button_cancel }}" class="btn btn-default"><i class="fa fa-reply"></i></a> </div>
      <h1>{{ text_title_advanced }}</h1>
      <ul class="breadcrumb">
        {% for breadcrumb in breadcrumbs %}
        <li><a href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a></li>
        {% endfor %}
      </ul>
    </div>
  </div>
  <div class="container-fluid">
    {% if errors %}
    <div class="alert alert-danger alert-dismissible">
      <ul>
        {% for listing_error in errors %}
        <li><i class="fa fa-exclamation-circle"></i> {{ listing_error.message }}</li>
        {% endfor %}
      </ul>
    </div>
    {% endif %}
    {% if success %}
    <div class="alert alert-success alert-dismissible"><i class="fa fa-check-circle"></i> {{ success }}</div>
    {% endif %}
    <ul class="nav nav-tabs" id="tabs">
      <li class="active"><a href="#page-main" data-toggle="tab">{{ tab_main }}</a></li>
    </ul>
    <form method="POST" id="product_form_advanced" class="form-horizontal">
      <input type="hidden" name="upload_after" value="false">
      <div class="tab-content" id="tab-content">
        <div class="tab-pane active" id="page-main">
          <div class="form-group">
            <label class="col-sm-2 control-label">{{ entry_product }}</label>
            <div class="col-sm-10">
              <p><a href="{{ listing_url }}">{{ listing_name }}{% if options is not empty %} : {% endif %}</a>
                {% if options %}
                <select id="openstock_selector" name="optionVar" class="form-control">
                  {% set option_selected = false %}
                  {% for option in options %}
                    {% if option.sku is not empty %}
                      <option value="{{ option.sku }}"{% if variation == option.sku %} selected{% set option_selected = true %}{% endif %}>{{ option.combination }}</option>
                    {% endif %}
                  {% endfor %}
                  {% if option_selected == false %}
                    <option selected="selected"></option>
                  {% endif %}
                </select>
                {% endif %}
              </p>
            </div>
          </div>
          <div class="form-group">
            <label class="col-sm-2 control-label">{{ entry_marketplace }}</label>
            <div class="col-sm-10" id="marketplaces">
              {% for mp in marketplaces %}
                <label class="radio-inline">
                  {% if saved_marketplaces == false %}
                    <input class="marketplace_ids" id="adv_marketplace_{{ mp.code }}" {% if mp.id in default_marketplaces %} checked="checked" {% endif %} type="radio" name="marketplace_ids[]" value="{{ mp.id }}">
                  {% else %}
                    <input class="marketplace_ids" id="adv_marketplace_{{ mp.code }}" {% if mp.id in saved_marketplaces %} checked="checked" {% endif %} type="radio" name="marketplace_ids[]" value="{{ mp.id }}">
                  {% endif %}
                {{ mp.name }}</label>
              {% endfor %}
            </div>
          </div>
          <div class="form-group required">
            <label class="col-sm-2 control-label" for="category_selector" id="category_selector_label">{{ entry_category }}</label>
            <div class="col-sm-4">
              <select name="category_selector" id="category_selector" class="form-control">
                <option value=""></option>
                {% for category in amazon_categories %}
                <option value="{{ category.template }}"{% if edit_product_category == category.name %} selected{% endif %}>{{ category.friendly_name }}</option>
                {% endfor %}
              </select>
            </div>
          </div>
          <table class="table table-bordered table-hover">
            <tbody class="fields_advanced">
            </tbody>
          </table>
        </div>
      </div>
      <div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" id="browse-node-modal">
        <div class="modal-dialog modal-lg">
          <div class="modal-content">
            <div class="modal-header">
              <button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button>
              <h4 id="mySmallModalLabel" class="modal-title">{{ entry_browse_node }}</h4>
            </div>
            <div class="modal-body">
              <div id="browse-node-content"></div>
            </div>
          </div>
        </div>
      </div>
    </form>
    <div class="well">
      <div class="row">
        <div class="col-md-12 text-right"> <a class="btn btn-primary" data-toggle="tooltip" title="{{ button_save }}" onclick="validate_and_save('advanced')"><i class="fa fa-save fa-lg"></i></a> <a class="btn btn-primary" data-toggle="tooltip" title="{{ button_save_upload }}" onclick="save_and_upload()"><i class="fa fa-cloud-upload fa-lg"></i></a> <a class="btn btn-primary" data-toggle="tooltip" title="{{ button_saved_listings }}" href="{{ saved_listings_url }}"><i class="fa fa-copy fa-lg"></i></a> </div>
      </div>
    </div>
  </div>
</div>
<script type="text/javascript"><!--
$(document).ready(function(){
    $('#openstock_selector').change(function() {
        redirectOption($('#openstock_selector').val(), 'advanced');
    });

    {% if not amazon_categories %}
        $("#advanced_table").html("");
        $(".content").prepend('<div id="warning" class="alert alert-danger">{{ error_connecting }}</div>');
        return;
    {% endif %}

    $(".fields_advanced :input").bind('change', function() {
        update_form(this, 'advanced');
    });

    $('#category_selector').change(function(){
        var xml = $('#category_selector').val();
        if (xml == '') {
            $('.fields_advanced').empty();
            $('.dynamic-tab').remove();
            $('.dynamic-page').remove();
            return;
        }
        show_form(xml, 'advanced');
    });
    //Update needed if editing
    $('#category_selector').change();
    $('#product_form_advanced input[name=upload_after]').val(false);

});

function redirectOption(varOption, tabOption) {
    var searchLoc = insertParamToUrl(document.location.search, 'sku', varOption);
    searchLoc = insertParamToUrl(searchLoc, 'tab', tabOption);
    searchLoc = searchLoc.substr(1);
    if (document.location.search === searchLoc) {
        return false;
    } else {
        document.location.search = searchLoc;
        return true;
    }
}

function insertParamToUrl(searchLoc, key, value) {
    var kvp = searchLoc.split('&');

    if (kvp == '') {
        searchLoc = '?' + key + '=' + value;
        return searchLoc;
    }
    else {
        var i = kvp.length; var x; while (i--) {
            x = kvp[i].split('=');
            if (x[0] == key) {
                if (x[1] == value) {
                    return searchLoc;
                }
                x[1] = value;
                kvp[i] = x.join('=');
                break;
            }
        }
        if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
        return kvp.join('&');
    }
}

var fieldsArray = new Array();

function show_form(xml, formType) {
    $('.fields_' + formType).empty();
    $('.dynamic-tab').remove();
    $('.dynamic-page').remove();

    var parserURL = '{{ template_parser_url }}';
    var reqUrl = parserURL + '&xml=' + xml;

    if ($('#openstock_selector').val() !== undefined) {
        reqUrl = reqUrl + '&sku=' + $('#openstock_selector').val();
    }

    $.ajax({
        url: reqUrl,
        data: {},
        dataType: 'json',
        beforeSend: function() {
            $('#category_selector').attr('disabled', 'disabled');
            $('#category_selector_label').after('<a class="btn btn-primary wait" disabled="disabled"><i class="fa fa-cog fa-lg fa-spin"></i> </a>');
        },
        complete: function() {
            $('#category_selector').removeAttr('disabled');
            $('.wait').remove();
        },
        success: function(data) {
            if (data['status'] === 'error') {
                if ('info' in data) {
                    alert(data['info']);
                } else {
                    alert('Unexpected error.');
                }
                return;
            }
            for(tab in data['tabs']) {
                $('#tabs').append('<li class="dynamic-tab"><a href="#page-' + data['tabs'][tab]['id'] + '" data-toggle="tab">' + data['tabs'][tab]['name'] + '</a></li>');

                var pageHtml = '';
                pageHtml += '<div id="page-' + data['tabs'][tab]['id'] + '" class="tab-pane dynamic-page">';
                  pageHtml += '<div class="fields_advanced"></div>';
                pageHtml += '</div>'

                $('#tab-content').append(pageHtml);
            }

            var categoryName = data['category'];
            fieldsArray[formType] = data['fields'];

            $('.fields_' + formType).append('<input type="hidden" name="category" value="' + categoryName + '">');

            for (i in fieldsArray[formType]) {
              var row  = '<div class="form-group';


              if (fieldsArray[formType][i]['type'] == 'required') {
                row += ' required';
              }

              if (fieldsArray[formType][i]['child']){
                  row += ' child_row" display="no" field_index="' + i + '" style="display: none">';
              } else {
                  row += '">';
              }

              row += '<label class="col-sm-2 control-label">'+fieldsArray[formType][i]['title']+'</label>';
              row += '<div class="col-sm-10">';

              row += '<div class="alert alert-danger" id="error_' + fieldsArray[formType][i]['name'] + '" style="display:none;"></div>'

              if (fieldsArray[formType][i]['name'] == "Quantity") {
                  row += getQuantityField(fieldsArray[formType][i]);
              } else if (fieldsArray[formType][i]['accepted']['type'] == "integer") {
                if (fieldsArray[formType][i]['name'] == 'RecommendedBrowseNode' || fieldsArray[formType][i]['name'] == 'RecommendedBrowseNode2'){
                  row += getBrowseNodeField(fieldsArray[formType][i]);
                } else {
                  row += getIntegerField(fieldsArray[formType][i]);
                }
              }
              else if (fieldsArray[formType][i]['accepted']['type'] == "text_area") {
                  row += getTextAreaField(fieldsArray[formType][i]);
              }
              else if (fieldsArray[formType][i]['accepted']['type'] == "select") {
                  row += getSelectField(fieldsArray[formType][i]);
              }
              else if (fieldsArray[formType][i]['accepted']['type'] == "image") {
                  row += getImageField(fieldsArray[formType][i]);
              }
              else {
                  row += getStringField(fieldsArray[formType][i]);
              }

              if (fieldsArray[formType][i]['definition']) {
                row += '<span class="help-block">' + fieldsArray[formType][i]['definition'] + '</span>';
              }

              row += '</div>';
              row += '</div>';

              $('#page-' + fieldsArray[formType][i]['tab'] + ' .fields_' + formType).append(row);
            }

            //Emulate changes to populate child fields
            $('.fields_' + formType + ' :input').each(function (i) {
                $(this).change();
            });
        },
        error: function (xhr, ajaxOptions, thrownError) {
        if (xhr.status != 0) { alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText); }
      }
    });
}

//Called when chenge to form was made. Shows child rows bassed on input if needed.
function update_form(element, formType) {
    var changedFieldName = $(element).attr('field_name');
    var changedFieldValue = $(element).val();

    $('.fields_' + formType + ' .child_row').each(function (i) {
        var index = $(this).attr('field_index');
        if (fieldsArray[formType][index]['parent']['name'] == changedFieldName) {
            var showChild = false;

            //values is array?
            if (fieldsArray[formType][index]['parent']['value'] instanceof Array) {
                for(i in fieldsArray[formType][index]['parent']['value']) {
                    if (fieldsArray[formType][index]['parent']['value'][i] == changedFieldValue) {
                        showChild = true;
                    }
                }
            } else if (fieldsArray[formType][index]['parent']['value'] == changedFieldValue) {
                showChild = true;
            } else if (fieldsArray[formType][index]['parent']['value'] == '*' && changedFieldValue != '') {
                showChild = true;
            }

            if (showChild) {
                $(this).attr('display', 'yes');
                $(this).removeAttr('style');
            } else {
                $('.fields_' + formType + ' [field_name="' + fieldsArray[formType][index]['name']  + '"]').val('');
                $(this).attr('display', 'no');
                $(this).attr('style', 'display: none');
            }
        }
    });
}

function getImageField(fieldData) {
  var output = "";

  output += '<a class="img-thumbnail img-edit" id="thumb-image-'+fieldData['name']+'">';
    if (fieldData['thumb'] != "") {
      output += '<img src="'+fieldData['thumb']+'" alt="" title="" />';
    } else {
      output += '<i class="fa fa-camera fa-5x"></i>';
    }
  output += "</a>";
  output += '<input type="hidden" id="input-image-'+fieldData['name']+'" name="fields[' + fieldData['name'] + ']" value="' + fieldData['value'] + '" accepted="' + fieldData['accepted']['type'] + '" field_name="' + fieldData['name'] + '" field_type="' + fieldData['type'] + '">';

  return output;
}

function getQuantityField(fieldData) {
    var output = "";

    output += fieldData['value'];
    output += '<input ';
    output += 'type="hidden" ';
    output += 'min="0" ';
    output += 'accepted="' + fieldData['accepted']['type'] + '" ';
    output += 'field_name="' + fieldData['name'] + '" ';
    output += 'field_type="' + fieldData['type'] + '" ';
    output += 'name="fields[' + fieldData['name'] + ']" ';
    output += 'value="' + fieldData['value'] + '" class="form-control">';

    return output;
}

function getIntegerField(fieldData) {
  var output = "";

  output += '<input ';
  output += 'type="number" ';
  output += 'min="0" ';
  output += 'accepted="' + fieldData['accepted']['type'] + '" ';
  output += 'field_name="' + fieldData['name'] + '" ';
  output += 'field_type="' + fieldData['type'] + '" ';
  output += 'name="fields[' + fieldData['name'] + ']" ';
  output += 'class="form-control" ';
  output += 'value="' + fieldData['value'] + '">';

  return output;
}

function getBrowseNodeField(fieldData) {
  var output = "";

  output += '<div class="input-group col-md-3">';
  output += '<input ';
  output += 'id="'+fieldData['name']+'_input" ';
  output += 'type="number" ';
  output += 'min="0" ';
  output += 'accepted="' + fieldData['accepted']['type'] + '" ';
  output += 'field_name="' + fieldData['name'] + '" ';
  output += 'field_type="' + fieldData['type'] + '" ';
  output += 'name="fields[' + fieldData['name'] + ']" ';
  output += 'class="form-control" ';
  output += 'onclick="loadBrowseNode(\''+fieldData['name']+'\');" ';
  output += 'value="' + fieldData['value'] + '">';
  output += '<span class="input-group-addon"><i class="fa fa-sitemap fa-lg"></i></span>';
  output += '</div>';
  output += '<span class="label label-info" style="display:none;" id="'+fieldData['name']+'_label"></span>';

  return output;
}

function getTextAreaField(fieldData) {
    var output = "";

    output += '<textarea ';
    if ('min_length' in fieldData['accepted']) {
        output += 'min_length="'+ fieldData['accepted']['min_length'] + '" ';
    }
    if ('max_length' in fieldData['accepted']) {
        output += 'max_length="'+ fieldData['accepted']['max_length'] + '" ';
    }
    output += 'field_name="' + fieldData['name'] + '" ';
    output += 'field_type="' +  fieldData['type'] + '" ';
    output += 'name="fields[' + fieldData['name'] + ']" class="form-control" rows="3">';
    output += fieldData['value'];
    output += '</textarea>';

    return output;
}

function getStringField(fieldData) {
    var output = "";

    output += '<input type="text"';
    output += 'accepted="' + fieldData['accepted']['type'] + '" ';
    if ('min_length' in fieldData['accepted']) {
        output += 'min_length="'+ fieldData['accepted']['min_length'] + '" ';
    }
    if ('max_length' in fieldData['accepted']) {
        output += 'max_length="'+ fieldData['accepted']['max_length'] + '" ';
    }
    output += 'field_name="' + fieldData['name'] + '" ';
    output += 'field_type="' + fieldData['type'] + '" ';
    output += 'name="fields[' + fieldData['name'] + ']" ';
    output += 'value="' + fieldData['value'] + '" class="form-control">';

    return output;
}

function getSelectField(fieldData) {
    var output = "";

    output += '<select ';
    output += 'field_name="' + fieldData['name'] + '" ';
    output += 'field_type="' + fieldData['type'] + '" ';
    output += 'name="fields[' + fieldData['name'] + ']" class="form-control">';

    output += '<option></option>';

    if (fieldData['accepted']['option'].length != undefined) {
        for(j in fieldData['accepted']['option']) {
            output += '<option ';

            if (fieldData['value'].toLowerCase() == fieldData['accepted']['option'][j]['value'].toLowerCase()) {
                output += 'selected="selected" ';
            }
            output += 'value="' + fieldData['accepted']['option'][j]['value'] + '">';
            output += fieldData['accepted']['option'][j]['name'];
            output += '</option>';
        }
    }
    else {
        output += '<option ';

        if (fieldData['value'].toLowerCase() == fieldData['accepted']['option']['value'].toLowerCase()) {
            output += 'selected="selected" ';
        }
        output += 'value="' + fieldData['accepted']['option']['value'] + '">';
        output += fieldData['accepted']['option']['name'];
        output += '</option>';
    }
    output += '</select>';
    return output;
}

function validate(formType) {
  var warnings = 0;
  var mChecked = 0;
  var productIdType;
  var productId;
  var productIdRequired;

  if ($('#category_selector').val() == '') {
    return false;
  }

  $('.marketplace_ids').each(function (i) {
    if ($(this).is(':checked')) {
      mChecked++;
    }
  });

  if (mChecked == 0) {
    $('#marketplaces').prepend('<div class="alert alert-danger" id="marketplace-alert">{{ error_required }}</div>');
    warnings ++;
  } else {
    $('#marketplace-alert').remove();
  }

    $('.fields_' + formType + ' :input').each(function (i) {
        if ($(this).parent().parent().attr('display') === "no") {
            return;
        }

        var field_value = $(this).val();
        var field_name = $(this).attr('field_name');
        var field_type = $(this).attr('field_type');
        var min_length = $(this).attr('min_length');
        var max_length = $(this).attr('max_length');

        if (field_name === 'Type') {
            productIdType = field_value;
        } else if (field_name === 'Value') {
            productId = field_value;
            if (field_type === 'required') {
                productIdRequired = true;
            } else {
                productIdRequired = false;
            }
        }

        if (field_type == 'required' || field_value !== '') {
            if (field_value === '') {
              $('.fields_' + formType + ' #error_' + field_name).text('{{ error_required }}').show();
              warnings ++;
            } else if (min_length != undefined && field_value.length < min_length) {
              $('.fields_' + formType + ' #error_' + field_name).text('{{ error_length }} ' + min_length + ' {{ text_characters }}').show();
              warnings ++;
            } else if (max_length != undefined && field_value.length > max_length) {
              $('.fields_' + formType + ' #error_' + field_name).text((field_value.length - max_length) + ' {{ error_char_limit }}').show();
              warnings ++;
            } else {
                $('.fields_' + formType + ' #error_' + field_name).text('').hide();
            }
        }
    });

    if (productIdRequired && productIdType !== 'ASIN' && !isValidProductId(productId)) {
      $('.fields_' + formType + ' :input').each(function (i) {
        var field_name = $(this).attr('field_name');
        if (field_name === 'Value') {
          $('.fields_' + formType + ' #error_' + field_name).text('Not valid product ID!');
          warnings ++;
          return;
        }
      });
    }

    if ($('.fields_' + formType + ' [name="category"]').val() == undefined) {
      warnings ++;
  }

    if (warnings > 0) {
        return false;
    } else {
        return true;
    }
}

function validate_and_save(formType) {
  if (validate(formType)) {
    if (formType == 'advanced') {
      $("#product_form_advanced").submit();
    } else if (formType == 'quick') {
      $("#product_form_quick").submit();
    }
  } else {
    alert('{{ error_not_saved }}');
  }
}

function save_and_upload() {
    $('#product_form_advanced input[name=upload_after]').val(true);

    if (validate('advanced')) {
        $("#product_form_advanced").submit();
    } else {
        alert('{{ error_not_saved }}');
    }
}

function isValidProductId(value) {
    var barcode = value.substring(0, value.length - 1);
    var checksum = parseInt(value.substring(value.length - 1), 10);
    var calcSum = 0;
    var calcChecksum = 0;
    barcode.split('').map(function(number, index ) {
        number = parseInt(number, 10);
        if (value.length === 13) {
            if (index % 2 === 0) {
                calcSum += number;
            }
            else {
                calcSum += number * 3;
            }
        } else {
            if (index % 2 === 0) {
                calcSum += number * 3;
            }
            else {
                calcSum += number;
            }
        }
    });
    calcSum %= 10;
    calcChecksum = (calcSum === 0) ? 0 : (10 - calcSum);
    if (calcChecksum !== checksum) {
        return false;
    }
    return true;
}

var nodeBox = '';
var nodeString = '';
var nodeStringSimple = '';

function loadBrowseNode(field) {
  $('#browse-node-modal').modal('toggle');

  var html = '';
  var market = $('.marketplace_ids:checked').val();

  $('#'+field+'_input').val('');

    nodeString = '';
    nodeStringSimple = '';

    $.ajax({
        url: 'index.php?route=extension/openbay/amazon_listing/getBrowseNodes&user_token={{ user_token }}',
        type: 'POST',
        data: { marketplaceId: market},
        dataType: 'json',
        beforeSend: function(){
            $('#browse-node-content').empty();
            $('#'+field+'_label').empty().hide();
        },
        success: function(data) {
            if (data.node.error != true){
                html += '<div class="well">';
                  html += '<div class="input-group col-md-12">';
                    html += '<p><select class="form-control" id="root-node" onchange="nodeSelect(\'root-node\', \''+field+'\');">';
                      html += '<option value="">{{ text_select }}</option>';
                      $.each(data.children, function(k,v){
                          html += '<option value="'+ v.node_id+'">'+ v.name+'</option>';
                      });
                    html += '</select></p>';
                  html += '</div>';
                html += '</div>';

                $('#browse-node-content').empty().html(html);
            }else{
              alert(data.node.error);
            }
        },
        failure: function(){
            alert('{{ error_load_nodes }}');
        },
        error: function(){
            alert('{{ error_load_nodes }}');
        }
    });
}

function nodeSelect(field, original_field) {
    //called when the root node id is chosen
    var html = '';
    var market = $('.marketplace_ids:checked').val();
    var node = $('#'+field).val();
    var parentNodeName = $('#'+field).find(":selected").text();
    nodeStringSimple += parentNodeName+' > ';

    $.ajax({
        url: 'index.php?route=extension/openbay/amazon_listing/getBrowseNodes&user_token={{ user_token }}',
        type: 'POST',
        data: { marketplaceId: market, node: node},
        dataType: 'json',
        beforeSend: function(){
          $('#browse-node-content').empty().html('<a class="btn btn-primary" disabled="disabled"><i class="fa fa-cog fa-lg fa-spin"></i> </a>');
        },
        success: function(data) {
          if (data.node.error != true){
            html += '<div class="row">';
              html += '<div class="col-sm-12 text-left">';
                html += '<h4>'+nodeStringSimple+'</h4>';
              html += '</div>';
            html += '</div>';
            if (data.node.final == 0){
              html += '<div class="well">';
                html += '<div class="input-group col-md-12">';
                  html += '<p><select class="form-control" id="'+field+'-'+node+'" onchange="nodeSelect(\''+field+'-'+node+'\', \''+original_field+'\');">';
                    html += '<option value="">{{ text_select }}</option>';
                    $.each(data.children, function(k,v){
                        html += '<option value="'+ v.node_id+'">'+ v.name+'</option>';
                    });
                  html += '</select></p>';
                html += '</div>';
              html += '</div>';
            }else{
              html += '<div class="row">';
                html += '<div class="col-sm-12 text-right">';
                  html += '<a onclick="saveNode('+data.node.id+', \''+original_field+'\', \''+nodeStringSimple+'\')" class="btn btn-primary"><i class="fa fa-save fa-lg"></i> {{ button_save }}</a>';
                html += '</div>';
              html += '</div>';
            }

            $('#browse-node-content').empty().html(html);
          }else{
              alert(data.node.error);
          }
        },
        failure: function(){
            alert('{{ error_load_nodes }}');
        },
        error: function(){
            alert('{{ error_load_nodes }}');
        }
    });
}

function saveNode(id, field, text){
  $('input[field_name='+field+']').val(id);
  $('#'+field+'_label').text(text).show();
  $('#browse-node-modal').modal('toggle');
}
//--></script>
{{ footer }}