-
Notifications
You must be signed in to change notification settings - Fork 33
/
imgmap.js
2949 lines (2718 loc) · 94.1 KB
/
imgmap.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
/**
* Image Map Editor (imgmap) - in-browser imagemap editor
* Copyright (C) 2006 - 2008 Adam Maschek (adam.maschek @ gmail.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
* @fileoverview
* Online Image Map Editor - main script file.
* This is the main script file of the Online Image Map Editor.
*
* TODO:
* -scriptload race condition fix
* -destroy/cleanup function ?
* -testing highlighter
* -cursor area_mousemove in opera not refreshing quite well - bug reported
* -get rid of memo array
* -highlight which control point is edited in html or form mode
* -more comments, especially on config vars
* -make function names more logical
* - dumpconfig
* -prepare for bad input /poly not properly closed?
* -prepare for % values in coords
* -prepare for default shape http://www.w3.org/TR/html4/struct/objects.html#edef-AREA
*
* @date 26-02-2007 2:24:50
* @author Adam Maschek (adam.maschek(at)gmail.com)
* @copyright
* @version 2.2
*
*/
/*jslint browser: true, newcap: false, white: false, onevar: false, plusplus: false, eqeqeq: false, nomen: false */
/*global imgmapStrings:true, window:false, G_vmlCanvasManager:false, air:false, imgmap_spawnObjects:true */
/**
* @author Adam Maschek
* @constructor
* @param config The config object.
*/
function imgmap(config) {
/** Version string of imgmap */
this.version = "2.2";
/** Build date of imgmap */
this.buildDate = "2009/08/12 22:18";
/** Sequential build number of imgmap */
this.buildNumber = "113";
/** Config object of the imgmap instance */
this.config = {};
/** Status flag to indicate current drawing mode */
this.is_drawing = 0;
/** Array to hold language strings */
this.strings = [];
/** Helper array for some drawing operations */
this.memory = [];
/** Array to hold reference to all areas (canvases) */
this.areas = [];
/** Array to hold last log entries */
this.logStore = [];
/** Associative array to hold bound event handlers */
this.eventHandlers = {};
this.currentid = 0;
this.draggedId = null;
this.selectedId = null;
this.nextShape = 'rect';
/** possible values: 0 - edit, 1 - preview */
this.viewmode = 0;
/** array of dynamically loaded javascripts */
this.loadedScripts = [];
this.isLoaded = false;
this.cntReloads = 0;
/** holds the name of the actively edited map, use getMapName to read it */
this.mapname = '';
/** holds the id of the actively edited map, use getMapIdto read it */
this.mapid = '';
/** watermark to attach to output */
this.waterMark = '<!-- Created by Online Image Map Editor (http://www.maschek.hu/imagemap/index) -->';
/** global scale of areas (1-normal, 2-doubled, 0.5-half, etc.) */
this.globalscale = 1;
/** is_drawing draw mode constant */
this.DM_RECTANGLE_DRAW = 1;
/** is_drawing draw mode constant */
this.DM_RECTANGLE_MOVE = 11;
/** is_drawing draw mode constant */
this.DM_RECTANGLE_RESIZE_TOP = 12;
/** is_drawing draw mode constant */
this.DM_RECTANGLE_RESIZE_RIGHT = 13;
/** is_drawing draw mode constant */
this.DM_RECTANGLE_RESIZE_BOTTOM = 14;
/** is_drawing draw mode constant */
this.DM_RECTANGLE_RESIZE_LEFT = 15;
/** is_drawing draw mode constant */
this.DM_SQUARE_DRAW = 2;
/** is_drawing draw mode constant */
this.DM_SQUARE_MOVE = 21;
/** is_drawing draw mode constant */
this.DM_SQUARE_RESIZE_TOP = 22;
/** is_drawing draw mode constant */
this.DM_SQUARE_RESIZE_RIGHT = 23;
/** is_drawing draw mode constant */
this.DM_SQUARE_RESIZE_BOTTOM = 24;
/** is_drawing draw mode constant */
this.DM_SQUARE_RESIZE_LEFT = 25;
/** is_drawing draw mode constant */
this.DM_POLYGON_DRAW = 3;
/** is_drawing draw mode constant */
this.DM_POLYGON_LASTDRAW = 30;
/** is_drawing draw mode constant */
this.DM_POLYGON_MOVE = 31;
/** is_drawing draw mode constant */
this.DM_BEZIER_DRAW = 4;
/** is_drawing draw mode constant */
this.DM_BEZIER_LASTDRAW = 40;
/** is_drawing draw mode constant */
this.DM_BEZIER_MOVE = 41;
//set some config defaults below
/**
* Mode of operation
* possible values:
* editor - classical editor,
* editor2 - dreamweaver style editor,
* highlighter - map highlighter, will spawn imgmap instances for each map found in the current page
* highlighter_spawn - internal mode after spawning imgmap objects
*/
this.config.mode = "editor";
this.config.baseroot = '';
this.config.lang = '';
this.config.defaultLang = 'en';
this.config.loglevel = 0;
this.config.custom_callbacks = {};//possible values: see below!
/** Callback events that you can handle in your GUI. */
this.event_types = [
'onModeChanged',
'onHtmlChanged',
'onAddArea',
'onRemoveArea',
'onDrawArea',
'onResizeArea',
'onRelaxArea',
'onFocusArea',
'onBlurArea',
'onMoveArea',
'onSelectRow',
'onLoadImage',
'onSetMap',
'onGetMap',
'onSelectArea',
'onDblClickArea',
'onStatusMessage',
'onAreaChanged'];
//default color values
this.config.CL_DRAW_BOX = '#E32636';
this.config.CL_DRAW_SHAPE = '#d00';
this.config.CL_DRAW_BG = '#fff';
this.config.CL_NORM_BOX = '#E32636';
this.config.CL_NORM_SHAPE = '#d00';
this.config.CL_NORM_BG = '#fff';
this.config.CL_HIGHLIGHT_BOX = '#E32636';
this.config.CL_HIGHLIGHT_SHAPE = '#d00';
this.config.CL_HIGHLIGHT_BG = '#fff';
this.config.CL_KNOB = '#555';
this.config.bounding_box = true;
this.config.label = '%n';
//the format string of the area labels - possible values: %n - number, %c - coords, %h - href, %a - alt, %t - title
this.config.label_class = 'imgmap_label';
//the css class to apply on labels
this.config.label_style = 'font: bold 10px Arial';
//this.config.label_style = 'font-weight: bold; font-size: 10px; font-family: Arial; color: #964';
//the css style(s) to apply on labels
this.config.hint = '#%n %h';
//the format string of the area mouseover hints - possible values: %n - number, %c - coords, %h - href, %a - alt, %t - title
this.config.draw_opacity = '35';
//the opacity value of the area while drawing, moving or resizing - possible values 0 - 100 or range "(x)-y"
this.config.norm_opacity = '50';
//the opacity value of the area while relaxed - possible values 0 - 100 or range "(x)-y"
this.config.highlight_opacity = '70';
//the opacity value of the area while highlighted - possible values 0 - 100 or range "(x)-y"
this.config.cursor_default = 'crosshair'; //auto/pointer
//the css cursor while hovering over the image
//browser sniff
var ua = navigator.userAgent;
this.isMSIE = (navigator.appName == "Microsoft Internet Explorer") || (navigator.appName == 'Netscape' && navigator.userAgent.search('Trident') != -1);
this.isMSIE5 = this.isMSIE && (ua.indexOf('MSIE 5') != -1);
this.isMSIE5_0 = this.isMSIE && (ua.indexOf('MSIE 5.0') != -1);
this.isMSIE7 = this.isMSIE && (ua.indexOf('MSIE 7') != -1);
this.isGecko = ua.indexOf('Gecko') != -1;
this.isSafari = ua.indexOf('Safari') != -1;
this.isOpera = (typeof window.opera != 'undefined');
this.setup(config);
}
/**
* Return an object given by id or object itself.
* @date 22-02-2007 0:14:50
* @author Adam Maschek (adam.maschek(at)gmail.com)
* @param objorid A DOM object, or id of a DOM object.
* @return The identified DOM object or null on error.
*/
imgmap.prototype.assignOID = function(objorid) {
try {
if (typeof objorid == 'undefined') {
this.log("Undefined object passed to assignOID.");// Called from: " + arguments.callee.caller, 1);
return null;
}
else if (typeof objorid == 'object') {
return objorid;
}
else if (typeof objorid == 'string') {
return document.getElementById(objorid);
}
}
catch (err) {
this.log("Error in assignOID", 1);
}
return null;
};
/**
* Main setup function.
* Can be called manually or constructor will call it.
* @date 22-02-2007 0:15:42
* @author Adam Maschek (adam.maschek(at)gmail.com)
* @param config config object
* @return True if all went ok.
*/
imgmap.prototype.setup = function(config) {
//this.log('setup');
//copy non-default config parameters to this.config
for (var i in config) {
if (config.hasOwnProperty(i)) {
this.config[i] = config[i];
}
}
//set document event hooks
this.addEvent(document, 'keydown', this.eventHandlers.doc_keydown = this.doc_keydown.bind(this));
this.addEvent(document, 'keyup', this.eventHandlers.doc_keyup = this.doc_keyup.bind(this));
this.addEvent(document, 'mousedown', this.eventHandlers.doc_mousedown = this.doc_mousedown.bind(this));
//set pic_container element - supposedly it already exists in the DOM
if (config && config.pic_container) {
this.pic_container = this.assignOID(config.pic_container);
this.disableSelection(this.pic_container);
}
if (!this.config.baseroot) {
//search for a base - theoretically there can only be one, but lets search
//for the first non-empty
var bases = document.getElementsByTagName('base');
var base = '';
for (i=0; i<bases.length; i++) {//i declared earlier
if (bases[i].href) {
base = bases[i].href;
//append slash if missing
if (base.charAt(base.length-1) != '/') {
base+= '/';
}
break;
}
}
//search for scripts
var scripts = document.getElementsByTagName('script');
var found = false;
for (i=0; i<scripts.length; i++) {//i declared earlier
if (scripts[i].src && scripts[i].src.match(/imgmap\w*\.js(\?.*?)?$/)) {
var src = scripts[i].src;
//cut filename part, leave last slash
src = src.substring(0, src.lastIndexOf('/') + 1);
//set final baseroot path
if (base && src.indexOf('://') == -1) {
this.config.baseroot = base + src;
}
else {
this.config.baseroot = src;
}
//exit loop
found = true;
break;
}
}
if (!found && this.config.baseroot === '') {
this.log("Unable to detect baseroot.", 1);
}
}
//load excanvas js - as soon as possible
if (this.isMSIE &&
typeof window.CanvasRenderingContext2D == 'undefined' && typeof G_vmlCanvasManager == 'undefined') {
this.loadScript(this.config.baseroot + 'excanvas.js');
//alert('loadcanvas');
}
//alert(this.config.baseroot);
//load language js - as soon as possible
if (!this.config.lang) {
this.config.lang = this.detectLanguage();
}
if (typeof imgmapStrings == 'undefined') {
//language file might have already been loaded (ex highlighter mode)
this.loadScript(this.config.baseroot + 'lang_' + this.config.lang + '.js');
}
//check event hooks
var found, j, le;
for (i in this.config.custom_callbacks) {
if (this.config.custom_callbacks.hasOwnProperty(i)) {
found = false;
for (j = 0, le = this.event_types.length; j < le; j++) {
if (i == this.event_types[j]) {
found = true;
break;
}
}
if (!found) {
this.log("Unknown custom callback: " + i, 1);
}
}
}
//hook onload event - as late as possible
this.addEvent(window, 'load', this.onLoad.bind(this));
return true;
};
/**
* currently unused
* @ignore
*/
imgmap.prototype.retryDelayed = function(fn, delay, tries) {
if (typeof fn.tries == 'undefined') {fn.tries = 0;}
//alert(fn.tries+1);
if (fn.tries++ < tries) {
//alert('ss');
window.setTimeout(function() {
fn.apply(this);
}, delay);
}
};
/**
* EVENT HANDLER: Handle event when the page with scripts is loaded.
* @date 22-02-2007 0:16:22
* @author Adam Maschek (adam.maschek(at)gmail.com)
* @param e The event object.
*/
imgmap.prototype.onLoad = function(e) {
if (this.isLoaded) {return true;}
var _this = this;
//this.log('readystate: ' + document.readyState);
if (typeof imgmapStrings == 'undefined') {
if (this.cntReloads++ < 5) {
//this.retryDelayed(_this.onLoad(), 1000, 3);
window.setTimeout(function () {_this.onLoad(e);} ,1200);
this.log('Delaying onload (language ' + this.config.lang + ' not loaded, try: ' + this.cntReloads + ')');
return false;
}
else if (this.config.lang != this.config.defaultLang && this.config.defaultLang != 'en') {
this.log('Falling back to default language: ' + this.config.defaultLang);
this.cntReloads = 0;
this.config.lang = this.config.defaultLang;
this.loadScript(this.config.baseroot + 'lang_' + this.config.lang + '.js');
window.setTimeout(function () {_this.onLoad(e);} ,1200);
return false;
}
else if (this.config.lang != 'en') {
this.log('Falling back to english language');
this.cntReloads = 0;
this.config.lang = 'en';
this.loadScript(this.config.baseroot + 'lang_' + this.config.lang + '.js');
window.setTimeout(function () {_this.onLoad(e);} ,1200);
return false;
}
}
//else
try {
this.loadStrings(imgmapStrings);
}
catch (err) {
this.log("Unable to load language strings", 1);
}
//check if ExplorerCanvas correctly loaded - detect if browser supports canvas
//alert(typeof G_vmlCanvasManager + this.isMSIE + typeof window.CanvasRenderingContext2D);
if (this.isMSIE) {
//alert('cccc');
//alert(typeof G_vmlCanvasManager);
if (typeof window.CanvasRenderingContext2D == 'undefined' && typeof G_vmlCanvasManager == 'undefined') {
//alert('bbb');
/*
if (this.cntReloads++ < 5) {
var _this = this;
//this.retryDelayed(_this.onLoad(), 1000, 3);
window.setTimeout(function () {
_this.onLoad(e);
}
,1000
);
//alert('aaa');
this.log('Delaying onload (excanvas not loaded, try: ' + this.cntReloads + ')');
return false;
}
*/
this.log(this.strings.ERR_EXCANVAS_LOAD, 2);//critical error
}
}
if (this.config.mode == 'highlighter') {
//call global scope function
imgmap_spawnObjects(this.config);
}
this.isLoaded = true;
return true;
};
/**
* Attach new 'evt' event handler 'callback' to 'obj'
* @date 24-02-2007 21:16:20
* @param obj The object on which the handler is defined.
* @param evt The name of the event, like mousedown.
* @param callback The callback function (named if you want it to be removed).
*/
imgmap.prototype.addEvent = function(obj, evt, callback) {
if (obj.attachEvent) {
//Microsoft style registration model
return obj.attachEvent("on" + evt, callback);
}
else if (obj.addEventListener) {
//W3C style model
obj.addEventListener(evt, callback, false);
return true;
}
else {
obj['on' + evt] = callback;
}
};
/**
* Detach 'evt' event handled by 'callback' from 'obj' object.
* Callback must be a non anonymous function, see eventHandlers.
* @see #eventHandlers
* Example: myimgmap.removeEvent(myimgmap.pic, 'mousedown', myimgmap.eventHandlers.img_mousedown);
* @date 24-11-2007 15:22:17
* @param obj The object on which the handler is defined.
* @param evt The name of the event, like mousedown.
* @param callback The named callback function.
*/
imgmap.prototype.removeEvent = function(obj, evt, callback) {
if (obj.detachEvent) {
//Microsoft style detach model
return obj.detachEvent("on" + evt, callback);
}
else if (obj.removeEventListener) {
//W3C style model
obj.removeEventListener(evt, callback, false);
return true;
}
else {
obj['on' + evt] = null;
}
};
/**
* We need this because load events for scripts function slightly differently.
* @link http://dean.edwards.name/weblog/2006/06/again/
* @author Adam Maschek (adam.maschek(at)gmail.com)
* @date 24-03-2007 11:02:21
*/
imgmap.prototype.addLoadEvent = function(obj, callback) {
if (obj.attachEvent) {
//Microsoft style registration model
return obj.attachEvent("onreadystatechange", callback);
}
else if (obj.addEventListener) {
//W3C style registration model
obj.addEventListener('load', callback, false);
return true;
}
else {
obj.onload = callback;
}
};
/**
* Include another js script into the current document.
* @date 22-02-2007 0:17:04
* @author Adam Maschek (adam.maschek(at)gmail.com)
* @param url The url of the script we want to load.
* @see #script_load
* @see #addLoadEvent
*/
imgmap.prototype.loadScript = function(url) {
if (url === '') {return false;}
if (this.loadedScripts[url] == 1) {return true;}//script already loaded
this.log('Loading script: ' + url);
//we might need this someday for safari?
//var temp = '<script language="javascript" type="text/javascript" src="' + url + '"></script>';
//document.write(temp);
try {
var head = document.getElementsByTagName('head')[0];
var temp = document.createElement('SCRIPT');
temp.setAttribute('language', 'javascript');
temp.setAttribute('type', 'text/javascript');
temp.setAttribute('src', url);
//temp.setAttribute('defer', true);
head.appendChild(temp);
this.addLoadEvent(temp, this.script_load.bind(this));
}
catch (err) {
this.log('Error loading script: ' + url);
}
return true;
};
/**
* EVENT HANDLER: Event handler of external script loaded.
* @param e The event object.
*/
imgmap.prototype.script_load = function(e) {
var obj = (this.isMSIE) ? window.event.srcElement : e.currentTarget;
var url = obj.src;
var complete = false;
if (typeof obj.readyState != 'undefined') {
//explorer
if (obj.readyState == 'complete' || obj.readyState == 'loaded') {
complete = true;
}
}
else {
//other browsers?
complete = true;
}
if (complete) {
this.loadedScripts[url] = 1;
this.log('Loaded script: ' + url);
return true;
}
};
/**
* Load strings from a key:value object to the prototype strings array.
* @author adam
* @date 2007
* @param obj Javascript object that holds key:value pairs.
*/
imgmap.prototype.loadStrings = function(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
this.strings[key] = obj[key];
}
}
};
/**
* This function is to load a given img url to the pic_container.
*
* Loading an image will clear all current maps.
* @see #useImage
* @param img The imageurl or object to load (if object, function will get url, and do a recall)
* @param imgw The width we want to force on the image (optional)
* @param imgh The height we want to force on the image (optional)
* @returns True on success
*/
imgmap.prototype.loadImage = function(img, imgw, imgh) {
//test for container
if (typeof this.pic_container == 'undefined') {
this.log('You must have pic_container defined to use loadImage!', 2);
return false;
}
//wipe all
this.removeAllAreas();
//reset scale
this.globalscale = 1;
this.fireEvent('onHtmlChanged', '');//empty
if (!this._getLastArea()) {
//init with one new area if there was none editable
if (this.config.mode != "editor2") {this.addNewArea();}
}
if (typeof img == 'string') {
//there is an image given with url to load
if (typeof this.pic == 'undefined') {
this.pic = document.createElement('IMG');
this.pic_container.appendChild(this.pic);
//event handler hooking - only at the first load
this.addEvent(this.pic, 'mousedown', this.eventHandlers.img_mousedown = this.img_mousedown.bind(this));
this.addEvent(this.pic, 'mouseup', this.eventHandlers.img_mouseup = this.img_mouseup.bind(this));
this.addEvent(this.pic, 'mousemove', this.eventHandlers.img_mousemove = this.img_mousemove.bind(this));
this.pic.style.cursor = this.config.cursor_default;
}
//img ='../../'+img;
this.log('Loading image: ' + img, 0);
//calculate timestamp to bypass browser cache mechanism
var q = '?';
if (img.indexOf('?') > -1) {
q = '&';
}
this.pic.src = img + q + (new Date().getTime());
if (imgw && imgw > 0) {this.pic.setAttribute('width', imgw);}
if (imgh && imgh > 0) {this.pic.setAttribute('height', imgh);}
this.fireEvent('onLoadImage', this.pic);
return true;
}
else if (typeof img == 'object') {
//we have to use the src of the image object
var src = img.src; //img.getAttribute('src');
if (src === '' && img.getAttribute('mce_src') !== '') {
//if it is a tinymce object, it has no src but mce_src attribute!
src = img.getAttribute('mce_src');
}
else if (src === '' && img.getAttribute('_fcksavedurl') !== '') {
//if it is an fck object, it might have only _fcksavedurl attribute!
src = img.getAttribute('_fcksavedurl');
}
// Get the displayed dimensions of the image
if (!imgw) {
imgw = img.clientWidth;
}
if (!imgh) {
imgh = img.clientHeight;
}
//recurse, this time with the url string
return this.loadImage(src, imgw, imgh);
}
};
/**
* We use this when there is an existing image object we want to handle with imgmap.
* Mainly used in highlighter mode.
* @author adam
* @see #loadImage
* @see #imgmap_spawnObjects
* @date 2007
* @param img DOM object or id of image we want to use.
*/
imgmap.prototype.useImage = function(img) {
//wipe all
this.removeAllAreas();
if (!this._getLastArea()) {
//init with one new area if there was none editable
if (this.config.mode != "editor2") {this.addNewArea();}
}
img = this.assignOID(img);
if (typeof img == 'object') {
if (typeof this.pic != 'undefined') {
//remove previous handlers
this.removeEvent(this.pic, 'mousedown', this.eventHandlers.img_mousedown);
this.removeEvent(this.pic, 'mouseup', this.eventHandlers.img_mouseup);
this.removeEvent(this.pic, 'mousemove', this.eventHandlers.img_mousemove);
this.pic.style.cursor = '';
}
this.pic = img;
//hook event handlers
this.addEvent(this.pic, 'mousedown', this.eventHandlers.img_mousedown = this.img_mousedown.bind(this));
this.addEvent(this.pic, 'mouseup', this.eventHandlers.img_mouseup = this.img_mouseup.bind(this));
this.addEvent(this.pic, 'mousemove', this.eventHandlers.img_mousemove = this.img_mousemove.bind(this));
this.pic.style.cursor = this.config.cursor_default;
if (this.pic.parentNode.className == 'pic_container') {
//use existing container
this.pic_container = this.pic.parentNode;
}
else {
//dynamically create container
this.pic_container = document.createElement("div");
this.pic_container.className = 'pic_container';
this.pic.parentNode.insertBefore(this.pic_container, this.pic);
//ref: If the node already exists it is removed from current parent node, then added to new parent node.
this.pic_container.appendChild(this.pic);
}
this.fireEvent('onLoadImage', this.pic);
return true;
}
};
/**
* Fires custom hook onStatusMessage, passing the status string.
* Use this to update your GUI.
* @author Adam Maschek (adam.maschek(at)gmail.com)
* @date 26-07-2008 13:22:54
* @param str The status string
*/
imgmap.prototype.statusMessage = function(str) {
this.fireEvent('onStatusMessage', str);
};
/**
* Adds basic logging functionality using firebug console object if available.
* Also tries to use AIR introspector if available.
* @date 20-02-2007 17:55:18
* @author Adam Maschek (adam.maschek(at)gmail.com)
* @param obj The object or string you want to debug/echo.
* @level level The log level, 0 being the smallest issue.
*/
imgmap.prototype.log = function(obj, level) {
if (level === '' || typeof level == 'undefined') {level = 0;}
if (this.config.loglevel != -1 && level >= this.config.loglevel) {
this.logStore.push({level: level, obj: obj});
}
if (typeof console == 'object') {
console.log(obj);
}
else if (this.isOpera) {
opera.postError(level + ': ' + obj);
}
else if (typeof air == 'object') {
//we are inside AIR
if (typeof air.Introspector == 'object') {
air.Introspector.Console.log(obj);
}
else {
air.trace(obj);
}
}
else {
if (level > 1) {
//alert(level + ': ' + obj);
//dump with all pevious errors:
var msg = '';
for (var i=0, le = this.logStore.length; i<le; i++) {
msg+= this.logStore[i].level + ': ' + this.logStore[i].obj + "\n";
}
alert(msg);
}
else {
window.defaultStatus = (level + ': ' + obj);
}
}
};
/**
* Produces the image map HTML output with the defined areas.
* Invokes getMapInnerHTML.
* @author Adam Maschek (adam.maschek(at)gmail.com)
* @date 2006-06-06 15:10:27
* @param flags Currently ony 'noscale' used to prevent scaling of coordinates in preview mode.
* @return The generated html code.
*/
imgmap.prototype.getMapHTML = function(flags) {
var html = '<map id="'+this.getMapId()+'" name="'+this.getMapName()+'">' + this.getMapInnerHTML(flags) + this.waterMark + '</map>';
this.fireEvent('onGetMap', html);
//alert(html);
return html;
};
/**
* Get the map areas part only of the current imagemap.
* @see #getMapHTML
* @author adam
* @param flags Currently ony 'noscale' used to prevent scaling of coordinates in preview mode.
* @return The generated map code without the map wrapper.
*/
imgmap.prototype.getMapInnerHTML = function(flags) {
var html, coords;
html = '';
//foreach area properties
for (var i=0, le = this.areas.length; i<le; i++) {
if (this.areas[i]) {
if (this.areas[i].shape && this.areas[i].shape != 'undefined') {
coords = this.areas[i].lastInput;
if (flags && flags.match(/noscale/)) {
//for preview use real coordinates, not scaled
var cs = coords.split(',');
for (var j=0, le2 = cs.length; j<le2; j++) {
cs[j] = Math.round(cs[j] * this.globalscale);
}
coords = cs.join(',');
}
html+= '<area shape="' + this.areas[i].shape + '"' +
' alt="' + this.areas[i].aalt + '"' +
' title="' + this.areas[i].atitle + '"' +
' coords="' + coords + '"' +
' href="' + this.areas[i].ahref + '"' +
' target="' + this.areas[i].atarget + '" />';
}
}
}
//alert(html);
return html;
};
/**
* Get the map name of the current imagemap.
* If doesnt exist, nor map id, generate a new name based on timestamp.
* The most portable solution is to use the same value for id and name.
* This also conforms the HTML 5 specification, that says:
* "If the id attribute is also specified, both attributes must have the same value."
* @link http://www.w3.org/html/wg/html5/#the-map-element
* @author adam
* @see #getMapId
* @return The name of the map.
*/
imgmap.prototype.getMapName = function() {
if (this.mapname === '') {
if (this.mapid !== '') {return this.mapid;}
var now = new Date();
this.mapname = 'imgmap' + now.getFullYear() + (now.getMonth()+1) + now.getDate() + now.getHours() + now.getMinutes() + now.getSeconds();
}
return this.mapname;
};
/**
* Get the map id of the current imagemap.
* If doesnt exist, use map name.
* @author adam
* @see #getMapName
* @return The id of the map.
*/
imgmap.prototype.getMapId = function() {
if (this.mapid === '') {
this.mapid = this.getMapName();
}
return this.mapid;
};
/**
* Convert wild shape names to normal ones.
* @date 25-12-2008 19:27:06
* @param shape The name of the shape to convert.
* @return The normalized shape name, rect as default.
*/
imgmap.prototype._normShape = function(shape) {
if (!shape) {return 'rect';}
shape = this.trim(shape).toLowerCase();
if (shape.substring(0, 4) == 'rect') {return 'rect';}
if (shape.substring(0, 4) == 'circ') {return 'circle';}
if (shape.substring(0, 4) == 'poly') {return 'poly';}
return 'rect';
};
/**
* Try to normalize coordinates that came from:
* 1. html textarea
* 2. user input in the active area's input field
* 3. from the html source in case of plugins or highlighter
* Example of inputs that need to be handled:
* 035,035 075,062
* 150,217, 190,257, 150,297,110,257
* @author adam
* @param coords The coordinates in a string.
* @param shape The shape of the object (rect, circle, poly, bezier1).
* @param flag Flags that modify the operation. (fromcircle, frompoly, fromrect, preserve)
* @returns The normalized coordinates.
*/
imgmap.prototype._normCoords = function(coords, shape, flag) {
//function level var declarations
var i;//generic cycle counter
var sx;//smallest x
var sy;//smallest y
var gx;//greatest x
var gy;//greatest y
var temp, le;
//console.log('normcoords: ' + coords + ' - ' + shape + ' - ' + flag);
coords = this.trim(coords);
if (coords === '') {return '';}
var oldcoords = coords;
//replace some general junk
coords = coords.replace(/(\d)([^\d\.])+(\d)/g, "$1,$3"); // Other software might create decimal points, respect them
coords = coords.replace(/,\D+(\d)/g, ",$1");//cut leading junk
coords = coords.replace(/,0+(\d)/g, ",$1");//cut leading zeros
coords = coords.replace(/(\d)(\D)+,/g, "$1,");
coords = coords.replace(/^\D+(\d)/g, "$1");//cut leading junk
coords = coords.replace(/^0+(\d)/g, "$1");//cut leading zeros
coords = coords.replace(/(\d)(\D)+$/g, "$1");//cut trailing junk
//console.log('>'+coords + ' - ' + shape + ' - ' + flag);
//now fix other issues
var parts = coords.split(',');
if (shape == 'rect') {
if (flag == 'fromcircle') {
var r = parts[2];
parts[0] = parts[0] - r;
parts[1] = parts[1] - r;
parts[2] = parseInt(parts[0], 10) + 2 * r;
parts[3] = parseInt(parts[1], 10) + 2 * r;
}
else if (flag == 'frompoly') {
sx = parseInt(parts[0], 10); gx = parseInt(parts[0], 10);
sy = parseInt(parts[1], 10); gy = parseInt(parts[1], 10);
for (i=0, le = parts.length; i<le; i++) {
if (i % 2 === 0 && parseInt(parts[i], 10) < sx) {
sx = parseInt(parts[i], 10);}
if (i % 2 === 1 && parseInt(parts[i], 10) < sy) {
sy = parseInt(parts[i], 10);}
if (i % 2 === 0 && parseInt(parts[i], 10) > gx) {
gx = parseInt(parts[i], 10);}
if (i % 2 === 1 && parseInt(parts[i], 10) > gy) {
gy = parseInt(parts[i], 10);}
//console.log(sx+","+sy+","+gx+","+gy);
}
parts[0] = sx; parts[1] = sy;
parts[2] = gx; parts[3] = gy;
}
if (!(parseInt(parts[1], 10) >= 0)) {parts[1] = parts[0];}
if (!(parseInt(parts[2], 10) >= 0)) {parts[2] = parseInt(parts[0], 10) + 10;}
if (!(parseInt(parts[3], 10) >= 0)) {parts[3] = parseInt(parts[1], 10) + 10;}
if (parseInt(parts[0], 10) > parseInt(parts[2], 10)) {
temp = parts[0];
parts[0] = parts[2];
parts[2] = temp;
}
if (parseInt(parts[1], 10) > parseInt(parts[3], 10)) {
temp = parts[1];
parts[1] = parts[3];
parts[3] = temp;
}
coords = parts[0]+","+parts[1]+","+parts[2]+","+parts[3];
//console.log(coords);
}
else if (shape == 'circle') {
if (flag == 'fromrect') {
sx = parseInt(parts[0], 10); gx = parseInt(parts[2], 10);
sy = parseInt(parts[1], 10); gy = parseInt(parts[3], 10);
//use smaller side
parts[2] = (gx - sx < gy - sy) ? gx - sx : gy - sy;
parts[2] = Math.floor(parts[2] / 2);//radius
parts[0] = sx + parts[2];
parts[1] = sy + parts[2];
}
else if (flag == 'frompoly') {
sx = parseInt(parts[0], 10); gx = parseInt(parts[0], 10);
sy = parseInt(parts[1], 10); gy = parseInt(parts[1], 10);
for (i=0, le = parts.length; i<le; i++) {
if (i % 2 === 0 && parseInt(parts[i], 10) < sx) {
sx = parseInt(parts[i], 10);}
if (i % 2 === 1 && parseInt(parts[i], 10) < sy) {
sy = parseInt(parts[i], 10);}
if (i % 2 === 0 && parseInt(parts[i], 10) > gx) {
gx = parseInt(parts[i], 10);}
if (i % 2 === 1 && parseInt(parts[i], 10) > gy) {
gy = parseInt(parts[i], 10);}
//console.log(sx+","+sy+","+gx+","+gy);
}
//use smaller side
parts[2] = (gx - sx < gy - sy) ? gx - sx : gy - sy;
parts[2] = Math.floor(parts[2] / 2);//radius
parts[0] = sx + parts[2];