-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.js
1378 lines (1091 loc) · 39.7 KB
/
helpers.js
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Frontend helpers for AdRapid API example implementations
* Documentation is available at http://raviteq.github.io/adrapid-api/
*/
var helpers = function(options) {
// configuration
/////////////////////////////////////////////////////////////////
var func = function() {};
this.inspectors = [];
this.uploadHelper = uploadHelper;
this.template_key = '';
// setup options for using the AdRapid api_get method
// to send the file upload request using AJAX.
var uploadOptions = {
cache : false, // Don't cache
processData : false, // Don't process the files
contentType : false, // Set content type to false as jQuery will tell the server its a query string request
};
// global vars f0r html5 live preview
var bannerState = false;
var bannerType = ''; // temp global var
var globalRules = false; // global rules var
var globalOptions = false; // global options var
var currentFormat = '300x250'; // contains current format of html5 banner
var formFields; // contains form field rules
var edgeSrc = '//animate.adobe.com/runtime/6.0.0/edge.6.0.0.min.js'; // path to Edge
var pixel = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; // 'http://api.adrapid.com/img/assets/pixel.png';
var spinner, format, tempColor, state = {}; // temp vars
// helper functions
/////////////////////////////////////////////////////////////////
function getAttributes(selector) {
var attrs = {};
$.each( selector[0].attributes, function ( index, attribute ) {
attrs[attribute.name] = attribute.value;
});
return attrs;
}
// build a form from template rules
this.buildForm = function(rules, template, settings) {
// setup settings
var settings = $.extend( {
selector: '#form', // form selector
formats: true, // include formats dropdown
colors: true, // include colors
images: true, // include images
texts: true, // include texts//
url: true, // include URL field
form: '', // any HTML to be included before te form output
complete: func, // complete function, is fired when the form has been added to the document
mode: 'html', // set mode of appending the content to the form selector. possible values are html, append and prepend
}, settings);
var form = settings.form + '<div>';
// create formats dropdown
if(settings.formats) form += form_formats(rules.formats);
// create form fields
// form += build_fields(rules.fields);
if(settings.texts) form += build_fields(rules.fields, 'text', 'text-fields');
if(settings.images) form += build_fields(rules.fields, 'image', 'image-fields');
if(settings.colors) form += build_fields(rules.fields, 'color', 'color-fields');
// add url field at bottom of form
if(settings.url) form += form_field({name: 'URL', label: 'URL', type: 'URL', default: ''});
// close form
form += '</div>';
// append the form to the HTML document
switch(settings.mode) {
default: $(settings.selector).html(form); break;
case 'append': $(settings.selector).append(form); break;
case 'prepend': $(settings.selector).prepend(form); break;
}
// perform complete callback function, sends the rules that was passed to this function
settings.complete(rules);
// return rules to next
return rules;
}
// watch order events
this.watchOrder = function(options) {
var settings = $.extend({
init: function() {
$('.loader').fadeIn();
},
update: function(data) {
adrapid.getPreview(data.id).then(function(res) {
$('#results').html(res.preview);
});
},
complete: function(data) {
$('.loader').fadeOut();
}
}, options);
return adrapid.watch({
order_id: options.order_id,
init: settings.init,
update: settings.update,
complete: settings.complete,
// TODO: add 'downloadable' event
});
}
// file upload helper
function uploadHelper(options) {
// config
var file; // global files object
var maxFileSize = 100 * 1000; // 100mb
// throwerror helper
function throwError(error) { alert(error); }
// extend defaults
var settings = $.extend( {
element: '#form2',
error: function(error) { throwError(error) },
begin: func,
complete: func,
progress: func,
errors: {
missingFile: function() { throwError('File missing') },
tooLarge: function() { throwError('File too large') },
wrongMime: function() { throwError('File type not allowe!') },
},
}, options);
var str = settings.element.substring(1);
// create form
$(settings.element).append('<input type="file" name="' + str + '-file" />');
// setup file upload events
$('input[name="' + str + '-file"]').change(function(event) {
settings.begin(str);
file = event.target.files; // update file data
var data = new FormData();
// add file(s)
$.each(file, function(key, value) {
data.append(key, value);
});
// send the upload request using our formData and custom ajax options
adrapid.api_get('medias', false, data, uploadOptions).then(function(response) {
settings.complete(response[0]);
});
});
}
// render formats dropdown
function form_formats(formats) {
var temp = '<br> <label for="formats">Banner format</label> <br><select name="formats"><br>';
$.each(formats, function(key, format) {
temp += '<option value="banner_' + format + ':google_adwords">' + format + '</option>'
});
temp += '</select> <br><br>';
return temp;
}
// build a set of form fields
function build_fields(fields, type, wrap) {
var output = '';
// filter fields
if(type) {
fields = fields.filter(function (el) {
return el.type == type
});
}
// build fields
$.each(fields, function(key, field) {
output += form_field(field);
});
// wrap fields in containing div
if(wrap) output = '<div class="' + wrap + '">' + output + '</div>';
return output;
}
// render a form field
function form_field(field, options) {
var settings = $.extend({
maxLength: true,
textLimiter: false,
}, options);
var fieldProperties = 'name="' + field.name + '" value="' + field.default + '" prop="' + field.type + '" ';
// handle maxlength
if(settings.maxLength && field.max_length) fieldProperties += 'maxlength="' + field.max_length + '" ';
var output = '<div class="field"><label for="' + field.name + '">' + field.label + '</label>' + '<input ' + fieldProperties + '/>';
// handle text-length counter
if(settings.textLimiter && field.type == 'text') output += '<div class="calc" id="calc-' + field.name + '">0</div>';
output += '</div>'
return output;
}
// live banner preview functions
// ---------------------------------------------------
this.loadPreviewDependencies = function(callback) {
// TODO: we need to know the banner type to load
// the correct dependencies for the ad.
// if(bannerType != 'edge') {
// if(callback) callback();
// return;
// }
// TODO: load correct dependencies depending on the banner type
if(typeof AdobeEdge == 'undefined') {
$.getScript(edgeSrc, function() {
if(callback) callback();
});
} else {
if(callback) callback();
}
}
// add an banner to the current page
this.appendAnimation = function(data, callback, target) {
// if we have html content, load it
if(data.content) $('#target').html(data.content);
// try setting dimensions
if(data.script.indexOf(', ') > -1) {
// create Stage element if it does not exist
var parts = data.script.split(', ');
var edgeID = parts[1].substring(1, parts[1].length - 1);
// create Stage element
if(!$('.' + edgeID).length) $('#target').html('<div id="Stage" class="' + edgeID + '"></div>');
// add the script
$('head').append(data.script);
// set dimensions
var wdims = $('script#ad-preview').attr('data-dimensions').split('x');
$('#target').width(wdims[0]).height(wdims[1]);
} else {
console.log('Head script');
$('head').append(data.script);
}
if(callback) callback();
return data;
}
// setup editor for html5 live preview
// - depends html5 preview (loaded), as well as a an order form.
this.previewHelper = function(options) {
// empty field obj, will be populated with fieldName:elementSelector pairs
// is also mapped to global formFields object
var fields = {};
// extend options
var settings = $.extend( {
selector: '',
complete: function() {},
load: function() {}
}, options);
// initialize function - is only run once
(function init() {
// re-build image selectors before loading banner events
rebuildImgSelectors().then(function(res) {
// getAndBindFormFields();
// perform bnaner load events when banner has finished loading
bannerLoadEvents(options)
.then(function(loadedBanner) {
console.log('Loaded banner...')
// do stuff then banner has finished loading..
return res;
})
;
// replace the elem
// return when complete
});
// perform bnaner load events when banner has finished loading
// bannerLoadEvents();
// save global options
globalOptions = options;
// TODO: handle with status flag var so that we can avoid doing this multiple times
// add a timeout in case we dont get the iframe load event
setTimeout(updateBanner, 700);
setTimeout(updateBanner, 1500);
}());
// add color pickers to form
// TODO: file upload helpers?
// TODO: crop select helpers?
helpers.addColorPickers();
// perform complete callback functions
settings.complete();
}
function getTemplateSelectors(rules, callback) {
var fields = {};
var max = rules.fields.length;
var c = 0;
// loop through list of fields to build rules
$.each(rules.fields, function(key, field) {
++c;
fields[field.name] = getSelector(field); // find selector for field
if(c == max) {
// debug form selectors object
formFields = fields; // save fields object globally
if(callback) callback(fields);
return fields;
}
});
}
function getFormFields(options, callback) {
if(globalRules) {
// console.log('Got global rules');
getTemplateSelectors(globalRules, function(fields) {
callback(fields);
});
} else {
// console.log('Need to get global rules');
// get rules for the template, since they are not provided to this method
adrapid.rules(options.templateId).then(function(rules) {
globalRules = rules; // save rules to global rules object
// update form selectors
getTemplateSelectors(rules, function(fields) {
callback(fields);
});
});
}
}
// get and bind form fields for template
// TODO: promisify!
function getAndBindFormFields(options) {
if(!options) options = {templateId: template_key} // handle empty options
getFormFields(options, function(fields) { // get fields
bindFormFields(fields); // bind fields
});
}
function debugSelector(selector) {
// get attributes
var attributes = getAttributes(selector);
// set of attributes to ignore
var ignore = [
'is',
'src',
'source',
'style',
];
// eppend attributes
var out = '<div ';
$.each(attributes, function(index, attrib) {
// skip some attributes
if(($.inArray(index.toLowerCase(), ignore) === -1)) {
out += index + '="' + attrib + '" ';
}
});
return out;
}
this.debugFields = function() {
var inputs = $('input');
$.each(inputs, function(i, inpt) {
console.log(inpt);
});
}
function debugImages() {
// get all images in iframe
// var imgs = $('img');
var imgs = $('#iframe_result').contents().find('img');
$.each(imgs, function(i, el) {
el = $(el); // ??
});
}
// debug current form selectors
this.debugFormSelectors = function() {
console.log('Debug form selectors:');
console.log(globalRules);
}
this.debugGlobalOptions = function() {
console.log('Global options:');
console.log(this.template_key);
}
// additional exports
this.getAndBindFormFields = getAndBindFormFields;
this.changeColor = changeColor;
this.performMultiple = performMultiple;
this.debugSelector = debugSelector;
this.debugCurrentScripts = debugCurrentScripts;
helpers.debugImages = this.debugImages;
// bind form events to update html5 live preview
function bindFormFields(fields) {
// TODO: add support for defining how each field type should be handled/retreived
// text fields change
$('input[prop=text]').off().on('input', function() {
$(fields[$(this).attr('name')]).html($(this).val());
// set temp calc var
$('#calc-' + $(this).attr('name')).text($(this).val().length);
});
// image fields change
$('input[prop=image]').off().on('input', function() {
var name = $(this).attr('name');
var value = $(this).val();
if(name.indexOf('-') > -1) name = name.split('-')[0];
replaceImage(name, value, fields[name]);
});
// color fields change
$('input[prop=color]').off().on('input', function() {
changeColor($(this).attr('name'), $(this).val());
});
// handle formats dropdown change
$('select[name=formats]').off().change(function(event) {
switchFormat($(this).find(':selected').text());
});
// trigger update event to update banner content
updateBannerContent();
}
function isArray(a) {
return (!!a) && (a.constructor === Array);
};
function flashElement(selector) {
selector.addClass('border');
setTimeout(function() {
selector.removeClass('border');
}, 1500);
}
function updateBannerContent() {
// trigger state change on all text fields in order
// to get the correct content in the ad.
// updateFields(); // update / replace all form fields once only
performMultiple(updateFields, [0, 100, 500, 1000]); // perform multiple times to make sure fields are replaced
}
function updateFields() {
$('input[prop=text], input[prop=image], input[prop=color]').trigger('input');
}
function performMultiple(func, times) {
$.each(times, function(i, time) {
setTimeout(func, time);
});
}
// replace image wrapper function
// TODO: needs updated selector...
function replaceImage(name, value, field) {
if(!value || value.length < 3) return false; // do not replace image unless we have a value
performMultiple(changeImage(field, value), [0, 200, 800]);
}
function changeImage(field, value) {
// debug
// console.log('Replace image (' + field.attr + ') - ' + field.name + ' -> ' + value);
// console.log(field);
// different handling for img and background replacement
if(field.attr == 'img') {
replaceImageElement(field.target, value);
} else if(field.attr == 'background') {
replaceImageBackground($(field.target), value);
} else {
console.log('Unknown image type: ' + field.attr);
}
}
// get type of html5 banner
// @returns 'adrapid', 'edge' or 'iframe'
function getHtml5BannerType(element) {
if(!element) element = '#target';
if($(element + ' .adrapid').length) return 'adrapid';
if($('#Stage').length) return 'edge';
if($(element + ' iframe').length) return 'iframe';
return 'unknown'; // did not detect banner type
}
// find selector for name
function getSelector(field) {
var name = field.name;
var target;
var outputs = [];
// check for internal replacement for image
// TODO: split this into separate function ..
if(field.type == 'image') { // && field.replace [?]
target = findImageElement(field); // using helper
// check if we found image using the `findImageElement` function
if(target && target.length) {
}
// check for other targets
if($('#' + field.name).length) target = '#' + field.name;
// check for image..
if($('#iframe_result').length) {
// find through replace ID:s...
// TODO: fix!!
// TODO: each image should only belong to one selector at max
if(field.replace_ids) {
// is array?
if(field.replace_ids instanceof Array) {
// loop through items
$.each(field.replace_ids, function(i, image) {
var iframeItem = $('#iframe_result').contents().find('#' + image);
if(iframeItem.length > 0) {
// debug
var cont = debugSelector(iframeItem);
// make sure image has src
// temp test: only performing this for background images
if(iframeItem.attr('src') && iframeItem.attr('id') == 'gwd-image_9' && iframeItem.prev().prop('nodeName') !== 'DIV') {
console.log('Replacing image form backgrund!');
// // replace the selector - div with background as oposed of img
// replaceImageSelector(iframeItem);
// // // re-get element for selector
// iframeItem = $('#iframe_result').contents().find('#' + image);
// add to outputs
outputs.push(iframeItem);
} else {
// no src
// add to outputs
outputs.push(iframeItem);
}
}
});
} else {
// replace ids:s is single item
}
} else {
// no replace id:s for item
}
// found any image selectors?
if(outputs.length) {
return {
target: outputs,
attr: 'img',
};
}
// pattern : #replacement
if(field.replace) {
var iframeItem = $('#iframe_result').contents().find('#' + field.replace);
// TODO: need to handle multiple selectors !!!
if(iframeItem.length) {
// return with 'img' change attrib...
return {
target: iframeItem,
attr: 'img',
};
}
}
// pattern : #name
if($('#iframe_result').contents().find('#' + name).length) {
target = $('#iframe_result').contents().find('#' + name);
// return with 'img' change attrib...
return {
// returns an object
// TODO: set config for this
target: target,
attr: 'img', // intead of 'background'
};
}
}
// console.log('We return object ... ');
// console.log({
// name: name,
// target: target,
// type: 'replace',
// attr: 'background', // either 'background' or 'img'
// // replace: replaceString,
// });
return {
name: name,
target: target,
type: 'replace',
attr: 'background', // either 'background' or 'img'
// replace: replaceString,
};
} // end image handling
// text fields / other:
// using findTextElement helper function
// var elem = findTextElement(field, name);
// if(elem && elem != "NOTFOUND") {
// return elem;
// }
// #name
if($('#' + field.name + ' p').length) return $('#' + field.name + ' p');
if($('#' + name + ' p').length) return $('#' + name + ' p'); // durr
if($('#' + name).length) return $('#' + name);
// double __
if($('#Stage__' + name + ' p font span').length) return '#Stage__' + name + ' p font span';
if($('#Stage__' + name + ' p span').length) return '#Stage__' + name + ' p span';
if($('#Stage__' + name + ' p font').length) return '#Stage__' + name + ' p font';
if($('#Stage__' + name + ' p').length) return '#Stage__' + name + ' p';
if($('#Stage__' + name).length) return '#Stage__' + name;
// single _
if($('#Stage_' + name + ' p font span').length) return '#Stage_' + name + ' p font span';
if($('#Stage_' + name + ' p span').length) return '#Stage_' + name + ' p span';
if($('#Stage_' + name + ' p font').length) return '#Stage_' + name + ' p font';
if($('#Stage_' + name + ' p').length) return '#Stage_' + name + ' p';
if($('#Stage_' + name).length) return '#Stage_' + name;
// no results yet, look into the iframe as well...
if($('#iframe_result').length) {
if($('#iframe_result').contents().find('#' + name + ' p').length) {
return $('#iframe_result').contents().find('#' + name + ' p');
}
if($('#iframe_result').contents().find('#' + name).length) {
return $('#iframe_result').contents().find('#' + name);
}
}
// TODO: support for colors
// element was still not found
return '#notFound';
}
// find text element selector for a field name - returns maximum 1 element only
function findTextElement(field, name) {
var possibilities = [
'#' + field.name + ' p',
'#' + name + ' p',
'#' + name,
'#Stage__' + name + ' p font span',
'#Stage__' + name + ' p span',
'#Stage__' + name + ' p font',
'#Stage__' + name + ' p',
'#Stage__' + name,
'#Stage_' + name + ' p font span',
'#Stage_' + name + ' p span',
'#Stage_' + name + ' p font',
'#Stage_' + name + ' p',
'#Stage_' + name,
];
// loop through fields, find selector in documents
$.each(possibilities, function(i, selector) {
if($(selector).length) return selector;
});
return 'NOTFOUND'; // no selector found
}
function findIframeTextElement(field) {
}
function replaceImageElement(selector, newImage) {
if(isArray(selector)) {
$.each(selector, function(i, el) {
replaceImageElement(el, newImage);
});
} else {
// get type of element
var elType = selector.prev().prop('nodeName');
// console.log(' change elem: ' + selector.attr('id') + ' (' + elType + ')');
// handling for different types of img elements
switch(elType) {
default:
case 'IMG':
// console.log(' > handle: IMG');
// replace the element image
selector
.attr({
'src': newImage,
'source': newImage // gwd needs this property as well
})
;
break;
case 'DIV':
// console.log(' > handle: DIV');
// debug element html
// console.log('>' + newImage + '<' + ' ...');
// console.log(selector.get());
selector
.css({
'background-image': 'url(' + newImage + ')',
})
;
break;
}
}
}
// replace element helpers
// this is a temp fix
function rebuildImgSelectors() {
// return promise
return new Promise(function(resolve, reject) {
// get the background image, replace the element
// bind form selectors at this point
// TODO: should be own function
// TODO: should of course be dynamic, this is for demo purposes
// wait
// setTimeout(function() {
// var imgElem = $('#iframe_result').contents().find('#gwd-image_9');
// console.log('Change this elem:');
// console.log(imgElem);
// // replace the elem
// replaceImageSelector(imgElem, function(res) {
// // log new elem
// var imgElem = $('#iframe_result').contents().find('#gwd-image_9');
// console.log('New elem:');
// console.log(imgElem);
// // some wait
// setTimeout(function() {
// // reset fields - not neccessary if we bind
// // events in the next step at first ...
// getAndBindFormFields();
// }, 1000);
// // return when complete
// resolve('was completed');
// });
// }, 3000);
// return instead
resolve('complete');
});
}
// replace img selector with div element for a specified selector
function replaceImageSelector(selector, callback) {
// get new css of div element
var itemStyle =
'width: ' + selector.width() + 'px;' +
'height: ' + selector.height() + 'px;' +
'background-image: url(' + selector.attr('src') + ');' +
'background-size: cover;' +
'background-position: 50%'
;
// debug selector, also get content of replacement div
var divHtml = debugSelector(selector);
// add css to div html
divHtml += ' style="' + itemStyle + '"></div>';
// replace img element with div element, delete original img element
selector.after(divHtml).remove();
// callback
if(callback) callback();
}
function replaceImageBackground(selector, newImage) {
if(typeof selector == 'array') {
$.each(selector, function(i, el) {
replaceImageBackground(el, newImage);
});
} else {
console.log('Replace image background...');
selector.css('background-image', 'url("' + newImage + '")');
// replaceImageElement(selector, newImage); // try replace img element as well
}
}
function findImageElement(field) {
var target;
var outputs = [];
// // try find by replace images..
// if(field.replace_images) {
// // TODO: should not do the actual replace
// if(field.replace_images instanceof Array) {
// $.each(field.replace_images, function(i, image) {
// var findStr = 'img[src="' + image + '"]';
// var imgEl = $(findStr);
// if(imgEl.length) {
// // return imgEl;
// outputs.push(imgEl);
// } else {
// }
// });
// } else {
// }
// }
// if(field.replace_ids) {
// if(field.replace_ids instanceof Array) {
// // loop through items
// $.each(field.replace_ids, function(i, image) {
// var findStr = '#' + image;
// var imgEl = $(findStr);
// if(imgEl.length) {
// return findStr;
// } else {
// }
// });
// } else {
// }
// }
if(field.replace) {
var replaceString = field.replace.substring(0, field.replace.length - 4);
if(replaceString.length) {
// find selector by some patterns:
if($('#' + replaceString).length) return '#' + replaceString;
if($('#Stage__' + replaceString).length) return '#Stage__' + replaceString;
if($('#Stage_' + replaceString).length) return '#Stage_' + replaceString;
} else {
}
} else {
}
// additional checks
if($('#Stage__' + field.name).length) return '#Stage__' + field.name;
if($('#Stage_' + field.name).length) return '#Stage_' + field.name;
if(outputs) return outputs;
return '#noImg'; // no image found
}
// remove add depdendencies
function unloadLivePreview(callback) {
console.log('Remove previous live preview...');
// remove scripts
// $("script[src='*edge.js']").remove();
$('script#ad-preview').remove();
// $.each($('script#ad-preview'), function(i, s) {
// console.log($(s));
// // $(s).remove();
// });
// loop through head scripts
$.each($('head script'), function(i, s) {
if($(s).attr('src') && $(s).attr('src').indexOf('adrapid') > -1) {
console.log(' -> ' + $(s).attr('src'));
$(s).remove();
}
});
$.each($('head object'), function(i, s) {
if($(s).attr('data') && $(s).attr('data').indexOf('adrapid') > -1) {
console.log(' -> ' + $(s).attr('src'));
$(s).remove();
}
});
// reset global vars
globalRules = false;
formFields = false;
bannerType = false;
// do callback after some timeout
setTimeout(function() {
console.log('Done cleaning');
if(callback) callback();
}, 100);
}
function debugCurrentScripts() {
$.each($('head script'), function(i, s) {
if($(s).attr('src')) {
console.log(' -> ' + $(s).attr('src'));
}
});
$.each($('head object'), function(i, s) {