OSDN Git Service

0fd69fdbd7273531fb0d2f9b8875008bb939b59f
[pettanr/pettanr.git] / public / assets / peta.apps.js
1 /*
2  * pettanR peta.apps.js
3  *   version 0.5.5
4  *   
5  * author:
6  *   itozyun
7  * licence:
8  *   3-clause BSD
9  */
10
11 ( function( pettanr, gOS, window, undefined ){
12
13 /*
14  * PettanR service driver.
15  */
16         var MyAuthorID = 'current_author' in window ? current_author.id : ( pettanr.CONST.SERVER_SUPPORT === false ? 1 : -1 ),
17                 MyArtistID = 'current_artist' in window ? current_artist.id : ( pettanr.CONST.SERVER_SUPPORT === false ? 1 : -1 ),
18                 Driver     = null,
19                 FileAPI    = gOS.registerDriver( function(){
20                         var self = Driver = this;
21                         
22                         function onLoadJson( _file, _json ){
23                                 var _access = FileAPI.getFileDataAccess( _file ),
24                                         _data = _access !== null ? _access.DATA : null,
25                                         l;
26                                 if( _data === null ){
27                                         onErrorJson( _file);
28                                         return;
29                                 }
30                                 _data.state = Const.FILE.STATE.OK;
31                                 
32                                 if( Type.isArray( _json ) === true ){
33                                         l = _json.length;
34                                         if( l === 0) return;
35                                         for( var i=0; i<l; ++i ){
36                                                 buildFileData( _json[ i], _data);
37                                         }                       
38                                 } else
39                                 if( _json.id ){
40                                         buildFileData( _json, _data );
41                                 }
42                                 _file.dispatchEvent( FileAPI.createFileEvent( Const.FILE.EVENT.GET_SEQENTIAL_FILES, _file, 'children', null) );
43                         }
44                         function onErrorJson( _file ){ 
45                                 var _data = FileAPI.getFileData( _file);
46                                 if( _data !== null){
47                                         _data.state = Const.FILE.STATE.ERROR;
48                                 }
49                         }
50                         function buildFileData( _data, _parent ){
51                                 var _array, i, l;
52                                 // Panel
53                                 if( _parent === FILE_DATA_PANELS_ROOT ){
54                                         _data.type = FILE_TYPE.PANEL;
55                                         _array = PANEL_ARRAY;
56                                 } else
57                                 // Comic
58                                 if( _parent === FILE_DATA_COMICS_ROOT ){
59                                         _data.type = FILE_TYPE.COMIC;
60                                         _array = COMIC_ARRAY;
61                                 } else
62                                 if( _parent.type === FILE_TYPE.COMIC ){
63                                         _array = COMIC_ARRAY;
64                                 } else
65                                 // Lisence
66                                 if( _parent === FILE_DATA_LISENCE_ROOT ){
67                                         _data.type = FILE_TYPE.LICENSE;
68                                         _array = ORIGINAL_LICENSE_ARRAY;
69                                 } else
70                                 // Author
71                                 if( _parent === FILE_DATA_AUTHOR_ROOT ){
72                                         _data.type = FILE_TYPE.AUTHOR;
73                                         _array = AUTHOR_ARRAY;
74                                 } else
75                                 // Artist
76                                 if( _parent === FILE_DATA_ARTIST_ROOT ){
77                                         _data.type = FILE_TYPE.ARTIST;
78                                         _array = ARTIST_ARRAY;
79                                 } else          
80                                 // Picture
81                                 if( _parent === FILE_DATA_PICTURE_ROOT || _parent === FILE_DATA_MY_PICTURES_ROOT ){
82                                         _data.type = FILE_TYPE.PICTURE;
83                                         _array = RESOURCE_PICTURE_ARRAY;
84                                         // original_license を含まなければ、license object を削除して ビットデータ で保持
85                                         // original_license なら ファイルを作る buildFileData( _license, FILE_DATA_LISENCE_ROOT)
86                                         var _license = _data.license,
87                                                 _rule,
88                                                 _Math_pow = Math.pow,
89                                                 _bits = 0;
90                                         if( typeof _license === 'object'){
91                                                 for( i=0, l=BASIC_LICENSES.length; i<l; ++i ){
92                                                         _rule = _license[ BASIC_LICENSES[ i]];
93                                                         if( typeof _rule === 'number' && _rule === 1 ){
94                                                                 _bits += _Math_pow( 2, i );
95                                                         }
96                                                 }
97                                                 _data.license = _bits;
98                                         }
99                                 } else {
100                                         alert( 'error' );
101                                 }
102                                 
103                                 _data.driver = Driver;
104                                 
105                                 // _array に _data を格納 または 上書き
106                                 if( typeof _data.id === 'number' && _data.id > 0 ){
107                                         var _id = _data.id - 1,
108                                                 __data = _array[ _id ],
109                                                 _reserved = Const.FILE.DATA_PROPERTY_RESERVED.join( ', ' );
110                                         if( __data ){
111                                                 for( var key in _data){
112                                                         if( _reserved.indexOf( key ) === -1 ){
113                                                                 __data[ key ] = _data[ key ];
114                                                         };
115                                                 };
116                                                 _data = __data; // このタイミングで参照が切れるので注意!!
117                                         } else {
118                                                 _array[ _id ] = _data;
119                                         };
120                                 } else {
121                                         alert( 'error' );
122                                 };
123                 
124                                 // Author
125                                 // Artist
126                                 if( _parent === FILE_DATA_AUTHOR_ROOT || _parent === FILE_DATA_ARTIST_ROOT ){
127                                         addChildData( _parent, _data );
128                                 } else
129                                 // Comic + Panels
130                                 if( _parent.type === FILE_TYPE.COMIC || _parent === FILE_DATA_COMICS_ROOT ){
131                                         var _panels = _data.panels,
132                                                 _panel;
133                                         if( _panels && Type.isArray( _panels ) === true ){
134                                                 
135                                                 for( i=0, l=_panels.length; i<l; ++i){
136                                                         _panel = buildFileData( _panels[ i ], FILE_DATA_PANELS_ROOT );
137                                                         /*
138                                                          * 間違い! t 順に格納
139                                                          */
140                                                         addChildData( _data, _panel );
141                                                 };
142                                                 delete _data.panels;
143                                         } else {
144                                                 if( _data.json !== null ){
145                                                         _data.json = true;
146                                                 };
147                                                 if( Type.isArray( _data.children ) === false ){
148                                                         _data.children = [];
149                                                 };
150                                         };
151                                         var _author = _data.author || getResource( AUTHOR_ARRAY, _data.author_id );
152                                         if( _author ){
153                                                 _data.author = _author = buildFileData( _author, FILE_DATA_AUTHOR_ROOT );
154                                                 addChildData( _author, _data );
155                                                 _author.id === MyAuthorID && addChildData( FILE_DATA_MY_COMICS_ROOT, _data );
156                                         };
157                                         if( _parent === FILE_DATA_COMICS_ROOT ){
158                                                 addChildData( FILE_DATA_LATEST_COMICS, _data);
159                                         };
160                                 } else
161                                 // Panel
162                                 if( _parent === FILE_DATA_PANELS_ROOT ){
163                                         _data.comic = getResource( COMIC_ARRAY, _data.comic_id );
164                                         _data.author = getResource( AUTHOR_ARRAY, _data.author_id );
165                 
166                                         // picture data をファイルに取り出し
167                                         var _elements = _data.panel_elements,
168                                                 _elm;
169                                         if( Type.isArray( _elements ) === true ){
170                                                 for( i=0, l=_elements.length; i<l; ++i){
171                                                         _elm = _elements[ i];
172                                                         if( _elm.resource_picture ){
173                                                                 _elm.resource_picture = buildFileData( _elm.resource_picture, FILE_DATA_PICTURE_ROOT ); // 上記参照切れに備えてここで上書き
174                                                         } else {
175                                                                 _elm.resource_picture = getResource( RESOURCE_PICTURE_ARRAY, _elm.resource_picture_id );
176                                                         };
177                                                 };
178                                         };
179                                 } else
180                                 // Picture
181                                 if( _data.type == FILE_TYPE.PICTURE ){
182                                         var _artist = _data.artist || getResource( ARTIST_ARRAY, _data.artist_id );
183                                         if( _artist){
184                                                 _data.artist = _artist = buildFileData( _artist, FILE_DATA_ARTIST_ROOT );
185                                                 addChildData( _artist, _data );
186                                                 if( _artist.id === MyArtistID ){
187                                                         addChildData( FILE_DATA_MY_PICTURES_ROOT, _data );
188                                                         //FILE_DATA_MY_PICTURES_ROOT.type = FILE_TYPE.ARTIST;
189                                                         //FILE_DATA_MY_PICTURES_ROOT.id = MyArtistID;
190                                                 };
191                                         };
192                                 };
193                                 return _data;
194                         }
195                         function addChildData( _parent, _child ){
196                                 if( Type.isArray( _parent.children ) === false){
197                                         _parent.children = [];
198                                 };
199                                 Util.getIndex( _parent.children, _child ) === -1 && _parent.children.push( _child );
200                         };
201                         function getResource( _array, _id ){
202                                 if( Type.isArray( _array ) === false || Type.isNumber( _id ) === false || _id < 1 ) return null;
203                                 var _data = _array[ _id - 1 ];
204                                 if( !_data ){
205                                         _data = _array[ _id - 1 ] = {};
206                                 };
207                                 return _data;
208                         };
209                         
210                         this.getSeqentialFiles = function( _file ){
211                                 var _data = FileAPI.getFileData( _file ),
212                                         _json = _data !== null ? _data.json : null;
213                                 if( _json === true && _data.type === FILE_TYPE.COMIC ){
214                                         if( pettanr.CONST.SERVER_SUPPORT === false ){
215                                                 _json = [ 'json\/comics_', _data.id, '.json' ].join( '' );
216                                         } else {
217                                                 _json = [ pettanr.CONST.PETTANR_ROOT_PATH, 'comics\/', _data.id, '.json\/play\/' ].join( '' );
218                                         }
219                                 }
220                                 if( typeof _json === 'string' ){
221                                         FileAPI.getJson( _file, _json, onLoadJson, onErrorJson );
222                                         _data.state = Const.FILE.STATE.LOADING;
223                                         _data.json  = null;
224                                         return;
225                                 }
226                         };
227                         this.getName = function( _file ){
228                                 var _data = FileAPI.getFileData( _file ),
229                                         _type = _data !== null ? _data.type : null;
230                                 if( _type === FILE_TYPE.PICTURE ){
231                                         return [ _data.id, _data.ext ].join( '.' );
232                                 } else
233                                 if( _type === FILE_TYPE.PANEL ){
234                                         return [ _data.t, ':', _data.comic.title ].join( '' );
235                                 } else
236                                 if( _type === FILE_TYPE.COMIC ){
237                                         return _data.title;
238                                 } else
239                                 if( _type === FILE_TYPE.ARTIST ){
240                                         return [ _data.name, '画伯' ].join( '' );
241                                 } else
242                                 if( _type === FILE_TYPE.AUTHOR ){
243                                         return [ _data.name, '先生' ].join( '' );
244                                 };
245                                 return _data.name;
246                         };
247                         this.getThumbnail = function( _file ){
248                                 var _data = FileAPI.getFileData( _file ),
249                                         _type = _data !== null ? _data.type : null;
250                                 if( _type === FILE_TYPE.PICTURE ){
251                                         return { image: [ pettanr.CONST.RESOURCE_PICTURE_PATH, 'thumbnail/', _data.id, '.', _data.ext ].join( '' )};
252                                 }
253                                 if( _data === FILE_DATA_COMICS_ROOT ){
254                                         return { className: 'file-type-cabinet' };
255                                 }
256                                 if( _type === FILE_TYPE.COMIC ){
257                                         return { className: 'file-type-comic' };
258                                 }
259                                 if( _type === FILE_TYPE.PANEL ){
260                                         return { className: 'file-type-panel' };
261                                 }
262                                 if( _type === FILE_TYPE.AUTHOR ){
263                                         return { className: 'file-type-author' };
264                                 }
265                                 if( _type === FILE_TYPE.ARTIST ){
266                                         return { className: 'file-type-artist' };
267                                 }
268                                 if( _type === FILE_TYPE.FOLDER){
269                                         return { className: 'file-type-folder' };
270                                 }
271                                 return { className: 'file-type-broken' };
272                         };
273                         this.getSummary = function( _file ){
274                                 var _data = FileAPI.getFileData( _file ),
275                                         _type = _data !== null ? _data.type : null;
276                                 if( _type === FILE_TYPE.PICTURE ){
277                                         return [ _data.width, 'x', _data.height, ', filesize:', _data.filesize, ', lisence:', _data.license ].join( '' );
278                                 }
279                                 if( _data === FILE_DATA_COMICS_ROOT ){
280                                         return 'cabinet file';
281                                 }
282                                 if( _type === FILE_TYPE.COMIC ){
283                                         return 'comic file, id:' + _data.id;
284                                 }
285                                 if( _type === FILE_TYPE.PANEL ){
286                                         return [ _data.width, 'x', _data.height ].join( '' );
287                                 }
288                                 if( _type === FILE_TYPE.AUTHOR ){
289                                         return 'author file, id:' + _data.id;
290                                 }
291                                 if( _type === FILE_TYPE.ARTIST ){
292                                         return [ 'id:', _data.id, ' Email:', _data.email || 'empty' , ', HP:', _data.homepage_url || 'empty' ].join( '' );
293                                 }
294                                 if( _type === FILE_TYPE.FOLDER ){
295                                         return 'pettanR folder';
296                                 }
297                                 return 'pettanR unknown file';
298                         };
299                         this.read = function( _file ){
300                                 var _data = FileAPI.getFileData( _file ),
301                                         _type = _data !== null ? _data.type : null,
302                                         ret;
303                                 if( _type === FILE_TYPE.COMIC ){
304                                         // children を panels に deepcopy
305                                         ret = {};
306                                         for( var key in _data ){
307                                                 ret[ key ] = _data[ key ]
308                                         }
309                                         ret.panels = _data.children;
310                                         return ret;
311                                 }
312                                 if( _type === FILE_TYPE.PANEL ){
313                                 }
314                                 if( _type === FILE_TYPE.PANEL_PICTURE ){
315                                         
316                                 }
317                                 if( _type === FILE_TYPE.BALLOON ){
318                                 }
319                                 if( _type === FILE_TYPE.PICTURE ){
320                                 }
321                         };
322                         this.write = function( _file, _newData, _onUpdate ){
323                                 var _data = FileAPI.getFileData( _file ),
324                                         _type = _data !== null ? _data.type : null;
325                                 if( _type === FILE_TYPE.COMIC ){
326                                 }
327                                 if( _type === FILE_TYPE.PANEL ){
328                                 }
329                                 if( _type === FILE_TYPE.PANEL_PICTURE ){
330                                         
331                                 }
332                                 if( _type === FILE_TYPE.BALLOON ){
333                                 }
334                                 if( _type === FILE_TYPE.PICTURE ){
335                                 }                               
336                         };
337                         this.viewerApplicationList = function( _file ){
338                                 var _data = FileAPI.getFileData( _file ),
339                                         _type = _data !== null ? _data.type : null;
340                                 if( _type === FILE_TYPE.PANEL ){
341                                         return [ Reader ];
342                                 }
343                                 if( _type === FILE_TYPE.COMIC ){
344                                         return [ Reader ];
345                                 }       
346                                 if( _data === FILE_DATA_MY_PICTURES_ROOT ){
347                                         return [ PremiumSatge ];
348                                 }
349                                 if( _type === FILE_TYPE.ARTIST ){
350                                         return [ PremiumSatge ];
351                                 }
352                                 return [];
353                         };
354                         this.editorApplicationList = function( _file ){
355                                 var _data = FileAPI.getFileData( _file ),
356                                         _type = _data !== null ? _data.type : null;
357                                 if( _type === FILE_TYPE.PANEL ){
358                                         return [ Editor ];
359                                 }
360                                 if( _type === FILE_TYPE.COMIC ){
361                                         return [Editor, ComicConsole ];
362                                 }
363                                 return [];
364                         }
365                 }),
366                 Const = FileAPI.getConst(),
367                 FILE_TYPE = Util.extend(
368                         Const.FILE.TYPE,
369                         {
370                                 COMIC:                          FileAPI.createFileTypeID(),
371                                 PANEL:                          FileAPI.createFileTypeID(),
372                                 PICTURE:                        FileAPI.createFileTypeID(),
373                                 PANEL_PICTURE:          FileAPI.createFileTypeID(),
374                                 BALLOON:                        FileAPI.createFileTypeID(),
375                                 AUTHOR:                         FileAPI.createFileTypeID(),
376                                 ARTIST:                         FileAPI.createFileTypeID(),
377                                 LICENSE:                        FileAPI.createFileTypeID()
378                         }
379                 ),
380                 FILE_DATA_SERVICE_ROOT = {
381                         name:           'PettanR root',
382                         type:           FILE_TYPE.FOLDER,
383                         children:       []
384                 },
385                 FILE_DATA_COMICS_ROOT = {
386                         name:           'Comics',
387                         type:           FILE_TYPE.FOLDER,
388                         children:       [],
389                         driver:         Driver,
390                         json:           pettanr.CONST.URL_COMICS_JSON
391                 },
392                 FILE_DATA_PANELS_ROOT = {
393                         name:           'Panels',
394                         type:           FILE_TYPE.FOLDER,
395                         children:       [],
396                         driver:         Driver,
397                         json:           pettanr.CONST.URL_PANELS_JSON
398                 },
399                 FILE_DATA_PICTURE_ROOT = {
400                         name:           'Picutures',
401                         type:           FILE_TYPE.FOLDER,
402                         children:       [],
403                         driver:         Driver,
404                         json:           pettanr.CONST.URL_RESOURCE_PICTURES_JSON
405                 },
406                 FILE_DATA_MY_COMICS_ROOT = {
407                         name:           'My Comics',
408                         type:           FILE_TYPE.FOLDER,
409                         children:       [],
410                         driver:         Driver,
411                         id:                     MyAuthorID
412                 },
413                 FILE_DATA_LATEST_COMICS = {
414                         name:           'Latest Comics',
415                         type:           FILE_TYPE.FOLDER,
416                         children:       []
417                 },
418                 FILE_DATA_MY_PICTURES_ROOT = {
419                         name:           'My Pictures',
420                         type:           FILE_TYPE.FOLDER,
421                         children:       [],
422                         driver:         Driver,
423                         json:           pettanr.CONST.URL_ORIGINAL_PICTURES_JSON,
424                         id:                     MyArtistID
425                 },
426                 FILE_DATA_AUTHOR_ROOT = {
427                         name:           'Authors',
428                         type:           FILE_TYPE.FOLDER,
429                         children:       []
430                 },
431                 FILE_DATA_ARTIST_ROOT = {
432                         name:           'Artists',
433                         type:           FILE_TYPE.FOLDER,
434                         children:       []
435                 },
436                 FILE_DATA_LISENCE_ROOT = {
437                         name:           'Original Lisences',
438                         type:           FILE_TYPE.FOLDER,
439                         children:       []
440                 },
441                 FILE_DATA_BALLOON_ROOT = {
442                         name:           'Balloon templetes',
443                         type:           FILE_TYPE.FOLDER,
444                         children:       []
445                 },
446                 AUTHOR_ARRAY = [],
447                 ARTIST_ARRAY = [],
448                 PANEL_ARRAY  = [],
449                 COMIC_ARRAY  = [],
450                 RESOURCE_PICTURE_ARRAY = [],
451                 BALLOON_TEMPLETE_ARRAY = [],
452                 ORIGINAL_LICENSE_ARRAY = [],
453                 BASIC_LICENSES = 'cc_by,cc_nc,cc_nd,cc_sa,keep_aspect_ratio,no_convert,no_flip,no_resize'.split( ',');
454         FILE_DATA_SERVICE_ROOT.children.push( FILE_DATA_COMICS_ROOT, FILE_DATA_PICTURE_ROOT, FILE_DATA_PANELS_ROOT, FILE_DATA_LISENCE_ROOT, FILE_DATA_BALLOON_ROOT );
455         FILE_DATA_COMICS_ROOT.children.push( FILE_DATA_MY_COMICS_ROOT, FILE_DATA_LATEST_COMICS, FILE_DATA_AUTHOR_ROOT );
456         FILE_DATA_PICTURE_ROOT.children.push( FILE_DATA_MY_PICTURES_ROOT, FILE_DATA_ARTIST_ROOT );
457         
458         FileAPI.createFolderUnderRoot( FILE_DATA_SERVICE_ROOT );
459
460         Driver.isPettanrFileInstance = function( _file ){
461                 if( FileAPI.isFileInstance( _file ) === true ){
462                         var _data = FileAPI.getFileData( _file.getUID() );// _file でなく  _file.getUID()
463                         return _data !== null && _data.driver === Driver;
464                 }
465                 return false;
466         };
467
468 var Cabinet = gOS.registerApplication( function(){
469         var self         = this,
470                 finder       = null,
471                 tree         = null,
472                 headerH      = 0;
473
474         this.bgColor     = '#FFFFFF';
475         this.MIN_WIDTH   = 500;
476         this.MIN_HEIGHT  = 300;
477         this.onInit = function(){
478                 self.rootElement.id = 'cabinet-root';
479                 self.rootElement.innerHTML = [
480                         '<div id="cabinet-header">Cabinet<div id="cabinet-close-button">x</div></div>',
481                         '<div id="cabinet-container" class="finder-container"></div>'
482                 ].join( '' );
483                 
484                 self.fetchCSS( '/assets/peta.apps.css' );
485                 
486                 tree   = FileAPI.createTree( FILE_DATA_SERVICE_ROOT );
487                 
488                 delete self.onInit;
489         };
490         this.onOpen = function( _w, _h ){
491                 headerH = Util.getElementSize( document.getElementById( 'cabinet-header' ) ).height;
492                 
493                 self.addMouseEventListener( document.getElementById( 'cabinet-close-button' ), 'click', Cabinet.shutdown );
494                 
495                 finder = self.createFinder( self.rootElement, tree );
496                 self.onPaneResize( _w, _h );
497         };
498         this.onClose = function(){
499                 finder.destroy();
500                 tree.destroy();
501                 finder = tree = null;
502         };
503         this.onPaneResize = function( _w, _h ){
504                 finder.resize( _w, _h - headerH );
505         };
506 }, false, true, 'Cabinet', 'cabinet', null, '#1C1C1C' );
507
508 var Gallery = gOS.registerApplication( function(){
509         var self         = this,
510                 finder       = null,
511                 tree         = null,
512                 headerH      = 0;
513
514         this.bgColor     = '#FFFFFF';
515         this.MIN_WIDTH   = 500;
516         this.MIN_HEIGHT  = 300;
517         this.onInit = function(){
518                 self.rootElement.id        = 'gallery-root';
519                 self.rootElement.innerHTML = [
520                         '<div id="gallery-header">Cabinet<div id="gallery-close-button">x</div></div>',
521                         '<div id="gallery-container" class="finder-container"></div>'
522                 ].join( '' );
523                 
524                 self.fetchCSS( '/assets/peta.apps.css' );
525                 
526                 tree = FileAPI.createTree( FILE_DATA_PICTURE_ROOT );
527                 var     _root  = tree.getRootFile(),
528                         _myPic = _root.getChildFileByIndex( 0 ),
529                         _pic   = _root.getChildFileByIndex( 1 );
530                 _myPic.getSeqentialFiles();
531                 _pic.getSeqentialFiles();
532                 _myPic.destroy();
533                 _pic.destroy();
534         };
535         this.onOpen = function( _w, _h ){
536                 headerH = Util.getElementSize( document.getElementById( 'gallery-header' ) ).height;
537                 
538                 self.addMouseEventListener( document.getElementById( 'gallery-close-button' ), 'click', Gallery.shutdown );
539                 
540                 finder = self.createFinder( self.rootElement, tree );
541                 self.onPaneResize( _w, _h );
542         };
543         this.onClose = function(){
544                 finder.destroy();
545                 tree.destroy();
546                 finder = tree = null;
547         };
548         this.onPaneResize = function( _w, _h ){
549                 finder.resize( _w, _h - headerH );
550         };
551 }, false, true, 'Gallery', 'gallery', null, '#01A31C' );
552
553 var Backyard = gOS.registerApplication( function(){
554         var self         = this;
555         
556         this.bgColor     = '#FFFFFF';
557         this.MIN_WIDTH   = 500;
558         this.MIN_HEIGHT  = 300;
559         this.onInit = function(){
560         };
561         this.onOpen = function( _w, _h, _option ){
562         }
563         this.onClose = function(){
564         }
565         this.onPaneResize = function( _w, _h){
566         }
567 }, false, false, 'Settings', 'settings', null, '#DDDDDD' );
568
569 if( pettanr.DEBUG === true){
570         var Debug = gOS.registerApplication( function(){
571                 var self = this,
572                         elmDl,
573                         data = ( function(){
574                                 var data = {
575                                         pettanR:       pettanr.version,
576                                         ua:            navigator.userAgent,
577                                         platform:      navigator.platform,
578                                         appVersion:    navigator.appVersion,
579                                         appCodeName:   navigator.appCodeName,
580                                         appName:       navigator.appName,
581                                         language:      navigator.browserLanguage || navigator.language,
582                                         ActiveX:       UA.ACTIVEX,
583                                         RenderingMode: UA.isStanderdMode === true ? 'Standerd' : 'Quirks'
584                                 };
585                                 if( UA.IE ){
586                                         data.version = UA.IE;
587                                         if( UA.ieVersion >= 8 ) data.RenderingVersion = UA.ieRenderingVersion;
588                                         data.browserType = UA.STANDALONE === true ? 'Standalone' : 'bundle';
589                                         if( UA.ieVersion < 9 ) {
590                                                 data.vml = UA.VML;
591                                         } else {
592                                                 data.svg = UA.SVG;
593                                         }
594                                 };
595                                 return data;
596                         })();
597
598                 this.bgColor     = '#FFFFFF';
599                 this.MIN_WIDTH   = 500;
600                 this.MIN_HEIGHT  = 300;
601                 this.onInit = function(){
602                         self.rootElement.id = 'debug-root';
603                         self.rootElement.innerHTML = '<dl id="useragent" class="dl-table clearfix"></dl>';
604                 };
605                 this.onOpen = function( _w, _h, _option ){
606                         elmDl = document.getElementById( 'useragent' );
607                         var elmDt, elmDd;
608                         for( var key in data ){
609                                 elmDt = document.createElement( 'dt' );
610                                 elmDt.innerHTML = key;
611                                 elmDd = document.createElement( 'dd' );
612                                 elmDd.innerHTML = '' + data[ key];
613                                 if( !data[ key ] ) elmDd.style.color = 'red';
614                                 elmDl.appendChild( elmDt );
615                                 elmDl.appendChild( elmDd );
616                         }
617                 }
618                 this.onClose = function(){
619                         
620                 }
621                 this.onPaneResize = function( _w, _h ){
622                         
623                 }
624         }, false, true, 'Debug', 'debug', null, '#01A31C' );
625 }
626
627 /* ----------------------------------------
628  * Image Group Exproler
629  *  - overlay
630  */
631 var PremiumSatge = gOS.registerApplication( function(){
632         var BASE_PATH      = pettanr.CONST.RESOURCE_PICTURE_PATH,
633                 THUMB_PATH     = BASE_PATH, // + 'thumbnail/',
634                 LIMIT_FILESIZE = 1024 * 10,
635                 ICON_ARRAY     = [];
636                 
637         var self             = this,
638                 tree, rootFile,
639                 winW, winH, wrapX,
640                 elmContainer, elmIconOrigin, elmName, elmButton,
641                 containerW, containerH, 
642                 itemW, itemH, buttonW,
643                 onUpdate        = null,
644                 onUpdateData    = null,
645                 artistID        = -1;
646
647         var ImageGroupIconClass = function( index, data ){
648                 var elmIconWrap     = elmIconOrigin.cloneNode( true ),
649                         elmIconTitle    = Util.getElementsByClassName( elmIconWrap, 'image-group-item-title' )[ 0 ],
650                         SRC             = [ BASE_PATH, data.id, '.', data.ext ].join( ''),
651                         LOW_SRC         = data.filesize && data.filesize > LIMIT_FILESIZE ? [ THUMB_PATH, data.id, '.', data.ext ].join( '') : null,
652                         reversibleImage = null,
653                         timer           = null,
654                         onEnterFlag     = false,
655                         instance        = this;
656                 elmContainer.appendChild( elmIconWrap );
657                 elmIconWrap.style.left = ( index * itemW ) + 'px';
658                 elmIconTitle.appendChild( document.createTextNode( data.filesize + 'bytes' ) );
659                 
660                 function onImageLoad( url, _imgW, _imgH ){
661                         data.width  = _imgW = _imgW || data.width  || 64;
662                         data.height = _imgH = _imgH || data.height || 64;
663                         elmIconTitle.firstChild.data = _imgW + 'x' + _imgH;
664                         var zoom = 128 /( _imgW > _imgH ? _imgW : _imgH ),
665                                 MATH_FLOOR = Math.floor,
666                                 h = MATH_FLOOR( _imgH * zoom ),
667                                 w = MATH_FLOOR( _imgW * zoom );
668                         reversibleImage.elm.style.cssText = [
669                                 'width:',  w, 'px;',
670                                 'height:', h, 'px;',
671                                 'margin:', MATH_FLOOR( itemH / 2 - h / 2 ), 'px ', MATH_FLOOR( itemW / 2 - w / 2 ), 'px 0'
672                         ].join('');
673                         reversibleImage.resize( w, h );
674                         self.addMouseEventListener( elmIconWrap, 'click', onClick );
675                 };
676                 
677                 function onClick(){
678                         onUpdateData = data;
679                         PremiumSatge.shutdown();
680                 };
681                 
682                 function asyncDraw(){
683                         reversibleImage = pettanr.image.createReversibleImage( LOW_SRC || SRC, itemW, itemH, onImageLoad );
684                         elmIconWrap.appendChild( reversibleImage.elm );
685                         onEnterFlag = true;
686                         timer = null;
687                 };
688                 
689                 this.onEnter = function( delay ){
690                         self.addTimer( asyncDraw, delay, true );
691                         delete instance.onEnter;
692                 };
693                 this.destroy = function(){
694                         delete instance.destroy;
695                         // timer && window.clearTimeout( timer );
696                         self.removeTimer( asyncDraw );
697                         self.removeMouseEventListener( elmIconWrap );
698                         reversibleImage !== null && reversibleImage.destroy();
699                         // Util.removeAllChildren( elmIconWrap );
700                         // elmContainer.removeChild( elmIconWrap );
701                         reversibleImage = elmIconWrap = elmIconTitle = data = timer = null;
702                 };
703         };
704         
705         function onEnterShowImage(){
706                 var l = ICON_ARRAY.length,
707                         _start = -wrapX /itemW -1,
708                         _end = _start + winW /itemW +1,
709                         _icon;
710                 for( var i=0, c = 0; i<l; ++i){
711                         _icon = ICON_ARRAY[ i ];
712                         if( _start < i && i < _end && _icon.onEnter ){
713                                 _icon.onEnter( c * 100 );
714                                 c++;
715                         }
716                 }
717                 //onEnterInterval !== null && window.clearTimeout( onEnterInterval );
718                 //onEnterInterval = null;
719                 self.removeTimer( onEnterShowImage );
720         };
721         function clickClose(){
722                 PremiumSatge.shutdown();
723         };
724         function onMouseWheel( e ){
725                 if( winW < containerW ){
726                         wrapX += e.wheelDelta / 2;
727                         wrapX = wrapX > 0 ? 0 : wrapX < winW -containerW ? winW -containerW : wrapX;
728                         elmContainer.style.left = wrapX + 'px';
729                         
730                         self.removeTimer( onEnterShowImage );
731                         self.addTimer( onEnterShowImage, 500 );
732                 }
733                 return false;                   
734         }
735         
736         function drawIcons(){
737                 while( ICON_ARRAY.length > 0 ){
738                         ICON_ARRAY.shift().destroy();
739                 }
740                 var _index = rootFile.search( {
741                                 id:   artistID,
742                                 type: FILE_TYPE.ARTIST
743                         })[ 0 ],
744                         _artistFile = rootFile.getChildFileByIndex( _index ),
745                         _file;
746                 if( _artistFile !== null ){
747                         for(var i=0, l=_artistFile.getChildFileLength(); i<l; ++i ){
748                                 _file = _artistFile.getChildFileByIndex( i );
749                                 ICON_ARRAY.push( new ImageGroupIconClass( i, FileAPI.getFileData( _file ) ));
750                                 _file.destroy();
751                         }
752                         elmName.firstChild.data = _artistFile.getName();
753                         _artistFile.destroy();
754                 }
755         }
756         
757         function onFadeout(){
758                 while( ICON_ARRAY.length > 0 ){
759                         ICON_ARRAY.shift().destroy();
760                 }
761                 onUpdate !== null && onUpdateData !== null && onUpdate( onUpdateData );
762                 onUpdate = onUpdateData = null;
763                 PremiumSatge.shutdown();
764         }
765         
766         
767         this.MIN_WIDTH   = 320;
768         this.MIN_HEIGHT  = 320;
769         this.onInit = function(){
770                         self.rootElement.id = 'image-group-wrapper';
771
772                         self.rootElement.innerHTML = [
773                                 '<div id="image-group-icon-container"></div>',
774                                 '<div id="image-group-name">NO DATA...</div>',
775                                 '<div id="image-group-button" class="button">close</div>'
776                         ].join( '' );
777                         
778                         self.fetchCSS( '/assets/peta.apps.css' );
779                         
780                         tree      = FileAPI.createTree( FILE_DATA_ARTIST_ROOT );
781                         rootFile  = tree.getRootFile();
782         };
783         this.onOpen = function( _windowW, _windowH, _ARTISTIDorFILE, _onUpdate ){
784                 elmContainer  = document.getElementById( 'image-group-icon-container' );
785                 containerH    = Util.getElementSize( elmContainer ).height;
786                 
787                 elmIconOrigin = ( function(){
788                         var ret  = document.createElement( 'div' ),
789                                 data = document.createElement( 'div' );
790                         ret.appendChild( data );
791                         ret.className  = 'image-group-item';
792                         data.className = 'image-group-item-title';
793                         return ret;
794                 })();
795
796                 var size      = Util.getElementSize( elmIconOrigin );
797                 itemW         = size.width;
798                 itemH         = size.height;
799
800                 elmName       = document.getElementById( 'image-group-name' );
801                 elmButton     = document.getElementById( 'image-group-button' );
802                 
803                 buttonW       = Util.getElementSize( elmButton ).width;
804                 
805                 self.addMouseEventListener( elmContainer, 'mousewheel', onMouseWheel );
806                 self.addMouseEventListener( elmButton, 'click', clickClose );
807                 tree.addTreeEventListener( Const.TREE.EVENT.UPDATE, drawIcons );
808                 
809                 if( Driver.isPettanrFileInstance( _ARTISTIDorFILE ) === true ){
810                         var _data = FileAPI.getFileData( _ARTISTIDorFILE );
811                         if( _ARTISTIDorFILE.getType() === FILE_TYPE.ARTIST || FILE_DATA_MY_PICTURES_ROOT === _data ){
812                                 artistID = _data.id || -1;
813                         }
814                 } else
815                 if( Type.isNumber( _ARTISTIDorFILE ) === true ){
816                         artistID = _ARTISTIDorFILE;
817                 }
818                 
819                 onUpdate = _onUpdate || null;
820                 onUpdateData = null;
821                 
822                 drawIcons();
823                 
824                 wrapX = 0;
825                 containerW = ICON_ARRAY.length * itemW;
826                 
827                 winW = _windowW;
828                 winH = _windowH;
829                 var w = winW > containerW ? winW : containerW,
830                         h = _windowH > containerH ? containerH : _windowH,
831                         MATH_FLOOR = Math.floor;
832
833                 $( elmContainer ).css( {
834                         width:          w,
835                         height:         0,
836                         left:           0,
837                         top:            MATH_FLOOR( _windowH /2 )
838                 }).stop().animate( {
839                         height:         h,
840                         top:            MATH_FLOOR( _windowH /2 - h /2 )
841                 }, onEnterShowImage );
842                 
843                 elmButton.style.cssText = [
844                         'left:', MATH_FLOOR( _windowW /2 - buttonW /2 ), 'px;',
845                         'top:',  MATH_FLOOR( _windowH /2 + containerH /2 +10 ), 'px'
846                 ].join('');
847         }
848         this.onPaneResize = function( _windowW, _windowH ){
849                 var w = _windowW > containerW ? _windowW : containerW,
850                         h = _windowH > containerH ? containerH : _windowH,
851                         MATH_FLOOR = Math.floor,
852                         offsetW = MATH_FLOOR( _windowW /2 -winW /2 );
853                         
854                 winW = _windowW;
855                 winH = _windowH;
856                 if( offsetW <= 0 ){ // smaller
857                         $( elmContainer ).stop().css( {
858                                 left:                           offsetW,
859                                 width:                          w
860                         }).animate( {
861                                 left:                           0,
862                                 top:                            MATH_FLOOR( _windowH /2 -h /2 )
863                         });                                     
864                 } else {
865                         $( elmContainer ).stop().css( { // bigger
866                                 left:                           0,
867                                 width:                          w,
868                                 borderLeftWidth:        offsetW
869                         }).animate( {
870                                 top:                            MATH_FLOOR( _windowH /2 -h /2 ),
871                                 borderLeftWidth:        0
872                         });
873                 }
874                 elmButton.style.cssText = [
875                         'left:', MATH_FLOOR( _windowW /2 -buttonW /2 ), 'px;',
876                         'top:',  MATH_FLOOR( _windowH /2 +containerH /2 + 10 ), 'px'
877                 ].join('');
878                 onEnterShowImage();
879         }
880         this.onClose = function(){
881                 if( tree === null ) return true;
882                 $( elmContainer ).stop().animate( {
883                                 height: 0,
884                                 top:    Math.floor( winH /2 )
885                         }, onFadeout );
886                 // onEnterInterval !== null && window.clearTimeout( onEnterInterval );
887                 // onEnterInterval = null;
888                 self.removeTimer();
889                 
890                 tree.removeTreeEventListener( Const.TREE.EVENT.UPDATE, drawIcons );
891                 tree.destroy();
892                 tree = rootFile = null;
893                 
894                 return false;
895         }
896 }, true, true, 'Premium Stage', 'premiumStage', null, '#C3325F' );
897
898
899 /* ----------------------------------------
900  * Text Editor
901  *  - overlay
902  */
903 var TextEditor = gOS.registerApplication( function(){
904         var elmTextarea, elmButton,
905                 textElement, onUpdate,
906                 ID = 'textEditor',
907                 panelX, panelY,
908                 self = this;
909         
910         function clickOK(){
911                 textElement && textElement.text( elmTextarea.value );
912                 self.addAsyncCall( asyncCallback );
913         }
914         
915         function asyncCallback(){
916                 onUpdate && onUpdate( textElement );
917                 onUpdate = textElement = null;
918                 TextEditor.shutdown();
919         }
920         
921
922         function textareaFitHeight(){
923                 var rows = 0;
924                 while( elmTextarea.offsetHeight < textElement.h ){
925                         rows++;
926                         elmTextarea.rows = rows;
927                 }
928                 if( rows > 1 ) elmTextarea.rows = --rows;
929         }
930         
931         /* grobal method */
932         
933         this.MIN_WIDTH   = 320;
934         this.MIN_HEIGHT  = 320;
935         this.onInit = function(){
936                 self.rootElement.id        = 'speach-editor-wrapper';
937                 self.rootElement.innerHTML = '<textarea id="speach-editor"></textarea><div id="speach-edit-complete-button" class="button">OK</div>';
938         };
939         this.onOpen = function( _w, _h, _panelX, _panelY, _textElement, _onUpdate ){
940                 elmTextarea = document.getElementById( 'speach-editor' );
941                 elmButton   = document.getElementById( 'speach-edit-complete-button' );
942                 
943                 self.addKeyEventListener( 'keydown', new Function( 'return false' ), 69, false, true );
944                 self.addMouseEventListener( elmButton, 'click', clickOK );
945                 
946                 panelX = _panelX;
947                 panelY = _panelY;
948                 textElement = _textElement;
949                 onUpdate = _onUpdate || null;
950                 
951                 self.onPaneResize( _w, _h );
952                 elmTextarea.value = _textElement.text()
953                 elmTextarea.focus();
954                 
955                 /*
956                  * ie6,7は、textarea { width:100%}でも高さが変わらない。rowsを設定。
957                  */
958                 UA.isIE === true && UA.ieVersion <= 7 && self.addAsyncCall( textareaFitHeight );
959         };
960         this.onPaneResize = function( _w, _h ){
961                 self.rootElement.style.cssText = [
962                         'left:', textElement.x + panelX, 'px;',
963                         'top:',  textElement.y + panelY, 'px;',
964                         'width:', textElement.w, 'px;',
965                         'height:', textElement.h, 'px;'
966                 ].join( '' );
967         };
968         this.onClose = function(){
969                 self.removeKeyEventListener();
970                 self.removeMouseEventListener( elmButton );
971                 
972                 elmTextarea = elmButton = onUpdate = textElement = self = null;
973         };
974 }, true, false, 'Tetxt Editor', 'texteditor', null, '#DDDDDD' );
975
976
977 var Reader = gOS.registerApplication( function(){
978         var windowW, windowH,
979                 headerH,
980                 consoleH,
981                 panelMargin,
982                 elmContainer, elmTitle, elmAuthor, elmBackButton, elmNextButton,
983                 bindWorker    = null,
984                 currentFile   = null,
985                 comicData     = null,
986                 currentPanel  = null,
987                 currentIndex  = 0,
988                 numPanel      = 0,
989                 self          = this;
990
991         function onBackClick(){
992                 currentIndex -= ( currentIndex > 0 ? 1 : 0 );
993                 slide();
994                 return false;
995         }
996         function onNextClick(){
997                 currentIndex += ( currentIndex < numPanel - 1 ? 1 : 0 );
998                 slide();
999                 return false;
1000         }
1001         function slide(){
1002                 var elm    = elmContainer.childNodes[ currentIndex ],
1003                         h      = windowH - headerH - consoleH,
1004                         top    = headerH;
1005                 if( elm ){
1006                         top =  headerH - elm.offsetTop + Math.floor( ( h - elm.offsetHeight ) / 2 );
1007                 }
1008                 
1009                 $( elmContainer ).stop().animate( {
1010                         top:    top
1011                 });
1012         }
1013         function getCurrentTopPosition(){
1014
1015         }
1016         function draw(){
1017                 var fileData, title, author;
1018                 
1019                 if( Driver.isPettanrFileInstance( currentFile ) === true ){
1020                         if( currentFile.getType() === FILE_TYPE.COMIC ){
1021                                 fileData    = currentFile.read();
1022                                 title       = fileData.title;
1023                                 author      = fileData.author.name;
1024                                 comicData   = fileData;
1025                                 numPanel    = currentFile.getChildFileLength();
1026                         } else
1027                         if( currentFile.getType() === FILE_TYPE.PANEL ){
1028                                 fileData    = currentFile.read();
1029                                 title       = fileData.comic.title;
1030                                 author      = fileData.comic.author.name;
1031                                 comicData   = fileData;
1032                                 numPanel    = 1;
1033                         }
1034                 } else {
1035                         
1036                 };
1037
1038                 if( comicData !== null ){
1039                         elmTitle.data  = title;
1040                         elmAuthor.data = author;
1041                         bindWorker.json( comicData );
1042                         self.addAsyncCall( asyncResize );
1043                 };
1044         }
1045         function asyncResize(){
1046                 self.onPaneResize( windowW, windowH );
1047         };
1048         
1049         /* grobal method */
1050         
1051         this.MIN_WIDTH   = 320;
1052         this.MIN_HEIGHT  = 320;
1053         this.onInit = function(){
1054                 self.rootElement.id = 'comic-reader-wrapper';
1055                 self.rootElement.innerHTML = [
1056                         '<div id="comic-reader-panel-container"></div>',
1057                         '<div class="comic-reader-shadow" style="top:0;height:40px;"></div>',
1058                         '<div id="comic-reader-header">',
1059                                 '<div id="comic-reader-header-content">',
1060                                         '<span id="comic-reader-title">NO DATA...</span>',
1061                                         '<span id="comic-reader-author">NO DATA...</span>',
1062                                 '</div>',
1063                         '</div>',
1064                         '<div class="comic-reader-shadow" style="bottom:0;height:100px;"></div>',
1065                         '<div id="comic-reader-console">',
1066                                 '<div id="comic-reader-button-centering">',
1067                                         '<a href="#" id="comic-reader-back-button">▲</da>',
1068                                         '<a href="#" id="comic-reader-forward-button">▼</a>',
1069                                 '</div>',
1070                         '</div>'
1071                 ].join( '' );
1072                 
1073                 self.fetchCSS( '/assets/peta.apps.css' );
1074                 
1075         };
1076         this.onOpen = function( _w, _h, _file ){
1077                 headerH       = Util.getElementSize( document.getElementById( 'comic-reader-header' ) ).height;
1078                 consoleH      = Util.getElementSize( document.getElementById( 'comic-reader-console' ) ).height;
1079                 elmContainer  = document.getElementById( 'comic-reader-panel-container' );
1080                 elmTitle      = document.getElementById( 'comic-reader-title' ).firstChild;
1081                 elmAuthor     = document.getElementById( 'comic-reader-author' ).firstChild;
1082                 elmBackButton = document.getElementById( 'comic-reader-back-button' );
1083                 elmNextButton = document.getElementById( 'comic-reader-forward-button' );
1084
1085                 bindWorker = pettanr.bind.createBindWorker( elmContainer, null, false, false );
1086                 
1087                 self.addMouseEventListener( elmBackButton, 'click', onBackClick );
1088                 self.addMouseEventListener( elmNextButton, 'click', onNextClick );
1089                 
1090                 numPanel = currentIndex = 0;
1091                 
1092                 elmContainer.style.cssText = 'left:' + ( _w / 2 )  + 'px;' + 'top:' + _h + 'px;';
1093                 
1094                 windowW = _w;
1095                 windowH = _h;
1096                 if( FileAPI.isFileInstance( _file ) === true ){
1097                         currentFile = _file;
1098                         _file.addEventListener( Const.FILE.EVENT.GET_SEQENTIAL_FILES, draw );
1099                         _file.getSeqentialFiles();
1100                         draw();
1101                 };
1102         };
1103         this.onPaneResize = function( _windowW, _windowH ){
1104                 windowW = _windowW;
1105                 windowH = _windowH;
1106                 var panelH = elmContainer.offsetHeight,
1107                         panelW = elmContainer.offsetWidth,
1108                         h      = _windowH - headerH - consoleH;
1109                 $( elmContainer ).stop().animate(
1110                         {
1111                                 left:   Math.floor( ( _windowW - panelW ) / 2 ),
1112                                 top:    headerH + ( panelH < h ? Math.floor( ( h - panelH ) / 2 ) : 0 )
1113                         }
1114                 );
1115         };
1116         this.onClose = function(){
1117                 self.removeMouseEventListener( elmBackButton );
1118                 self.removeMouseEventListener( elmNextButton );
1119                 
1120                 bindWorker.destroy();
1121                 bindWorker = null;
1122                 
1123                 currentFile && currentFile.removeEventListener( Const.FILE.EVENT.GET_SEQENTIAL_FILES, draw );
1124                 currentFile = comicData = currentPanel = null;
1125                 
1126                 elmContainer = elmTitle = elmAuthor = elmBackButton = elmNextButton = null;
1127         };
1128 }, true, true, 'Comic Reader', 'comicreader', null, '#01A31C' );
1129
1130
1131 var Editor = gOS.registerApplication( function(){
1132
1133         var PANEL_ELEMENT_TYPE_IMAGE = 0,
1134                 PANEL_ELEMENT_TYPE_TEXT  = 1,
1135                 MODULE_ARRAY             = [],
1136                 MOUSE_LISTENER_ARRAY     = [],
1137                 PANEL_ELEMENT_ARRAY      = [],
1138                 MIN_PANEL_HEIGHT         = 20,
1139                 MIN_ELEMENT_SIZE         = 19,
1140                 MOUSE_HIT_AREA           = 10,
1141                 elmMouseEventChatcher,
1142                 jqMouseEventChacher,
1143                 jqEditor,
1144                 windowW, windowH,
1145                 currentListener          = null,
1146                 currentCursor            = '',
1147                 self                     = this,
1148                 app                      = self,
1149                 option,
1150                 comicID                  = -1,
1151                 panelID                  = -1,
1152                 panelTimming             = -1,
1153                 phase                    = -1,
1154                 log;
1155
1156         var kill = function(){
1157                 var o = this, v;
1158                 for( var p in o ){
1159                         if( o.hasOwnProperty && !o.hasOwnProperty( p ) ) continue;
1160                         v = o[ p ];
1161                         delete o[ p ];
1162                 };
1163         };
1164         
1165         var Module = {
1166                 abstractModule: {
1167                         init: function(){
1168                                 
1169                         },
1170                         open: function(){
1171                                 
1172                         },
1173                         close: function(){
1174                                 
1175                         },
1176                         destroy: function(){
1177                                 this.kill = kill;
1178                                 this.kill();
1179                         }
1180                 },
1181                 register: function( _class ){
1182                         _class.prototype = TMP.abstractModule;
1183                         var ret = _class();
1184                         MODULE_ARRAY.push( ret );
1185                         return ret;
1186                 }
1187         }
1188 /* ----------------------------------------
1189  * MENU BAR
1190  *  - mouseEventListener
1191  *  - controler
1192  * 
1193  * div
1194  *   div.title
1195  *   ul
1196  *     li
1197  *        a
1198  *          span
1199  *          kbd shortcut
1200  */
1201         var MENU_BAR_CONTROL = ( function(){
1202                 var ELM_ITEM_CLASSNAME = 'menu-bar-item',
1203                         itemList           = [],
1204                         elmRoot, elmBar,
1205                         elmItemOrigin, elmSelectionOrigin,
1206                         barH, itemW, selectionW;
1207
1208                 var MenubarOptionClass = function( callback, separateAfter ){
1209                         this.callback      = callback;
1210                         this.separateAfter = separateAfter;
1211                 };
1212                 MenubarOptionClass.prototype = {
1213                         elm: null,
1214                         elmTitle: null,
1215                         title: function( _title ){
1216                                 if( Type.isString( _title ) === true ){
1217                                         this.elmTitle.innerHTML = _title;
1218                                 };
1219                                 return this.elmTitle.innerHTML;
1220                         },
1221                         _visible: false,
1222                         visible: function( _visible ){
1223                                 if( Type.isBoolean( _visible ) === true && this._visible !== _visible ){
1224                                         this._visible = _visible;
1225                                         this.elm.className = _visible === true ? '' : 'disabled';
1226                                 };
1227                                 return this._visible;
1228                         },
1229                         _init: function( elmParent, _title, _shortcut, _visible ){
1230                                 this.elm      = elmSelectionOrigin.cloneNode( true );
1231                                 this.elmTitle = this.elm.getElementsByTagName( 'span' )[ 0 ];
1232                                 
1233                                 elmParent.appendChild( this.elm );
1234                                 
1235                                 this.title( _title );
1236                                 this.visible( !!_visible );
1237                                 
1238                                 var elmShortcut = this.elm.getElementsByTagName( 'kbd' )[ 0 ];
1239                                 if( _shortcut ){
1240                                         elmShortcut.innerHTML = _shortcut;
1241                                 } else {
1242                                         elmShortcut.parentNode.removeChild( elmShortcut );
1243                                 };
1244                         },
1245                         _kill: kill
1246                 };
1247
1248                 var MenuBarItemClass = function( title ){
1249                         this.elm          = elmItemOrigin.cloneNode( true );
1250                         elmBar.appendChild( this.elm );
1251                         this.elm.style.left = ( itemW * itemList.length ) + 'px';
1252                         
1253                         this.elm.getElementsByTagName( 'div' )[ 0 ].innerHTML = title;
1254                         
1255                         this.elmUl        = this.elm.getElementsByTagName( 'ul' )[ 0 ];
1256                         this.optionList   = [];
1257                         this.visible      = false;
1258                         
1259                         var optionList    = this.optionList;
1260                         
1261                         this.onClick = function( e ){
1262                                 var i = Util.getChildIndex( this.parentNode, this );
1263                                 i !== -1 && this.className !== 'disabled' && optionList[ i ].callback( i );
1264                                 return false;
1265                         };
1266                         this._onClose = function(){
1267                                 optionList = null;
1268                         };
1269                 };
1270                 MenuBarItemClass.prototype = {
1271                         show: function(){
1272                                 if( this.visible === true ) return;
1273                                 elmRoot.appendChild( this.elm );
1274                                 this.elm.className = ELM_ITEM_CLASSNAME + '-focus';
1275                                 this.onShow && app.addAsyncCall( this.onShow );
1276                                 this.visible = true;
1277                         },
1278                         hide: function(){
1279                                 if( this.visible === false ) return;
1280                                 elmBar.appendChild( this.elm );
1281                                 this.elm.className = ELM_ITEM_CLASSNAME;
1282                                 this.onHide && app.addAsyncCall( this.onHide );
1283                                 this.visible = false;
1284                         },
1285                         createOption: function( title, shortcut, callback, visible, separateBefore, separateAfter ){
1286                                 var ret    = new MenubarOptionClass( callback, separateAfter ),
1287                                         before = this.optionList[ this.optionList.length -1 ];
1288                                 ret._init( this.elmUl, title, shortcut, visible );
1289                                 
1290                                 this.optionList.push( ret );
1291                                 if( before && ( separateBefore === true || before.separateAfter === true )){
1292                                         ret.elm.style.borderTop = '1px solid #ccc';
1293                                 }
1294                                 return ret;
1295                         },
1296                         _open: function(){
1297                                 for( var lis = this.optionList, i = lis.length; i; ){
1298                                         app.addMouseEventListener( lis[ --i ].elm, 'click', this.onClick );
1299                                 };
1300                         },                      
1301                         _close: function(){
1302                                 this._onClose();
1303                                 var o;
1304                                 while( o = this.optionList.shift() ) o._kill();
1305                                 this._kill = kill;
1306                                 this._kill();
1307                         }
1308                 };
1309                 
1310                 function createMenubarItem( title ){
1311                         itemList.push( new MenuBarItemClass( title ) );
1312                         return itemList[ itemList.length - 1 ];
1313                 }
1314                 return {
1315                         init: function(){
1316                                 elmRoot = app.rootElement;
1317                                 elmBar  = document.getElementById( 'menu-bar' );
1318                                 elmItemOrigin    = ( function(){
1319                                         var ret = document.createElement( 'div' ),
1320                                                 div = document.createElement( 'div' ),
1321                                                 ul  = document.createElement( 'ul' );
1322                                         ret.className = ELM_ITEM_CLASSNAME;
1323                                         ret.appendChild( div );
1324                                         ret.appendChild( ul );
1325                                         return ret;
1326                                 })();
1327                                 elmSelectionOrigin = ( function(){
1328                                         var ret  = document.createElement( 'li' ),
1329                                                 a    = document.createElement( 'a' ),
1330                                                 span = document.createElement( 'span' ),
1331                                                 key  = document.createElement( 'kbd' );
1332                                         a.appendChild( span );
1333                                         a.appendChild( key );
1334                                         ret.appendChild( a );
1335                                         a.href = '#';
1336                                         return ret;
1337                                 })();
1338                                 barH       = Util.getElementSize( elmBar ).height;
1339                                 MENU_BAR_CONTROL.h = barH;
1340                                 itemW      = Util.getElementSize( elmItemOrigin ).width;
1341                                 selectionW = Util.getElementSize( elmItemOrigin.getElementsByTagName( 'ul' )[ 0 ] ).width;
1342                                 
1343                                 MENU_BAR_CONTROL.QUIT   = createMenubarItem( 'Quit' );
1344                                 MENU_BAR_CONTROL.EDIT   = createMenubarItem( 'Edit' );
1345                                 MENU_BAR_CONTROL.WINDOW = createMenubarItem( 'Window' );
1346                                 MENU_BAR_CONTROL.HELP   = Util.extend(
1347                                         createMenubarItem( 'Help' ),
1348                                         {
1349                                                 createAjaxSelection: function( callback ){
1350                                                         var elmLoading   = document.createElement( 'li' ),
1351                                                                 that         = this;
1352                                                         this.elmUl.appendChild( elmLoading );
1353                                                         elmLoading.className    = 'loading';
1354                                                         elmLoading.style.height = '90px';                                                       
1355                 
1356                                                         this.onShow = callback;
1357                                                         callback    = null;
1358                                                         
1359                                                         delete this.createAjaxSelection;
1360                                                         return function(){
1361                                                                 that.elmUl.removeChild( elmLoading );
1362                                                                 that._open();
1363                                                                 delete that.onShow;
1364                                                                 elmLoading = that = null;
1365                                                         };
1366                                                 },
1367                                                 onShow: null
1368                                         }
1369                                 );
1370                                 
1371                                 elmBar.style.top = ( -barH ) + 'px';
1372                                 $( elmBar ).animate( { top: 0 });
1373
1374                                 delete MENU_BAR_CONTROL.init;
1375                         },
1376                         open: function(){
1377                                 for( var i = itemList.length; i; ) itemList[ --i ]._open();
1378                                 delete MENU_BAR_CONTROL.open;
1379                         },
1380                         close: function(){
1381                                 var s;
1382                                 while( s = itemList.shift() ) s._close();
1383                                 itemList = elmRoot = elmBar = elmItemOrigin = elmSelectionOrigin = null;
1384                                 MENU_BAR_CONTROL.kill = kill;
1385                                 MENU_BAR_CONTROL.kill();
1386                         },
1387                         h: 0,
1388                         mousemove: function( _mouseX, _mouseY ){
1389                                 if( barH >= _mouseY ) return true;
1390                                 
1391                                 for( var i = itemList.length; i; ) itemList[ --i ].hide();
1392                                 return false;
1393                         },
1394                         mouseup: function( _mouseX, _mouseY ){
1395                                 return false;
1396                         },
1397                         mousedown: function( _mouseX, _mouseY ){
1398                                 var l = itemList.length;
1399                                 if( barH < _mouseY || itemW * l < _mouseX ) return false;
1400                                 for( ; l; ){
1401                                         --l;
1402                                         itemList[ l ][ l * itemW <= _mouseX && _mouseX < ( l + 1 ) * itemW ? 'show' : 'hide' ]();
1403                                 };
1404                                 return true;
1405                         },
1406                         busy: function( _busy ){
1407                                 return false;
1408                         },
1409                         onWindowResize: function( _windowW, _windowH ){
1410                                 
1411                         },
1412                         QUIT:   null,
1413                         EDIT:   null,
1414                         WINDOW: null,
1415                         HELP:   null
1416                 }
1417         })();
1418
1419
1420 /* ----------------------------------------
1421  * HISTORY_CONTROL
1422  *  - controler
1423  */
1424         var HISTORY_CONTROL = ( function() {
1425                 var     stackBack    = [],
1426                         stackForward = [],
1427                         menubarBack,
1428                         menubarForward;
1429
1430                 function back(){
1431                         /*
1432                          * currentを控えてstackForward.push(current)
1433                          * stackBack.pop()を実行してcurrentに
1434                          */
1435                         if( stackBack.length === 0 ) return;
1436
1437                         var s = stackBack.pop();
1438                         s.fn( s.argBack );
1439                         menubarBack.visible( stackBack.length !== 0 );
1440                         SAVE_CONTROL.panelUpdated( stackBack.length !== 0 );
1441                         
1442                         stackForward.push( s );
1443                         menubarForward.visible( true );
1444                 };
1445                 function forward(){
1446                         if( stackForward.length === 0 ) return;
1447                         
1448                         var s = stackForward.pop();
1449                         s.fn( s.argForword );
1450                         menubarForward.visible( stackForward.length !== 0 );
1451                         
1452                         stackBack.push( s );
1453                         menubarBack.visible( true );
1454                         SAVE_CONTROL.panelUpdated( true );
1455                 };
1456                 var StackClass = function( _function, _argBack, _argForword, _destroy ){
1457                         this.fn         = _function;
1458                         this.argBack    = _argBack;
1459                         this.argForword = _argForword;
1460                         this.destroy    = _destroy;
1461                 };
1462                 StackClass.prototype.kill = function( _callDestroy ){
1463                         var     _argBack    = this.argBack,
1464                                 _argForword = this.argForword,
1465                                 v;
1466                         this._kill = kill;
1467                         this._kill();
1468                         
1469                         if( _callDestroy !== true ) return;
1470                         
1471                         if( Type.isArray( _argBack ) === true ){ // isArray
1472                                 while( v = _argBack.shift() ){
1473                                         _callDestroy === true && Type.isFunction( v.destroy ) === true && v.destroy();
1474                                 };
1475                         };
1476                         if( Type.isArray( _argForword ) === true ){
1477                                 while( v = _argForword.shift() ){
1478                                         _callDestroy === true && Type.isFunction( v.destroy ) === true && v.destroy();
1479                                 };
1480                         };
1481                 };
1482                 return {
1483                         init: function(){
1484                                 app.addKeyEventListener( 'keydown', back,    90, false, true ); // ctrl + Z
1485                                 app.addKeyEventListener( 'keydown', forward, 90, true,  true ); // ctrl + shift + Z
1486                                 app.addKeyEventListener( 'keydown', forward, 89, false, true ); // ctrl + Y
1487                                 
1488                                 delete HISTORY_CONTROL.init;
1489                         },
1490                         open: function(){
1491                                 menubarBack    = MENU_BAR_CONTROL.EDIT.createOption( 'back',    'ctrl + z', back, false );
1492                                 menubarForward = MENU_BAR_CONTROL.EDIT.createOption( 'forward', 'ctrl + y', forward, false, false, true );                              
1493                                 
1494                                 delete HISTORY_CONTROL.open;
1495                         },
1496                         close: function(){
1497                                 var s;
1498                         while( s = stackBack.shift() )    s.kill( true );
1499                         while( s = stackForward.shift() ) s.kill( true );
1500                         menubarBack = menubarForward = stackBack = stackForward = null;
1501                         },
1502                     saveState: function( _function, _argBack, _argForword, _destroy ){
1503                         stackBack.push( new StackClass( _function, _argBack, _argForword, _destroy ));
1504                         menubarBack.visible( true );
1505                                 SAVE_CONTROL.panelUpdated( true );
1506                                 
1507                                 var s;
1508                         while( s = stackForward.shift() ) s.kill( s.destroy );
1509                                 menubarForward.visible( false );
1510                     }           
1511                 }
1512         })();
1513
1514 /* ----------------------------------------
1515  * SAVE_CONTROL
1516  *  - controler
1517  */
1518         var SAVE_CONTROL = ( function(){
1519                 var save, saveQuit, eXport, quit,
1520                         updated  = false;
1521                 
1522                 function quit(){
1523                         Editor.shutdown();
1524                 }
1525                 function onExport(){
1526                         OutputConsole.boot(
1527                                 comicID, panelID, panelTimming,
1528                                 PANEL_CONTROL.w, PANEL_CONTROL.h,
1529                                 2, // border, BackgroundImage
1530                                 PANEL_ELEMENT_ARRAY
1531                         );
1532                 }
1533                 return {
1534                         init: function(){
1535                                 delete SAVE_CONTROL.init;
1536                         },
1537                         open: function(){
1538                                 save     = MENU_BAR_CONTROL.QUIT.createOption( 'save', 'ctrl + S', quit, false );
1539                                 saveQuit = MENU_BAR_CONTROL.QUIT.createOption( 'save & quit', null, quit, false, false, true );
1540                                 eXport   = MENU_BAR_CONTROL.QUIT.createOption( 'export', null, onExport, true, false, true );
1541                                 quit     = MENU_BAR_CONTROL.QUIT.createOption( 'quit', null, quit, true, true );                                
1542                                 
1543                                 delete SAVE_CONTROL.open;
1544                         },
1545                         close: function(){
1546                                 save = saveQuit = eXport = quit = null;
1547                                 SAVE_CONTROL.kill = kill;
1548                                 SAVE_CONTROL.kill();
1549                         },
1550                         quit: quit,
1551                         panelUpdated: function( _updated ){
1552                                 if( Type.isBoolean( _updated ) === true ){
1553                                         save.visible( _updated );
1554                                         saveQuit.visible( _updated );
1555                                         updated = _updated;
1556                                 }
1557                                 return updated;
1558                         },
1559                         save: function(){
1560                                 
1561                         }
1562                 }
1563         })();
1564
1565 /* ----------------------------------------
1566  * WINDOWS_CONTROL
1567  *  - contloler
1568  *  - mouseEventListener
1569  */     
1570         var WINDOWS_CONTROL = ( function(){
1571                 /*
1572                  *  表示上手前にあるwindowは、WINDOW_ARRAYの先頭にあり、htmlでは後ろにある。
1573                  */
1574                 var DEFAULT_MIN_WINDOW_WIDTH  = 200,
1575                         DEFAULT_MIN_WINDOW_HEIGHT = 200,
1576                         WINDOW_ARRAY              = [],
1577                         WINDOW_BODY_BODER_SIZE    = 1,
1578                         currentWindowIndex        = -1,
1579                         currentWindow,
1580                         elmRoot,
1581                         elmWindowOrigin,
1582                         closeButtonWidth;
1583                         
1584                 var WindowClass = function( bodyTempleteID, title, x, y, w, h, visible, CLOSE_BUTTON_ENABLED, RESIZE_BUTTON_ENABLED, minWindowW, minWindowH ){
1585                         var menubarOption,
1586                                 elmHeader, elmFooter = null,
1587                                 elmBody, elmBodyStyle,
1588                                 startX, startY, startW, startH,
1589                                 offsetX, offsetY,
1590                                 headerH, bodyH, footerH = 0,
1591                                 isDragging = false,
1592                                 isResizing = false,
1593                                 bodyIsTachable = false,
1594                                 self = this;
1595
1596                         function update( _x, _y, _w, _h ){
1597                                 _x = _x !== undefined ? _x : x;
1598                                 _y = _y !== undefined ? _y : y;
1599                                 _y = _y > MENU_BAR_CONTROL.h ? _y : MENU_BAR_CONTROL.h;
1600                                 _w = _w !== undefined ? _w : w;
1601                                 _h = _h !== undefined ? _h : h;
1602                                 self.elm.style.cssText = [
1603                                         'left:',   _x, 'px;',
1604                                         'top:',    _y, 'px;',
1605                                         'width:',  _w, 'px;',
1606                                         'height:', _h, 'px;'
1607                                 ].join( '' );
1608                                 bodyH = _h - headerH - footerH;
1609                                 elmBodyStyle.height = bodyH + 'px';
1610                                 ( w !== _w || h !== _h) && self.onResize && self.onResize( _w, bodyH );
1611                                 x = _x;
1612                                 y = _y;
1613                                 w = _w;
1614                                 h = _h;
1615                         };
1616                         function bodyBackOrForward( isBack ){
1617                                 if( !self ) return;
1618                                 if( bodyIsTachable === !isBack ) return;
1619                                 elmBodyStyle.position = isBack === true ? 'relative' : 'absolute';
1620                                 elmBodyStyle.left =             isBack === true ? 0  : x +'px';
1621                                 elmBodyStyle.top =              isBack === true ? 0  : y + headerH + 'px';
1622                                 elmBodyStyle.width =    isBack === true ? '' : ( w - WINDOW_BODY_BODER_SIZE * 2 ) + 'px';
1623                                 bodyIsTachable === isBack && isBack === true ? elmHeader.parentNode.insertBefore( elmBody, elmHeader.nextSibling ) : app.rootElement.appendChild( elmBody );
1624                                 bodyIsTachable = !isBack;
1625                         };
1626
1627                         this.init = function(){
1628                                 self.elm      = elmWindowOrigin.cloneNode( true );
1629                                 menubarOption = MENU_BAR_CONTROL.WINDOW.createOption( 
1630                                         ( visible !== true ? 'show ' : 'hide ' ) + title,
1631                                         null, function(){ visible === true ? self.close() : self.open(); }, true
1632                                 );
1633                                 elmHeader     = Util.getElementsByClassName( self.elm, 'window-header' )[ 0 ];
1634                                 elmHeader.innerHTML = title;
1635                                 headerH       = Util.getElementSize( elmHeader ).height;
1636                                 elmBody       = Util.getElementsByClassName( self.elm, 'window-body' )[ 0 ];
1637                                 elmBodyStyle  = elmBody.style;
1638                                 
1639                                 self.onInit && self.onInit();
1640                                 delete self.init;
1641                         };
1642                         this.x = function(){ return x;};
1643                         this.y = function(){ return y;};
1644                         this.w = function(){ return w;};
1645                         this.h = function(){ return h;};
1646                         this.title = function( _title ){
1647                                 if( Type.isString( _title ) === true ){
1648                                         jqHeader.html( _title );
1649                                         title = _title;
1650                                 }
1651                                 return title;
1652                         };
1653                         this.visible   = visible;
1654                         this.firstOpen = function(){
1655                                 var elmReplace = Util.getElementsByClassName( self.elm, 'window-body-insert-position' )[ 0 ];
1656
1657                                 if( bodyTempleteID ){
1658                                         elmReplace.parentNode.replaceChild( document.getElementById( bodyTempleteID ), elmReplace );
1659                                 } else {
1660                                         elmReplace.parentNode.removeChild( elmReplace );
1661                                 };
1662                                 
1663                                 if( CLOSE_BUTTON_ENABLED !== true ){
1664                                         var elmClose = Util.getElementsByClassName( self.elm, 'window-close-button' )[ 0 ];
1665                                         elmClose.parentNode.removeChild( elmClose );
1666                                 };                              
1667                                 
1668                                 
1669                                 var elmFooter = Util.getElementsByClassName( self.elm, 'window-footer' )[ 0 ];
1670                                 if( RESIZE_BUTTON_ENABLED === true ){
1671                                         footerH = Util.getElementSize( elmFooter ).height;
1672                                 } else {
1673                                         elmFooter.parentNode.removeChild( elmFooter );
1674                                 }
1675                                 self.onFirstOpen && self.onFirstOpen( w, h - headerH - footerH );
1676                                 
1677                                 update( x, y, w, h );
1678                                 
1679                                 delete self.firstOpen;
1680                         };
1681                         this.open = function(){
1682                                 if( visible === true )return;
1683                                 self.visible = visible = true;
1684                                 openWindow( self );
1685                                 menubarOption.title( 'hide ' + title );
1686                                 
1687                                 for( var i=0, l = WINDOW_ARRAY.length; i<l; ++i ){
1688                                         if( WINDOW_ARRAY[ i ] === self ){
1689                                                 WINDOW_ARRAY.splice( i, 1 );
1690                                                 WINDOW_ARRAY.unshift( self );
1691                                                 currentWindow      = null;
1692                                                 currentWindowIndex = -1;
1693                                         };
1694                                 };
1695                         };
1696                         this.onFadeIn = function(){
1697                                 self.firstOpen && self.firstOpen();
1698                                 self.onOpen && self.onOpen( w, bodyH );
1699                         };
1700                         this.onFadeOut = function(){
1701                                 self.elm.parentNode.removeChild( self.elm );
1702                                 self.onClose &&  app.addAsyncCall( self.onClose );
1703                         };
1704                         this.close = function(){
1705                                 if( visible === false) return;
1706                                 self.visible = visible = false;
1707                                 $( self.elm ).fadeOut( self.onFadeOut );
1708                                 menubarOption.title( 'show ' + title );
1709                         };
1710                         this.bodyBackOrForward = bodyBackOrForward;
1711                         this.mousedown = function( _mouseX, _mouseY ){
1712                                 if( RESIZE_BUTTON_ENABLED === true && x + w -20 <= _mouseX && _mouseX < x + w && y + headerH + bodyH < _mouseY && _mouseY <= y + h ){
1713                                         bodyBackOrForward( true);
1714                                         isResizing = true;
1715                                         startX = x;
1716                                         startY = y;
1717                                         startW = w;
1718                                         startH = h;
1719                                         offsetX = _mouseX;
1720                                         offsetY = _mouseY;
1721                                         updateMouseCursor( 'nw-resize');
1722                                         return;
1723                                 }
1724                                 
1725                                 if( x > _mouseX || y > _mouseY || x + w < _mouseX || y + headerH < _mouseY ) return;
1726                                 if( CLOSE_BUTTON_ENABLED === true && x + w - closeButtonWidth < _mouseX){
1727                                         self.close();
1728                                         return;
1729                                 }
1730                                 
1731                                 isDragging = true;
1732                                 updateMouseCursor( 'move');                             
1733                                 startX = x;
1734                                 startY = y;
1735                                 startW = w;
1736                                 startH = h;
1737                                 offsetX = _mouseX;
1738                                 offsetY = _mouseY;
1739                         };
1740                         this.mouseup = function( _mouseX, _mouseY ){
1741                                 isDragging = isResizing = false;
1742                                 updateMouseCursor( '');
1743                         };
1744                         this.mousemove = function( _mouseX, _mouseY ){
1745                                 var _updateX = _mouseX - offsetX,
1746                                         _updateY = _mouseY - offsetY;
1747                                 
1748                                 if( isResizing === true){
1749                                         var _w = startW +_updateX,
1750                                                 _h = startH +_updateY;
1751                                         update( startX, startY, _w < minWindowW ? minWindowW : _w, _h < minWindowH ? minWindowH : _h );
1752                                         return;
1753                                 } else
1754                                 if( isDragging === true) {
1755                                         update( startX + _updateX, startY + _updateY);
1756                                         return;
1757                                 } else
1758                                 if( x > _mouseX || x + w < _mouseX ) return;
1759
1760                                 ( y <= _mouseY && y +headerH >= _mouseY ) ?
1761                                         updateMouseCursor( 'pointer') : // hit to header
1762                                         updateMouseCursor( '');
1763                                 bodyBackOrForward( y + headerH > _mouseY || y + headerH + bodyH < _mouseY);
1764                         };
1765                         this.onMouseOut = function( _mouseX, _mouseY ){
1766                                 bodyIsTachable === true && bodyBackOrForward( true );
1767                                 isDragging = false;
1768                                 updateMouseCursor( '' );
1769                         };
1770                         this.busy = function(){
1771                                 return isDragging === true || isResizing === true;
1772                         };
1773                 };
1774                 
1775                 function getCurrentIndex( _mouseX, _mouseY ){
1776                         if( currentWindow && currentWindow.busy() === true ) return currentWindowIndex;
1777                         var l = WINDOW_ARRAY.length,
1778                                 _currentWindow = null,
1779                                 _win, _x, _y;
1780                         currentWindowIndex = -1;
1781                         for( var i=0; i<l; i++){
1782                                 _win = WINDOW_ARRAY[ i];
1783                                 if( _win.visible !== true ) continue;
1784                                 _x = _win.x();
1785                                 _y = _win.y();
1786                                 if( _x <= _mouseX && _y <= _mouseY && _x +_win.w() >= _mouseX && _y +_win.h() >= _mouseY){
1787                                         _currentWindow = _win;
1788                                         currentWindowIndex = i;
1789                                         break;
1790                                 }
1791                         }
1792                         currentWindow && currentWindow !== _currentWindow && currentWindow.onMouseOut( _mouseX, _mouseY);
1793                         currentWindow = _currentWindow;
1794                         return currentWindowIndex;
1795                 }
1796                 function openWindow( _window ){
1797                         if( _window.visible !== true ) return;
1798                         elmRoot.appendChild( _window.elm );// appendした後に fadeIn() しないと ie で filterが適用されない.
1799                         $( _window.elm ).fadeIn( _window.onFadeIn );
1800                         return;
1801                 }
1802                 
1803                 return {
1804                         init: function(){
1805                                 elmRoot          = document.getElementById( 'window-container' );
1806                                 elmWindowOrigin  = app.fetchHTMLElement( 'windowTemplete' );
1807                                 closeButtonWidth = Util.getElementSize( Util.getElementsByClassName( elmWindowOrigin, 'window-close-button' )[ 0 ] ).width;
1808                                 
1809                                 delete WINDOWS_CONTROL.init;
1810                         },
1811                         open: function(){
1812                                 for( var i = WINDOW_ARRAY.length, _window; i; ){
1813                                         _window = WINDOW_ARRAY[ --i ];
1814                                         _window.init && _window.init();
1815                                         _window.visible === true && openWindow( _window );
1816                                 };
1817                                 
1818                                 delete WINDOWS_CONTROL.open;
1819                         },
1820                         close: function(){
1821                         },
1822                         mousemove: function( _mouseX, _mouseY ){
1823                                 var _index = getCurrentIndex( _mouseX, _mouseY );
1824                                 if( _index === 0 ){
1825                                         currentWindow.mousemove( _mouseX, _mouseY );
1826                                         return true;
1827                                 } else
1828                                 if( _index > 0 ){ // 先頭のクリックでない場合
1829                                 // Array を前に
1830                                         WINDOW_ARRAY.splice( currentWindowIndex, 1 );
1831                                         WINDOW_ARRAY.unshift( currentWindow );
1832                                 // Domを最後に
1833                                         elmRoot.appendChild( currentWindow.elm );
1834                                         currentWindowIndex = 0;
1835                                         return true;
1836                                 }
1837                                 return false;
1838                         },
1839                         mouseup: function( _mouseX, _mouseY ){
1840                                 if( getCurrentIndex( _mouseX, _mouseY) === 0){
1841                                         currentWindow.mouseup( _mouseX, _mouseY);
1842                                         return true;
1843                                 }
1844                                 return false;
1845                         },
1846                         mousedown: function( _mouseX, _mouseY ){
1847                                 if( getCurrentIndex( _mouseX, _mouseY) === 0){
1848                                         currentWindow.mousedown( _mouseX, _mouseY);
1849                                         return true;
1850                                 }
1851                                 return false;
1852                         },
1853                         busy: function(){
1854                                 return currentWindow !== null;
1855                         },
1856                         onWindowResize: function( _windowW, _windowH ){
1857                                 /*
1858                                  * 画面外に出るwindowの移動
1859                                  */
1860                         },
1861                         createWindow: function( EXTENDS, bodyTempleteID, title, x, y, w, h, opt_visible, opt_closeButtonEnabled, opt_resizeButtonEnabled, opt_minWindowW, opt_minWindowH ){
1862                                 opt_visible = opt_visible !== false;
1863                                 opt_closeButtonEnabled = opt_closeButtonEnabled === true;
1864                                 opt_resizeButtonEnabled = opt_resizeButtonEnabled === true;
1865                                 opt_minWindowW = opt_minWindowW || ( w < DEFAULT_MIN_WINDOW_WIDTH ) ? w : DEFAULT_MIN_WINDOW_WIDTH;
1866                                 opt_minWindowH = opt_minWindowH || ( h < DEFAULT_MIN_WINDOW_HEIGHT ) ? h : DEFAULT_MIN_WINDOW_HEIGHT;
1867                                 
1868                                 var _window = new WindowClass( bodyTempleteID, title, x, y, w, h, opt_visible, opt_closeButtonEnabled, opt_resizeButtonEnabled, opt_minWindowW, opt_minWindowH );
1869                                 for( var key in EXTENDS ){
1870                                         _window[ key ] = EXTENDS[ key ];
1871                                 }
1872                                 WINDOW_ARRAY.unshift( _window );
1873                                 if( Type.isUndefined( WINDOWS_CONTROL.init ) === true ){
1874                                         _window.init();
1875                                         openWindow( _window );
1876                                 }
1877                                 return _window;
1878                         }
1879                 }
1880         })();
1881
1882 /* ----------------------------------------
1883  * TOOL_BOX_WINDOW
1884  * - window
1885  */
1886         var TOOL_BOX_WINDOW = ( function(){
1887                         
1888                 app.addKeyEventListener( 'keydown', addImage,   73, false, true );
1889                 app.addKeyEventListener( 'keydown', addText,    84, false, true );
1890                 app.addKeyEventListener( 'keydown', switchGrid, 71, false, true );
1891
1892                 function addImage(){
1893                         IMAGE_EXPLORER_WINDOW.open();// setTimeout( IMAGE_EXPLORER_WINDOW.open, 0);
1894                         TOOL_BOX_WINDOW.bodyBackOrForward( true );
1895                 };
1896                 function addText(){
1897                         app.addAsyncCall( PANEL_ELEMENT_CONTROL.createTextElement );
1898                 };
1899                 function switchGrid(){
1900                         app.addAsyncCall( GRID_CONTROL.update );
1901                 };
1902                 function popupHelp(){
1903                         TOOL_BOX_WINDOW.bodyBackOrForward( true );
1904                         app.addAsyncCall( HELP_DOCUMENTS_WINDOW.open );
1905                 };
1906                 function editBG( e ){
1907                         TOOL_BOX_WINDOW.bodyBackOrForward( true );
1908                         app.addAsyncCall( INFOMATION_WINDOW.open );
1909                 };
1910                 
1911                 return WINDOWS_CONTROL.createWindow(
1912                         {
1913                                 onInit: function(){
1914                                         MENU_BAR_CONTROL.EDIT.createOption( 'Add Image', 'ctrl + I', addImage, true, true, false);
1915                                         MENU_BAR_CONTROL.EDIT.createOption( 'Add Text', 'ctrl + T',  addText, true, false, true);
1916                                         MENU_BAR_CONTROL.EDIT.createOption( 'show Grid', 'ctrl + G', switchGrid, true, true, true);
1917                                         
1918                                         delete TOOL_BOX_WINDOW.onInit;
1919                                 },
1920                                 onFirstOpen: function(){
1921                                         app.addMouseEventListener( document.getElementById( 'toolbox-add-image-button'), 'click', addImage );
1922                                         app.addMouseEventListener( document.getElementById( 'toolbox-add-text-button'), 'click', addText );
1923                                         app.addMouseEventListener( document.getElementById( 'toolbox-edit-bg-button'), 'click', editBG );
1924                                         app.addMouseEventListener( document.getElementById( 'toolbox-switch-grid'), 'click', switchGrid );
1925                                         app.addMouseEventListener( document.getElementById( 'toolbox-popup-help-button'), 'click', popupHelp );
1926                                         
1927                                         // postButton = $( '#toolbox-post-button');
1928                                         
1929                                         delete TOOL_BOX_WINDOW.onFirstOpen;
1930                                 }
1931                         },
1932                         'toolbox-window', 'Tool box', 0, 215, 110, 290, true
1933                 );
1934         })();
1935         
1936         
1937 /* ----------------------------------------
1938  * IMAGE_EXPROLER
1939  *  - window
1940  */
1941         var IMAGE_EXPLORER_WINDOW = ( function(){
1942                 var tree, finder;
1943                 
1944                 function onFileSelect( _file ){
1945                         // 他の image ファイルも許可する?
1946                         if( Driver.isPettanrFileInstance( _file ) === true ){
1947                                 if( _file.getType() === FILE_TYPE.PICTURE ){
1948                                         PANEL_ELEMENT_CONTROL.onImageSelect( FileAPI.getFileData( _file ) );
1949                                 }
1950                         }
1951                 }
1952                 
1953                 return WINDOWS_CONTROL.createWindow(
1954                         {
1955                                 onInit: function(){
1956                                         delete IMAGE_EXPLORER_WINDOW.onInit;
1957                                 },
1958                                 onFirstOpen: function( _w, _h ){
1959                                         tree = FileAPI.createTree( FILE_DATA_PICTURE_ROOT );
1960                                         var     _root  = tree.getRootFile(),
1961                                                 _myPic = _root.getChildFileByIndex( 0 ),
1962                                                 _pic   = _root.getChildFileByIndex( 1 );
1963                                         _myPic.getSeqentialFiles();
1964                                         _pic.getSeqentialFiles();
1965                                         _myPic.destroy();
1966                                         _pic.destroy(); 
1967                                         
1968                                         finder = app.createFinder(
1969                                                 document.getElementById( 'image-exproler-container' ),
1970                                                 tree,
1971                                                 null, null,
1972                                                 onFileSelect,
1973                                                 PANEL_ELEMENT_CONTROL.onImageSelect
1974                                         );
1975                                         
1976                                         delete IMAGE_EXPLORER_WINDOW.onFirstOpen;
1977                                 },
1978                                 onOpen: function( _w, _h ){
1979                                         finder.resize( _w, _h );
1980                                 },
1981                                 onResize: function( _w, _h ){
1982                                         finder.resize( _w, _h );
1983                                 }
1984                         },
1985                         'image-exproler', 'Album', 0, 215, 600, 350, false, true, true, 300, 300
1986                 );
1987         })();
1988         
1989         
1990 /* ----------------------------------------
1991  * INFOMATION_WINDOW
1992  *  - window
1993  */                     
1994         var INFOMATION_WINDOW = ( function(){
1995                 var FADE_EFFECT_ENABLED = true, //UA.isIE === false || UA.ieVersion >= 8,
1996                         FADE_IN_EFFECT      = FADE_EFFECT_ENABLED === true ? 'fadeIn' : 'show',
1997                         FADE_OUT_EFFECT     = FADE_EFFECT_ENABLED === true ? 'fadeOut' : 'hide',
1998                         backgroundInfomationElm,
1999                         jqPanelElementInformation,
2000                         ui, inputX, inputY, inputZ, inputA, inputW, inputH, inputAspectRatio,
2001                         inputPercentW, inputPercentH,
2002                         currentPanelElement = null,
2003                         currentElementType = -1,
2004                         currentLock = false;
2005
2006                 return WINDOWS_CONTROL.createWindow(
2007                         {
2008                                 onFirstOpen: function( _w, _h ){
2009                                         backgroundInfomationElm = $( '#panel-background-information');
2010                                         
2011                                         jqPanelElementInformation = $( '#comic-element-infomation').hide().css( {
2012                                                 height:         _h
2013                                         });
2014                                         ui               = app.createUIGroup();
2015                                         inputX           = ui.createInputText( document.getElementById( 'comic-element-x' ), null );
2016                                         inputY           = ui.createInputText( document.getElementById( 'comic-element-y' ), null );
2017                                         inputZ           = ui.createInputText( document.getElementById( 'comic-element-z' ), null );
2018                                         inputA           = ui.createInputText( document.getElementById( 'comic-element-a' ), null );
2019                                         inputW           = ui.createInputText( document.getElementById( 'comic-element-w' ), null );
2020                                         inputH           = ui.createInputText( document.getElementById( 'comic-element-h' ), null );
2021                                         inputPercentW    = ui.createInputText( document.getElementById( 'comic-element-w-percent' ), null );
2022                                         inputPercentH    = ui.createInputText( document.getElementById( 'comic-element-h-percent' ), null );
2023                                         inputAspectRatio = $( '#comic-element-keep-aspect' );
2024                                         delete INFOMATION_WINDOW.onFirstOpen;
2025                                 },
2026                                 onResize: function(  _w, _h ){
2027                                         jqPanelElementInformation.css( {
2028                                                 height: _h
2029                                         });
2030                                 },
2031                                 update: function( currentElement ){
2032                                         
2033                                         if( currentLock === true && currentElement === null) return;
2034                                         
2035                                         var _elementType = currentElement === null ? -1 : currentElement.type,
2036                                                 x = currentElement !== null ? currentElement.x : 0,
2037                                                 y = currentElement !== null ? currentElement.y : 0,
2038                                                 z = currentElement !== null ? currentElement.z : 0,
2039                                                 a = _elementType === PANEL_ELEMENT_TYPE_TEXT ? Math.floor( currentElement.angle() ) : 0,
2040                                                 w = currentElement !== null ? currentElement.w : 0,
2041                                                 h = currentElement !== null ? currentElement.h : 0,
2042                                                 actualW = _elementType === PANEL_ELEMENT_TYPE_IMAGE ? currentElement.actualW() : 1,
2043                                                 actualH = _elementType === PANEL_ELEMENT_TYPE_IMAGE ? currentElement.actualH() : 1,
2044                                                 wPercent = _elementType === PANEL_ELEMENT_TYPE_IMAGE ? Math.floor( w / actualW *100 ) : 0,
2045                                                 hPercent = _elementType === PANEL_ELEMENT_TYPE_IMAGE ? Math.floor( h / actualH *100 ) : 0,
2046                                                 keepAspect = currentElement !== null && currentElement.keepAspect === true;
2047                                         
2048                                         if( currentElementType !== _elementType ){
2049                                                 if( _elementType !== -1 ){
2050                                                         if( _elementType === 1 ){
2051                                                                 inputA.visible( true );
2052                                                                 inputPercentW.visible( false );
2053                                                                 inputPercentH.visible( false );
2054                                                                 inputAspectRatio.hide();
2055                                                         } else {
2056                                                                 inputA.visible( false );
2057                                                                 inputPercentW.visible( true );
2058                                                                 inputPercentH.visible( true );
2059                                                                 inputAspectRatio.show();
2060                                                         }
2061                                                         currentElementType === -1 && jqPanelElementInformation.stop().css( {
2062                                                                 filter:         '',
2063                                                                 opacity:        ''
2064                                                         })[ FADE_IN_EFFECT ]();
2065                                                 } else {
2066                                                         currentElementType !== -1 && jqPanelElementInformation.stop().css({
2067                                                                 filter:         '',
2068                                                                 opacity:        ''
2069                                                         })[ FADE_OUT_EFFECT ]();
2070                                                 }
2071                                                 currentElementType = _elementType;
2072                                         }
2073                                         if( currentElementType !== -1){
2074                                                 inputX.value( x );
2075                                                 inputY.value( y );
2076                                                 inputZ.value( z );
2077                                                 _elementType === 1 && inputA.value( a );
2078                                                 inputW.value( w );
2079                                                 inputH.value( h );
2080                                                 _elementType === 0 && inputPercentW.value( wPercent );
2081                                                 _elementType === 0 && inputPercentH.value( hPercent );
2082                                         } else {
2083                                                 
2084                                         }
2085                                 },
2086                                 lock: function( _currentLock ){
2087                                         currentLock = !!_currentLock;
2088                                         INFOMATION_WINDOW.bodyBackOrForward( !currentLock );
2089                                 }
2090                         },
2091                         'infomation-window', 'Infomation', 0, 30, 200, 180, true
2092                 );
2093         })();
2094
2095 /* ----------------------------------------
2096  * HELP_WINDOW
2097  *  - window
2098  */
2099         var HELP_DOCUMENTS_WINDOW = ( function(){
2100                 var visible          = true,
2101                         jqAjaxContents,
2102                         jqNaviItems,
2103                         jqPages,
2104                         currentPageIndex = 0,
2105                         numPage          = 0,
2106                         help             = null,
2107                         onLoadFunction   = null;
2108
2109                 function onAjaxStart( _pageIndex ){
2110                         currentPageIndex = _pageIndex || currentPageIndex;
2111                         if( onHelpLoad !== null ){
2112                                 $.ajax({
2113                                         url:            'help/jp.xml',
2114                                         dataType:       'xml',
2115                                         success:        onHelpLoad
2116                                 });
2117                                 onHelpLoad = null;
2118                         }
2119                         onAjaxStart = new Function;
2120                 }
2121                 var onHelpLoad = function( _xml ){
2122                         var jqXML          = $( _xml ),
2123                                 helpTitle      = jqXML.find( 'pages' ).eq( 0 ).attr( 'title' ),
2124                                 elmNavi        = document.createElement( 'div' ),
2125                                 elmItemOrigin  = document.createElement( 'a' ),
2126                                 elmPages       = document.createElement( 'div' ),
2127                                 elmPageOrigin  = document.createElement( 'div' ),
2128                                 elmTitleOrigin = document.createElement( 'h2' ),
2129                                 elmPage;
2130                         elmNavi.className       = 'sidenavi';
2131                         elmItemOrigin.className = 'sidenavi-item';
2132                         elmItemOrigin.href      = '#';
2133                         elmPages.className      = 'page-contents';
2134                         elmPageOrigin.className = 'page-content main';
2135                         elmPageOrigin.appendChild( elmTitleOrigin);
2136                         
2137                         jqXML.find( 'page' ).each( function(){
2138                                 var xmlPage = $( this ),
2139                                         title = xmlPage.attr( 'title' ),
2140                                         content = xmlPage.text();
2141                                 
2142                                 elmItemOrigin.innerHTML = title;
2143                                 elmNavi.appendChild( elmItemOrigin.cloneNode( true ));
2144                                 
2145                                 elmTitleOrigin.innerHTML = title;
2146                                 
2147                                 elmPage = elmPageOrigin.cloneNode( true );
2148                                 elmPage.innerHTML = content;
2149                                 
2150                                 Util.cleanElement( elmPage);
2151                                 
2152                                 if( elmPage.childNodes.length > 0 ){
2153                                         elmPage.insertBefore( elmTitleOrigin.cloneNode( true ), elmPage.childNodes[0]);
2154                                 } else {
2155                                         elmPage.appendChild( elmTitleOrigin.cloneNode( true ));
2156                                 }
2157                                 elmPages.appendChild( elmPage );
2158                                 
2159                                 help.createOption( title, null, onSelectionClick, true );
2160                                 ++numPage;
2161                         });
2162                         onLoadFunction();
2163                         onLoadFunction = null;
2164                         
2165                         jqAjaxContents.removeClass( 'loading' ).append( elmNavi, elmPages );
2166                         
2167                         jqNaviItems = jqAjaxContents.find( 'a.' + elmItemOrigin.className ).click( onNaviClick );
2168                         jqPages     = jqAjaxContents.find( '.page-content' );
2169                         jqPages.find( 'a' ).click( onInnerLinkClick );
2170                         
2171                         app.addAsyncCall( jumpPage );
2172                 }
2173                 function onSelectionClick( _pageIndex ){
2174                         HELP_DOCUMENTS_WINDOW.open();
2175                         jumpPage( _pageIndex );
2176                 }
2177                 function jumpPage( _index ){
2178                         if( Type.isNumber( _index ) === true && 0 <= _index && _index < numPage && currentPageIndex !== _index ){
2179                                 currentPageIndex = _index;
2180                         }
2181                         jqNaviItems.removeClass( 'current' ).eq( currentPageIndex).addClass( 'current' );
2182                         jqPages.hide().eq( currentPageIndex ).show();
2183                 }
2184                 function onNaviClick( e ){
2185                         // this は <a>
2186                         jumpPage( Util.getChildIndex( this.parentNode, this ));
2187                         return false;
2188                 }
2189                 function onInnerLinkClick( e ){
2190                         var jump = ( this.href || '' ).split( '#jump' ),
2191                                 n = jump[ 1 ];
2192                         if( !n ) return;
2193                         jumpPage( '' + parseFloat( n ) === n ? parseFloat( n ) : -1 );
2194                         return false;                           
2195                 }
2196                 return WINDOWS_CONTROL.createWindow(
2197                         {
2198                                 onInit: function(){
2199                                         help           = MENU_BAR_CONTROL.HELP;
2200                                         onLoadFunction = help.createAjaxSelection( onAjaxStart );
2201                                         jqAjaxContents = $( HELP_DOCUMENTS_WINDOW.elm ).find( '.window-body' ).addClass( 'loading' ).css( { overflow: 'auto' } );
2202                                         delete HELP_DOCUMENTS_WINDOW.onInit;
2203                                 },
2204                                 onFirstOpen: function( _w, _h ){
2205                                         jqAjaxContents.css( { height: _h } );
2206                                         onAjaxStart();
2207                                         delete HELP_DOCUMENTS_WINDOW.onFirstOpen;
2208                                 },
2209                                 onResize: function( _w, _h ){
2210                                         jqAjaxContents && jqAjaxContents.css( { height: _h });
2211                                 }
2212                         },
2213                         null, 'Help', 0, 215, 400, 350, false, true, true, 300, 300
2214                 );
2215         })();
2216
2217 /* ----------------------------------------
2218  * GRID_CONTROL
2219  *  - control
2220  *  - panelResizeListener
2221  */
2222         var GRID_CONTROL = ( function(){
2223                 var elmGrid,
2224                         urlBG = "url('images/grid.gif')",
2225                         visible = false;
2226
2227                 return {
2228                         init: function(){
2229                                 elmGrid = document.getElementById( 'grid' );
2230                                 delete GRID_CONTROL.init;
2231                         },
2232                         open: function(){
2233                                 delete GRID_CONTROL.open;
2234                         },
2235                         close: function(){
2236                                 
2237                         },
2238                         onPanelResize: function( _panelX, _panelY ){
2239                                 elmGrid.style.backgroundPosition = [ _panelX % 10, 'px ', _panelY % 10, 'px' ].join( '' );
2240                                 elmGrid.style.height = windowH +'px';
2241                         },
2242                         enabled: function(){
2243                                 return visible;
2244                         },
2245                         update: function(){
2246                                 $( elmGrid ).stop().css( {
2247                                         opacity:        '',
2248                                         fliter:         ''
2249                                 })[ visible === true ? 'fadeOut' : 'fadeIn' ]();
2250                                 
2251                                 visible = !visible;
2252                                 
2253                                 if( visible === true && urlBG !== null ){
2254                                         elmGrid.style.backgroundImage = urlBG;
2255                                         urlBG = null;
2256                                 }
2257                                 return visible;
2258                         }
2259                 }
2260         })();
2261                 
2262 /* ----------------------------------------
2263  * WHITE_GLASS_CONTROL
2264  *  - panelResizeListener
2265  */
2266         var WHITE_GLASS_CONTROL = ( function(){
2267                 var styleTop, styleLeft, styleRight, styleBottom;
2268
2269                 return {
2270                         init: function(){
2271                                 styleTop    = document.getElementById( 'whiteGlass-top' ).style;
2272                                 styleLeft   = document.getElementById( 'whiteGlass-left' ).style;
2273                                 styleRight  = document.getElementById( 'whiteGlass-right' ).style;
2274                                 styleBottom = document.getElementById( 'whiteGlass-bottom' ).style;
2275                                 delete WHITE_GLASS_CONTROL.init;
2276                         },
2277                         onPanelResize: function( _panelX, _panelY, _panelW, _panelH ){
2278                                 var     _w             = _panelW,
2279                                         _h             = _panelH,
2280                                         marginTop      = _panelY,
2281                                         marginBottom   = windowH -_h -marginTop,
2282                                         marginX        = _panelX,
2283                                         rightWidth     = windowW -_w -marginX;
2284                                 
2285                                 styleTop.height    = ( marginTop < 0 ? 0 : marginTop ) + 'px';
2286                                 
2287                                 styleLeft.top      = marginTop + 'px';
2288                                 styleLeft.width    = ( marginX < 0 ? 0 : marginX ) + 'px';
2289                                 styleLeft.height   = ( _h + marginBottom ) + 'px';
2290                                 
2291                                 styleRight.top     = marginTop + 'px';
2292                                 styleRight.left    = _w +marginX + 'px';
2293                                 styleRight.width   = ( rightWidth < 0 ? 0 : rightWidth ) + 'px';
2294                                 styleRight.height  = ( _h + marginBottom ) + 'px';
2295                                 
2296                                 styleBottom.top    = ( _h +marginTop ) + 'px';
2297                                 styleBottom.left   = marginX + 'px';
2298                                 styleBottom.width  = _w + 'px';
2299                                 styleBottom.height = ( marginBottom < 0 ? 0 : marginBottom ) + 'px';
2300                         }
2301                 }
2302         })();
2303
2304
2305 /* --------------------------------------------------------------------------------------------
2306  * PanelResizerClass
2307  *  - mouseEventListener
2308  */
2309         var PanelResizerClass = function( id, isTop ){
2310                 var style          = document.getElementById( id ).style,
2311                         BORDER_WIDTH   = 2,
2312                         RESIZER_HEIGHT = 30,
2313                         x              = -BORDER_WIDTH / 2,
2314                         y              = isTop === true ? ( -5 - RESIZER_HEIGHT - BORDER_WIDTH ) : 0,
2315                         w,
2316                         h = RESIZER_HEIGHT,
2317                         panelX, panelY, panelW, panelH,
2318                         offsetY, startY, startH,
2319                         isDragging = false;
2320                         
2321                 function restoreState( arg ){
2322                         if( arg && arg.length > 3){
2323                                 PANEL_CONTROL.resize( isTop, arg[ 0 ] || panelX, arg[ 1 ] || panelY, arg[ 2 ] || panelW, arg[ 3 ] || panelH );
2324                         };
2325                 };
2326                         
2327                 this.mousedown = function( _mouseX, _mouseY ){
2328                         var _x = _mouseX -panelX,
2329                                 _y = _mouseY -panelY;
2330                         if( _x < x || x + w < _x || _y < y || y + h < _y) return false;
2331                         offsetY = _y;
2332                         startY = panelY;
2333                         startH = panelH;
2334                         isDragging = true;
2335                         updateMouseCursor( 'n-resize' );
2336                         return true;
2337                 };
2338                 this.mousemove = function( _mouseX, _mouseY ){
2339                         var _x = _mouseX - panelX,
2340                                 _y = _mouseY - panelY;
2341                         if( isDragging !== true ){
2342                                 if( _x < x || x + w < _x || _y < y || y + h < _y ) return false;
2343                                 PANEL_ELEMENT_OPERATION_MANAGER.hide();
2344                                 updateMouseCursor( 'pointer' );
2345                                 return true;
2346                         } else {
2347                                 var move = _y -offsetY;
2348                                 if( isTop === true){
2349                                         if( panelH - move < MIN_PANEL_HEIGHT ){
2350                                                 move = panelH -MIN_PANEL_HEIGHT;
2351                                         };
2352                                         PANEL_CONTROL.resize( true, panelX, panelY + move, panelW, panelH - move );
2353                                 } else {
2354                                         var _h = startH + move;
2355                                         if( 0 < _h && _h < windowH -panelY -RESIZER_HEIGHT -5 -BORDER_WIDTH ){
2356                                                 PANEL_CONTROL.resize( false, panelX, panelY, panelW, _h < MIN_PANEL_HEIGHT ? MIN_PANEL_HEIGHT : _h );
2357                                         };
2358                                 };
2359                         };
2360                         return true;
2361                 };
2362                 this.mouseup = function( _mouseX, _mouseY ){
2363                         if( isDragging !== true ) return;
2364                         ( startY !== panelY || startH !== panelH ) && HISTORY_CONTROL.saveState( restoreState, [ NaN, startY, NaN, startH], [ NaN, panelY, NaN, panelH ] );
2365                         isDragging = false;
2366                         updateMouseCursor( '');
2367                 };
2368                 this.busy = function(){
2369                         return isDragging;
2370                 };
2371                 this.onPanelResize = function( _x, _y, _w, _h ){
2372                         panelX = _x;
2373                         panelY = _y;
2374                         if( panelW !== _w ){
2375                                 style.width = ( _w + 2 ) + 'px';
2376                                 panelW = _w;
2377                         }
2378                         panelH = _h;
2379                         y = isTop === true ? y : ( panelH + 5 + BORDER_WIDTH );
2380                         w = panelW + 2;
2381                 };
2382         };
2383         var     PANEL_RESIZER_TOP,
2384                 PANEL_RESIZER_BOTTOM;
2385
2386 /* ----------------------------------------
2387  * PANEL_CONTROL
2388  *  - controler
2389  *  - mouseEventListener
2390  * 
2391  * panel-border の表示と onPanelResize の通知.
2392  * panel drag.
2393  * 
2394  */
2395         var PANEL_CONTROL = ( function(){
2396                 var elmPanel, stylePanel,
2397                         DEFAULT_PANEL_WIDTH  = 400,
2398                         DEFAULT_PANEL_HEIGHT = 300,
2399                         borderSize = 2,
2400                         offsetX, offsetY, startX, startY,
2401                         isDragging = false,
2402                         isDraggable = false;
2403                 
2404                 app.addKeyEventListener( 'keychange', onSpaceUpdate, 32, false, false );
2405                 
2406                 function onSpaceUpdate( e ){
2407                         if( e.type === 'keyup' ){
2408                                 currentListener === null && updateMouseCursor( '' );
2409                                 isDraggable = false;
2410                         } else {
2411                                 currentListener === null && updateMouseCursor( 'move' );
2412                                 isDraggable = true;
2413                         };
2414                         return false;
2415                 };
2416                 
2417                 return {
2418                         x: 0,
2419                         y: 0,
2420                         w: 0,
2421                         h: 0,                   
2422                         init: function(){
2423                                 elmPanel   = document.getElementById( 'panel-tools-container' );
2424                                 stylePanel = elmPanel.style;
2425                                 
2426                                 PANEL_RESIZER_TOP    = new PanelResizerClass( 'panel-resizer-top',    true );
2427                                 PANEL_RESIZER_BOTTOM = new PanelResizerClass( 'panel-resizer-bottom', false );
2428                                 PanelResizerClass    = null;
2429                                 
2430                                 delete PANEL_CONTROL.init;
2431                         },
2432                         open: function( _panelW, _panelH, _borderSize ){
2433                                 PANEL_CONTROL.w = Type.isFinite( _panelW ) === true ? _panelW : DEFAULT_PANEL_WIDTH;
2434                                 PANEL_CONTROL.h = Type.isFinite( _panelH ) === true ? _panelH : DEFAULT_PANEL_HEIGHT;
2435                                 borderSize      = Type.isFinite( _borderSize ) === true ? _borderSize : borderSize;
2436                                 
2437                                 delete PANEL_CONTROL.open;
2438                         },
2439                         close: function(){
2440                                 
2441                         },
2442                         resize: function( isResizerTopAction, _x, _y, _w, _h ){
2443                                 PANEL_CONTROL.x = _x = _x !== undefined ? _x : PANEL_CONTROL.x;
2444                                 PANEL_CONTROL.y = _y = _y !== undefined ? _y : PANEL_CONTROL.y;
2445                                 PANEL_CONTROL.w = _w = _w !== undefined ? _w : PANEL_CONTROL.w;
2446                                 PANEL_CONTROL.h = _h = _h !== undefined ? _h : PANEL_CONTROL.h;
2447                                 
2448                                 stylePanel.left   = ( _x - borderSize ) + 'px';
2449                                 stylePanel.top    = ( _y - borderSize ) + 'px';
2450                                 stylePanel.width  = _w + 'px';
2451                                 stylePanel.height = _h + 'px';
2452                                 
2453                                 PANEL_RESIZER_TOP.onPanelResize( _x, _y, _w, _h );
2454                                 PANEL_RESIZER_BOTTOM.onPanelResize( _x, _y, _w, _h );
2455                                 GRID_CONTROL.onPanelResize( _x, _y );
2456                                 WHITE_GLASS_CONTROL.onPanelResize( _x, _y, _w, _h );
2457                                 PANEL_ELEMENT_CONTROL.onPanelResize( _x, _y, _w, _h, isResizerTopAction === true );
2458                         },
2459                         onWindowResize: function( _windowW, _windowH ){
2460                                 PANEL_CONTROL.x = Math.floor( ( _windowW - PANEL_CONTROL.w ) / 2 );
2461                                 PANEL_CONTROL.y = Math.floor( ( _windowH - PANEL_CONTROL.h ) / 2 );
2462                                 PANEL_CONTROL.resize();
2463                         },
2464                         mousemove: function( _mouseX, _mouseY ){
2465                                 if( isDraggable === true && isDragging === true ){
2466                                         PANEL_CONTROL.resize( false, startX + _mouseX - offsetX, startY + _mouseY - offsetY );
2467                                 }
2468                         },
2469                         mouseup: function( _mouseX, _mouseY ){
2470                                 if( isDraggable === true ){
2471                                         isDragging = false;
2472                                         updateMouseCursor( '' );
2473                                 }
2474                         },
2475                         mousedown: function( _mouseX, _mouseY ){
2476                                 if( isDraggable === true ){
2477                                         offsetX    = _mouseX;
2478                                         offsetY    = _mouseY;
2479                                         startX     = PANEL_CONTROL.x;
2480                                         startY     = PANEL_CONTROL.y;
2481                                         isDragging = true;
2482                                         updateMouseCursor( 'move' );
2483                                         return true;
2484                                 }
2485                         },
2486                         busy: function(){
2487                                 return isDragging === true;
2488                         }                               
2489                 }
2490         })();
2491
2492
2493 /* --------------------------------------------------------------------------------------------
2494  * CONSOLE_CONTROLER
2495  */
2496         var CONSOLE_CONTROLER = ( function(){
2497                 var LAYER_BACK_BUTTON, LAYER_FORWARD_BUTTON, DELETE_BUTTON, EDIT_BUTTON, CHANGE_BUTTON,
2498                         elmConsoleWrapper, styleConsoleWrapper,
2499                         elmConsoleParent,
2500                         styleImgConsole, styleTextConsole,
2501                         currentElement  = null,
2502                         currentType     = -1,
2503                         visible         = false,
2504                         imgConsoleWidth, imgConsoleHeight,
2505                         textConsoleWidth, textConsoleHeight,
2506                         tailSize        = 10,
2507                         buttonClickable = false;
2508                 
2509                 function buttonBackOrForward( isBack ){
2510                         var     offset = Util.getAbsolutePosition( elmConsoleWrapper );
2511                         styleConsoleWrapper.position = isBack === true ? '' : 'absolute';
2512                         styleConsoleWrapper.left     = ( isBack === true ? CONSOLE_CONTROLER.x  : offset.x ) + 'px';
2513                         styleConsoleWrapper.top      = ( isBack === true ? CONSOLE_CONTROLER.y  : offset.y ) + 'px';
2514                         buttonClickable === isBack && ( isBack === true ? elmConsoleParent : app.rootElement ).appendChild( elmConsoleWrapper );
2515                         buttonClickable = !isBack;
2516                 };
2517                 function layerBack(){
2518                         if( currentElement === null) return;
2519                         if( PANEL_ELEMENT_CONTROL.replace( currentElement, false) === false ) return;
2520                         INFOMATION_WINDOW.update( currentElement );
2521                         HISTORY_CONTROL.saveState( PANEL_ELEMENT_CONTROL.restoreReplace, [ currentElement, true ], [ currentElement, false ]);
2522                         var _z = currentElement.z;
2523                         LAYER_BACK_BUTTON.visible( _z > 0 );
2524                         LAYER_FORWARD_BUTTON.visible( _z < PANEL_ELEMENT_ARRAY.length -1 );
2525                 };
2526                 function layerForward(){
2527                         if( currentElement === null) return;
2528                         if( PANEL_ELEMENT_CONTROL.replace( currentElement, true) === false) return;
2529                         INFOMATION_WINDOW.update( currentElement);
2530                         HISTORY_CONTROL.saveState( PANEL_ELEMENT_CONTROL.restoreReplace, [ currentElement, false], [ currentElement, true]);
2531                         var _z = currentElement.z;
2532                         LAYER_BACK_BUTTON.visible( _z > 0);
2533                         LAYER_FORWARD_BUTTON.visible( _z < PANEL_ELEMENT_ARRAY.length -1);
2534                 };
2535                 function del(){
2536                         if( currentElement === null) return;
2537                         buttonBackOrForward( true);
2538                         PANEL_ELEMENT_CONTROL.remove( currentElement);
2539                         HISTORY_CONTROL.saveState( PANEL_ELEMENT_CONTROL.restore, [ true, currentElement], [ false, currentElement], true);
2540                         PANEL_ELEMENT_OPERATION_MANAGER.hide();
2541                 };
2542                 function edit(){
2543                         if( currentElement === null || currentElement.type !== PANEL_ELEMENT_TYPE_TEXT) return;
2544                         TextEditor.boot( PANEL_CONTROL.x, PANEL_CONTROL.y, currentElement );
2545                         buttonBackOrForward( true );
2546                 };
2547                 function change(){
2548                         if( currentElement === null) return;
2549                         buttonBackOrForward( true);
2550                         PremiumSatge.boot( currentElement.getArtistID(), currentElement.resourcePicture );
2551                 };
2552                 function onImageSelect( resourcePicture ){
2553                         currentElement.resourcePicture( resourcePicture );
2554                 };
2555                 return {
2556                         x: 0,
2557                         y: 0,
2558                         w: 0,
2559                         h: 0,
2560                         init: function(){
2561                                 app.addKeyEventListener( 'keydown', layerBack, 66, false, true );
2562                                 app.addKeyEventListener( 'keydown', layerForward, 70, false, true );
2563                                 app.addKeyEventListener( 'keydown', del, 68, false, true );
2564                                 app.addKeyEventListener( 'keydown', edit, 69, false, true );
2565                                 app.addKeyEventListener( 'keydown', change, 85, false, true );
2566                                 
2567                                 var elmImgConsole  = document.getElementById( 'image-element-consol' ),
2568                                         imgConsoleSize = Util.getElementSize( elmImgConsole );
2569                                 imgConsoleWidth    = imgConsoleSize.width;
2570                                 imgConsoleHeight   = imgConsoleSize.height;
2571                                 styleImgConsole    = elmImgConsole.style;
2572                                 elmImgConsole.style.display = 'none';
2573                                 
2574                                 var elmTextConsole  = document.getElementById( 'text-element-consol' ),
2575                                         textConsoleSize = Util.getElementSize( elmTextConsole );
2576                                 textConsoleWidth    = textConsoleSize.width;
2577                                 textConsoleHeight   = textConsoleSize.height;
2578                                 styleTextConsole    = elmTextConsole.style;
2579                                 styleTextConsole.display = 'none';
2580                                 
2581                                 elmConsoleWrapper   = document.getElementById( 'comic-element-consol-wrapper' );
2582                                 styleConsoleWrapper = elmConsoleWrapper.style;
2583                                 elmConsoleParent    = elmConsoleWrapper.parentNode;
2584                                 styleConsoleWrapper.display = 'none';
2585                                 
2586                                 app.addMouseEventListener( document.getElementById( 'edit-text-button' ),     'click', edit );
2587                                 app.addMouseEventListener( document.getElementById( 'delete-image-button' ),  'click', del );
2588                                 app.addMouseEventListener( document.getElementById( 'delete-text-button' ),   'click', del );
2589                                 app.addMouseEventListener( document.getElementById( 'change-image-button' ),  'click', change );
2590                                 app.addMouseEventListener( document.getElementById( 'layer-forward-button' ), 'click', layerForward );
2591                                 app.addMouseEventListener( document.getElementById( 'forward-text-button' ),  'click', layerForward );
2592                                 app.addMouseEventListener( document.getElementById( 'layer-back-button' ),    'click', layerBack );
2593                                 app.addMouseEventListener( document.getElementById( 'back-text-button' ),     'click', layerBack );
2594                                                                                         
2595                                 delete CONSOLE_CONTROLER.init;
2596                         },
2597                         open: function(){
2598                                 LAYER_BACK_BUTTON    = MENU_BAR_CONTROL.EDIT.createOption( 'layer back', 'ctrl + B', layerBack, false, true, false );
2599                                 LAYER_FORWARD_BUTTON = MENU_BAR_CONTROL.EDIT.createOption( 'layer forward', 'ctrl + F', layerForward, false, false, false );
2600                                 DELETE_BUTTON        = MENU_BAR_CONTROL.EDIT.createOption( 'delete', 'ctrl + D', del, false, true, true );
2601                                 EDIT_BUTTON          = MENU_BAR_CONTROL.EDIT.createOption( 'Edit Text', 'ctrl + E', edit, false, true, false );
2602                                 CHANGE_BUTTON        = MENU_BAR_CONTROL.EDIT.createOption( 'change', 'ctrl + U', change, false, false, true );
2603                                 
2604                                 delete CONSOLE_CONTROLER.open;
2605                         },
2606                         show: function( _currentElement, _w, _h ){
2607                                 if( visible === false ) styleConsoleWrapper.display = '';
2608                                 visible = true;
2609                                 currentElement = _currentElement;
2610                                 var _currentType = _currentElement.type,
2611                                         _z = _currentElement.z;
2612                                 if( currentType !== _currentType ){
2613                                         currentType = _currentType;
2614                                         styleImgConsole.display  = _currentType === PANEL_ELEMENT_TYPE_IMAGE ? '' : 'none';
2615                                         styleTextConsole.display = _currentType === PANEL_ELEMENT_TYPE_TEXT  ? '' : 'none';
2616                                         CONSOLE_CONTROLER.w = _currentType === PANEL_ELEMENT_TYPE_IMAGE ? imgConsoleWidth : textConsoleWidth;
2617                                         CONSOLE_CONTROLER.h = _currentType === PANEL_ELEMENT_TYPE_IMAGE ? imgConsoleHeight : textConsoleHeight;
2618                                 }
2619                                 CONSOLE_CONTROLER.x = Math.floor( ( _w - CONSOLE_CONTROLER.w ) / 2 );
2620                                 
2621                                 LAYER_BACK_BUTTON.visible( _z > 0 );
2622                                 LAYER_FORWARD_BUTTON.visible( _z < PANEL_ELEMENT_ARRAY.length - 1 );
2623                                 DELETE_BUTTON.visible( true);
2624                                 EDIT_BUTTON.visible( _currentType === PANEL_ELEMENT_TYPE_TEXT );
2625                                 CHANGE_BUTTON.visible( false);
2626                                 
2627                                 if( _w > CONSOLE_CONTROLER.w * 1.5 && _h > CONSOLE_CONTROLER.h * 1.5 ){
2628                                         CONSOLE_CONTROLER.y = Math.floor( ( _h - CONSOLE_CONTROLER.h ) / 2 );
2629                                         elmConsoleWrapper.className = '';
2630                                 } else {
2631                                         CONSOLE_CONTROLER.y = _h + tailSize;
2632                                         elmConsoleWrapper.className = 'console-out';
2633                                 };
2634                                 styleConsoleWrapper.left = CONSOLE_CONTROLER.x + 'px';
2635                                 styleConsoleWrapper.top  = CONSOLE_CONTROLER.y + 'px';
2636                         },
2637                         hide: function(){
2638                                 if( visible === true ) styleConsoleWrapper.display = 'none';
2639                                 visible = false;
2640                                 currentElement = null;
2641                                 LAYER_BACK_BUTTON.visible( false);
2642                                 LAYER_FORWARD_BUTTON.visible( false);
2643                                 DELETE_BUTTON.visible( false);
2644                                 EDIT_BUTTON.visible( false);
2645                                 CHANGE_BUTTON.visible( false);
2646                         },
2647                         mousemove: function( _mouseX, _mouseY ){
2648                                 if( CONSOLE_CONTROLER.x > _mouseX || CONSOLE_CONTROLER.y > _mouseY || CONSOLE_CONTROLER.x + CONSOLE_CONTROLER.w < _mouseX || CONSOLE_CONTROLER.y + CONSOLE_CONTROLER.h < _mouseY ){
2649                                         buttonClickable === true && buttonBackOrForward( true );
2650                                         return false;
2651                                 }
2652                                 buttonClickable === false && buttonBackOrForward( false );
2653                                 return true;
2654                         }
2655                 }
2656         })();
2657
2658 /* --------------------------------------------------------------------------------------------
2659  * TAIL_OPERATOR
2660  *  - panelElementOperator
2661  */
2662         var TAIL_OPERATOR = ( function(){
2663                 var     styleMover,
2664                         SIZE,
2665                         SIN          = Math.sin,
2666                         COS          = Math.cos,
2667                         ATAN         = Math.atan,
2668                         FLOOR        = Math.floor,
2669                         DEG_TO_RAD   = Math.PI / 180,
2670                         RAD_TO_DEG   = 1 / DEG_TO_RAD,
2671                         currentText  = null,
2672                         tailX, tailY,
2673                         x, y, w, h,
2674                         balloonW, balloonH, balloonA, radA,
2675                         visible = false,
2676                         startA;
2677                 
2678                 return {
2679                         init: function(){
2680                                 var elm    = document.getElementById( 'balloon-tail-mover' );
2681                                 SIZE       = Util.getElementSize( elm ).width;
2682                                 styleMover = elm.style;
2683                                 delete TAIL_OPERATOR.init;
2684                         },
2685                         update: function ( _w, _h, _a ){
2686                                 balloonW = _w !== undefined ? _w : balloonW;
2687                                 balloonH = _h !== undefined ? _h : balloonH;
2688                                 balloonA = _a !== undefined ? _a : balloonA;
2689                                 radA = ( balloonA - 90 ) * DEG_TO_RAD;
2690                                 tailX = FLOOR( ( ( COS( radA ) / 2 + 0.5 ) * ( balloonW + SIZE )) - SIZE / 2 );
2691                                 tailY = FLOOR( ( ( SIN( radA ) / 2 + 0.5 ) * ( balloonH + SIZE )) - SIZE / 2 );
2692                                 styleMover.left = tailX +'px';
2693                                 styleMover.top = tailY +'px';
2694                                 //log.html( [ balloonW, balloonH, balloonA].join());
2695                         },
2696                         show: function( _currentText ){
2697                                 /*
2698                                  * visibilityのほうがいい, display:none だと ie で描画が狂う
2699                                  */
2700                                 styleMover.visibility = '';
2701                                 TAIL_OPERATOR.update( _currentText.w, _currentText.h, _currentText.angle() );
2702                                 currentText = _currentText;
2703                         },
2704                         hitTest: function( _mouseX, _mouseY ){
2705                                 var _x = tailX -SIZE / 2,
2706                                         _y = tailY -SIZE / 2;
2707                                         ret = _x <= _mouseX && _y <= _mouseY && _x +SIZE >= _mouseX && _y +SIZE >= _mouseY;
2708                                 ret === true && updateMouseCursor( 'move' );
2709                                 return ret;
2710                         },
2711                         hide: function(){
2712                                 styleMover.visibility = 'hidden';
2713                                 currentText = null;
2714                         },
2715                         onStart: function( _currentText, _mouseX, _mouseY ){
2716                                 if( _currentText.type !== PANEL_ELEMENT_TYPE_TEXT ) return false;
2717                                 x = _currentText.x;
2718                                 y = _currentText.y;
2719                                 if( TAIL_OPERATOR.hitTest( _mouseX -x, _mouseY -y ) === true){
2720                                         w = _currentText.w;
2721                                         h = _currentText.h;
2722                                         currentText = _currentText;
2723                                         startA = _currentText.angle();
2724                                         return true;
2725                                 }
2726                                 return false;
2727                         },
2728                         onDrag: function( _mouseX, _mouseY ){
2729                                 _mouseX = _mouseX - x - w / 2;
2730                                 _mouseY = _mouseY - y - h / 2; //Balloonの中心を0,0とする座標系に変換
2731                                 TAIL_OPERATOR.update( w, h,
2732                                         _mouseX !== 0 ?
2733                                                 ATAN( _mouseY / _mouseX ) * RAD_TO_DEG + ( _mouseX > 0 ? 90 : 270 ) :
2734                                                 _mouseY > 0 ? 180 : 0
2735                                 );
2736                                 currentText && currentText.angle( FLOOR( balloonA + 0.5 ));
2737                                 INFOMATION_WINDOW.update( currentText );
2738                         },
2739                         onFinish: function(){
2740                                 startA !== currentText.angle() && PANEL_ELEMENT_OPERATION_MANAGER.saveStatus( x, y, w, h, startA );
2741                                 startA !== currentText.angle() && PANEL_ELEMENT_OPERATION_MANAGER.resize( x, y, w, h, currentText.angle() );
2742                                 currentText = null;
2743                         },
2744                         onCancel: function(){
2745                                 currentText.angle( startA);
2746                                 PANEL_ELEMENT_OPERATION_MANAGER.resize( x, y, w, h, startA );
2747                                 currentText = null;
2748                         }
2749                 }
2750         })();
2751
2752 /* --------------------------------------------------------------------------------------------
2753  * RESIZE_OPERATOR
2754  *  - panelElementOperator
2755  */
2756         var RESIZE_OPERATOR = ( function(){
2757                 var     HIT_AREA        = MOUSE_HIT_AREA,
2758                         POSITION_ARRAY  = [],
2759                         FLOOR           = Math.floor,
2760                         CURSOR_AND_FLIP = [
2761                                 { cursor:       'n-resize',             v: 3 },
2762                                 { cursor:       'e-resize',             h: 2 },
2763                                 { cursor:       'e-resize',             h: 1 },
2764                                 { cursor:       'n-resize',             v: 0 },
2765                                 { cursor:       'nw-resize',    h: 5, v: 6, vh: 7 },
2766                                 { cursor:       'ne-resize',    h: 4, v: 7, vh: 6 },
2767                                 { cursor:       'ne-resize',    h: 7, v: 4, vh: 5 },
2768                                 { cursor:       'nw-resize',    h: 6, v: 5, vh: 4 }
2769                         ],
2770                         elmResizerContainer,
2771                         elmResizerContainerStyle,
2772                         elmResizerTopStyle,
2773                         elmResizerLeftStyle,
2774                         elmResizerRightStyle,
2775                         elmResizerBottomStyle,
2776                         x, y, w, h,
2777                         currentIndex = -1,
2778                         currentElement,
2779                         currentIsTextElement = false;
2780                 
2781                 var RESIZE_WORK_ARRAY = [
2782                                 { x:    0, w:    0, y:  1, h:   -1}, //top
2783                                 { x:    1, w:   -1, y:  0, h:    0}, //left
2784                                 { x:    0, w:    1, y:  0, h:    0}, //right
2785                                 { x:    0, w:    0, y:  0, h:    1}, //bottom
2786                                 { x:    1, w:   -1, y:  1, h:   -1}, //top-left
2787                                 { x:    0, w:    1, y:  1, h:   -1}, //top-right
2788                                 { x:    1, w:   -1, y:  0, h:    1}, //bottom-left
2789                                 { x:    0, w:    1, y:  0, h:    1}  //bottom-right
2790                         ],
2791                         startX, startY, startW, startH, startFilpV, startFilpH, startAspect,
2792                         baseX, baseY, baseW, baseH,
2793                         currentX, currentY, currentW, currentH,
2794                         offsetX, offsetY,
2795                         lock  = false,
2796                         error = 0;
2797                 
2798                 function draw( _x, _y, _w, _h ){
2799                         x = _x = _x !== undefined ? _x : x;
2800                         y = _y = _y !== undefined ? _y : y;
2801                         w = _w = _w !== undefined ? _w : w;
2802                         h = _h = _h !== undefined ? _h : h;
2803                         try {
2804                                 elmResizerContainerStyle.left   = _x + 'px';
2805                                 elmResizerContainerStyle.top    = _y + 'px';
2806                                 elmResizerContainerStyle.width  = _w + 'px';
2807                                 elmResizerContainerStyle.height = _h + 'px';
2808                                 elmResizerTopStyle.left = elmResizerBottomStyle.left = FLOOR( _w / 2 - 5 ) + 'px';
2809                                 elmResizerLeftStyle.top = elmResizerRightStyle.top   = FLOOR( _h / 2 - 5 ) + 'px';
2810                         } catch(e){
2811                                 alert( [x, y, w, h].join( ','));
2812                                 return;
2813                         }
2814                         
2815                         POSITION_ARRAY.splice( 0, POSITION_ARRAY.length );
2816                         POSITION_ARRAY.push(
2817                                 {x:     _x +5,                                  y:      _y -HIT_AREA,           w:      _w -5 *2,               h:      HIT_AREA +5},
2818                                 {x: _x -HIT_AREA,                       y:      _y +HIT_AREA +5,        w:      HIT_AREA +5,    h:      _h -5 *2},
2819                                 {x: _x + _w -5,                         y:      _y +HIT_AREA +5,        w:      HIT_AREA +5,    h:      _h -5 *2},
2820                                 {x:     _x +5,                                  y:      _y +_h -5,                      w:      _w -5 *2,               h:      HIT_AREA +5},
2821                                 {x:     _x -HIT_AREA,                   y:      _y -HIT_AREA,           w:      HIT_AREA +5,    h:      HIT_AREA +5},
2822                                 {x: _x + _w -HIT_AREA,          y:      _y -HIT_AREA,           w:      HIT_AREA +5,    h:      HIT_AREA +5},
2823                                 {x:     _x -HIT_AREA,                   y:      _y +_h -5,                      w:      HIT_AREA +5,    h:      HIT_AREA +5},
2824                                 {x:     _x +_w -5,                              y:      _y +_h -5,                      w:      HIT_AREA +5,    h:      HIT_AREA +5}
2825                         );
2826                 }
2827                 
2828                 function update( _x, _y, _w, _h ){
2829                         var __w, __h;
2830                         _x = _x !== undefined ? _x : currentX;
2831                         _y = _y !== undefined ? _y : currentY;
2832                         _w = _w !== undefined ? _w : currentW;
2833                         _h = _h !== undefined ? _h : currentH;
2834                         
2835                         if( currentIsTextElement === false && currentIndex > 3 && app.shiftEnabled() === true){
2836                                 if( startAspect >= 1 ){
2837                                         __w = _w;
2838                                         _w = FLOOR( startAspect * _h );
2839                                         _x = _x +( currentIndex % 2 === 0 ? __w - _w : 0);
2840                                 } else {
2841                                         __h = _h;
2842                                         _h = FLOOR( _w / startAspect );
2843                                         _y = _y + ( currentIndex <= 5 ? __h - _h : 0);
2844                                 }
2845                         }
2846                         draw( x = _x, y = _y, w = _w, h = _h );
2847                         currentElement.resize( _x, _y, _w, _h );
2848                         currentIsTextElement === true && TAIL_OPERATOR.update( _w, _h );
2849                         CONSOLE_CONTROLER.show( currentElement, _w, _h );
2850                         INFOMATION_WINDOW.update( currentElement);
2851                 }
2852                 
2853                 function flip( _flipH, _flipV ){
2854                         var p = CURSOR_AND_FLIP[ currentIndex ];
2855                         currentIndex = _flipH === true || _flipV === true ? p[
2856                                         _flipH === true && _flipV === true ? 'vh' : ( _flipH === true ? 'h' : 'v' )
2857                                 ] : currentIndex;
2858                         updateMouseCursor( CURSOR_AND_FLIP[ currentIndex ].cursor );
2859                         elmResizerContainer.className = 'current-resizer-is-' + currentIndex;
2860                         currentElement.flip( _flipH, _flipV );
2861                 }
2862                 return {
2863                         init: function(){
2864                                 elmResizerContainer      = document.getElementById( 'comic-element-resizer-container');
2865                                 elmResizerContainerStyle = elmResizerContainer.style;
2866                                 elmResizerContainerStyle.display = 'none';
2867                                 
2868                                 elmResizerTopStyle       = document.getElementById( 'comic-element-resizer-top').style;
2869                                 elmResizerLeftStyle      = document.getElementById( 'comic-element-resizer-left').style;
2870                                 elmResizerRightStyle     = document.getElementById( 'comic-element-resizer-right').style;
2871                                 elmResizerBottomStyle    = document.getElementById( 'comic-element-resizer-bottom').style;
2872                                 
2873                                 delete RESIZE_OPERATOR.init;
2874                         },
2875                         update: draw,
2876                         index: function( _mouseX, _mouseY ){
2877                                 var     p, i;
2878                                 for( i=4; i<8; i++ ){
2879                                         p = POSITION_ARRAY[ i ];
2880                                         if( p.x <= _mouseX && p.y <= _mouseY && p.x + p.w >= _mouseX && p.y +p.h >= _mouseY ){
2881                                                 updateMouseCursor( CURSOR_AND_FLIP[ i].cursor);
2882                                                 elmResizerContainer.className = 'current-resizer-is-' +i;
2883                                                 return currentIndex = i;
2884                                         }
2885                                 }
2886                                 for( i=0; i<4; i++ ){
2887                                         p = POSITION_ARRAY[ i ];
2888                                         if( p.x <= _mouseX && p.y <= _mouseY && p.x + p.w >= _mouseX && p.y +p.h >= _mouseY){
2889                                                 updateMouseCursor( CURSOR_AND_FLIP[ i].cursor);
2890                                                 elmResizerContainer.className = 'current-resizer-is-' +i;
2891                                                 return currentIndex = i;
2892                                         }
2893                                 }
2894                                 updateMouseCursor( '' );
2895                                 elmResizerContainer.className = '';
2896                                 return -1;
2897                         },
2898                         show: function( _currentElement ){
2899                                 currentElement = _currentElement;
2900                                 currentIsTextElement = _currentElement.type === PANEL_ELEMENT_TYPE_TEXT;
2901                                 elmResizerContainerStyle.display = '';
2902                         },
2903                         hide: function(){
2904                                 currentElement = null;
2905                                 elmResizerContainerStyle.display = 'none';
2906                         },
2907                         onStart: function( _currentElement, _mouseX, _mouseY ){
2908                                 currentElement = _currentElement;
2909                                 currentIsTextElement = _currentElement.type === PANEL_ELEMENT_TYPE_TEXT;
2910                                 if( _currentElement.keepSize === true) return false;
2911                                 currentIndex = this.index( _mouseX, _mouseY);
2912                                 if( currentIndex === -1) return false;
2913                                 offsetX = _mouseX;
2914                                 offsetY = _mouseY;
2915                                 startX = baseX = _currentElement.x;
2916                                 startY = baseY = _currentElement.y;
2917                                 startW = baseW = _currentElement.w;
2918                                 startH = baseH = _currentElement.h;
2919                                 if( _currentElement.type === PANEL_ELEMENT_TYPE_IMAGE){
2920                                         startFilpV = _currentElement.flipV();
2921                                         startFilpH = _currentElement.flipH();                                                   
2922                                 }
2923                                 startAspect = startW /startH;
2924                                 return true;
2925                         },
2926                         onDrag: function( _mouseX, _mouseY ){
2927                                 var com = RESIZE_WORK_ARRAY[ currentIndex],
2928                                         moveX = _mouseX -offsetX,
2929                                         moveY = _mouseY -offsetY,
2930                                         _updated = moveX !== 0 || moveY !== 0,
2931                                         _x, _y, _w, _h,
2932                                         _thisError = 0;
2933                                         
2934                                 var _memoryX = 0,
2935                                         _memoryY = 0,
2936                                         _momoryW = 0,
2937                                         _momoryH = 0;
2938                                 /*
2939                                  * Opera 11+ often forget values, why ??
2940                                  */
2941                                 while( _x === undefined || _y === undefined || _w === undefined || _h === undefined){
2942                                         _x = _x !== undefined ? _x : baseX +moveX *com.x;
2943                                         _y = _y !== undefined ? _y : baseY +moveY *com.y;
2944                                         _w = _w !== undefined ? _w : baseW +moveX *com.w;
2945                                         _h = _h !== undefined ? _h : baseH +moveY *com.h;
2946                                         error += _thisError === 0 ? 0 : 1;
2947                                         ++_thisError;
2948                                         if( _thisError > 9999){
2949                                                 ++error
2950                                                 //alert( 'opera error' +error);
2951                                                 this.onCancel;
2952                                                 return;
2953                                         }
2954                                 }
2955                                 
2956                                 if( _w >= MIN_ELEMENT_SIZE && _h >= MIN_ELEMENT_SIZE){
2957                                         
2958                                 } else 
2959                                 if( _w >= -MIN_ELEMENT_SIZE && _h >= -MIN_ELEMENT_SIZE){
2960                                         //return;
2961                                         if( _w < MIN_ELEMENT_SIZE){
2962                                                 //_x += Math.abs( MIN_ELEMENT_SIZE -_w);
2963                                                 _x = currentX;
2964                                                 _w = MIN_ELEMENT_SIZE;
2965                                         }
2966                                         if( _h < MIN_ELEMENT_SIZE){
2967                                                 //_y += Math.abs( MIN_ELEMENT_SIZE -_h);
2968                                                 _y = currentY;
2969                                                 _h = MIN_ELEMENT_SIZE;
2970                                         }
2971                                 } else 
2972                                 if( currentElement.type === PANEL_ELEMENT_TYPE_TEXT){
2973                                         return;
2974                                 } else 
2975                                 if( _w < -MIN_ELEMENT_SIZE || _h < -MIN_ELEMENT_SIZE){
2976
2977                                         if( _w < -MIN_ELEMENT_SIZE && _h > MIN_ELEMENT_SIZE){
2978                                         // flipH
2979                                                 _memoryX = _x;
2980                                                 baseX = _x = _x +_w;
2981                                                 baseY = _y;
2982                                                 baseW = _w = _memoryX -_x;
2983                                                 baseH = _h;
2984                                                 flip( true, false);
2985                                                 flipV = currentElement.flipV();
2986                                         } else 
2987                                         if( _w > MIN_ELEMENT_SIZE && _h < -MIN_ELEMENT_SIZE){
2988                                         // flipV
2989                                                 _memoryY = _y;
2990                                                 baseX = _x;
2991                                                 baseY = _y = _y +_h;
2992                                                 baseW = _w;
2993                                                 baseH = _h = _memoryY -_y;
2994                                                 flip( false, true);
2995                                                 flipH = currentElement.flipH();
2996                                         } else {
2997                                         // flipVH
2998                                                 _memoryX = _x;
2999                                                 _memoryY = _y;
3000                                                 baseX = _x = _x +_w;
3001                                                 baseY = _y = _y +_h;
3002                                                 baseW = _w = _memoryX -_x;
3003                                                 baseH = _h = _memoryY -_y;
3004                                                 flip( true, true);
3005                                                 flipV = currentElement.flipV();
3006                                                 flipH = currentElement.flipH();
3007                                         }
3008                                         _updated = true;
3009                                         offsetX = _mouseX;
3010                                         offsetY = _mouseY;      
3011                                 }
3012                                 currentX = _x;
3013                                 currentY = _y;
3014                                 currentW = _w;
3015                                 currentH = _h;
3016                                 _updated === true && update( _x, _y, _w, _h );
3017                                 /*
3018                                 log.html( [
3019                                                 'currentIndex:', currentIndex, 
3020                                                 'baseW', baseW, 'baseH', baseH,'<br>',
3021                                                 'mouse', _mouseX, _mouseY,'<br>',
3022                                                 'move', moveX, moveY,'<br>',
3023                                                 'xy', _x, _y, 'wh',_w, _h,'<br>',
3024                                                 'com.w', com.w, 'com.h', com.h,'<br>',
3025                                                 'current',currentW, currentH,'<br>',
3026                                                 'result', y, h,
3027                                                 'err', error
3028                                 ].join( ' , ')); */
3029                         },
3030                         onFinish: function(){
3031                                 updateMouseCursor( '');
3032                                 if( w === startW && h === startH && x === startX && y === startY) return;
3033                                 PANEL_ELEMENT_OPERATION_MANAGER.resize( x, y, w, h);
3034                                 currentElement.resize( x, y, w, h);
3035                                 PANEL_ELEMENT_OPERATION_MANAGER.saveStatus( startX, startY, startW, startH, undefined, startFilpV, startFilpH);
3036                         },
3037                         onCancel: function(){
3038                                 updateMouseCursor( '');
3039                                 PANEL_ELEMENT_OPERATION_MANAGER.resize( startX, startY, startW, startH);
3040                                 currentElement.type === PANEL_ELEMENT_TYPE_IMAGE ?
3041                                         currentElement.animate( startX, startY, startW, startH, startFilpV, startFilpH) :
3042                                         currentElement.animate( startX, startY, startW, startH, angle);
3043                         },
3044                         lock: function( _lock ){
3045                                 if( _lock !== undefined){
3046                                         elmResizerContainerStyle.borderColor = _lock === true ? 'blue' : '';
3047                                         lock = _lock;
3048                                 }
3049                                 return lock;
3050                         },
3051                         onShiftUpdate: update,
3052                         onCtrlUpdate: update
3053                 }
3054         })();
3055
3056 /* --------------------------------------------------------------------------------------------
3057  * POSITION_OPERATOR
3058  *  - panelElementOperator
3059  */
3060         var POSITION_OPERATOR = ( function(){
3061                 var currentElement,
3062                         startX, startY,
3063                         x, y,
3064                         offsetX, offsetY,
3065                         isCopy = false;
3066                 function update( _x, _y ){
3067                         x = _x !== undefined ? _x : x;
3068                         y = _y !== undefined ? _y : y;
3069                         RESIZE_OPERATOR.update( x, y );
3070                         currentElement.resize( x, y );
3071                         INFOMATION_WINDOW.update( currentElement );
3072                 };
3073                 return {
3074                         init: function(){
3075                                 delete POSITION_OPERATOR.init;
3076                         },
3077                         onStart: function( _currentElement, _mouseX, _mouseY ){
3078                                 currentElement = _currentElement;
3079                                 offsetX = _mouseX;
3080                                 offsetY = _mouseY;
3081                                 startX  = x = _currentElement.x;
3082                                 startY  = y = _currentElement.y;
3083                                 updateMouseCursor( 'move' );
3084                         },
3085                         onDrag: function( _mouseX, _mouseY ){
3086                                 var moveX = _mouseX - offsetX,
3087                                         moveY = _mouseY - offsetY,
3088                                         _x    = startX + moveX,
3089                                         _y    = startY + moveY;
3090                                 if( GRID_CONTROL.enabled() === true ){
3091                                         _x = Math.floor( _x / 10 ) * 10;
3092                                         _y = Math.floor( _y / 10 ) * 10;
3093                                 };
3094                                 update( _x, _y );
3095                         },
3096                         onFinish: function(){
3097                                 updateMouseCursor( '' );
3098                                 if( x === startX && y === startY ) return;
3099                                 PANEL_ELEMENT_OPERATION_MANAGER.resize( x, y );
3100                                 currentElement.resize( x, y );
3101                                 PANEL_ELEMENT_OPERATION_MANAGER.saveStatus( startX, startY );
3102                         },
3103                         onCancel: function(){
3104                                 updateMouseCursor( '' );
3105                                 PANEL_ELEMENT_OPERATION_MANAGER.resize( startX, startY );
3106                                 currentElement.animate( startX, startY );
3107                         },
3108                         onShiftUpdate: update,
3109                         onCtrlUpdate: update
3110                 }
3111         })();
3112
3113
3114 /* --------------------------------------------------------------------------------------------
3115  * PANEL_ELEMENT_OPERATION_MANAGER
3116  */
3117         var PANEL_ELEMENT_OPERATION_MANAGER = ( function(){
3118                 var     HIT_AREA             = MOUSE_HIT_AREA,
3119                         currentIsTextElement = false,
3120                         currentOperator      = null,
3121                         currentElement       = null,
3122                         currentX, currentY, currentW, currentH, angle, flipV, flipH;
3123
3124                         function resize( _x, _y, _w, _h, _angle ){
3125                                 currentX = _x = _x !== undefined ? _x : currentX;
3126                                 currentY = _y = _y !== undefined ? _y : currentY;
3127                                 currentW = _w = _w !== undefined ? _w : currentW;
3128                                 currentH = _h = _h !== undefined ? _h : currentH;
3129                                 angle = _angle = _angle !== undefined ? _angle : angle;
3130
3131                                 RESIZE_OPERATOR.update( _x, _y, _w, _h );
3132                                 currentIsTextElement === true && TAIL_OPERATOR.update( _w, _h, angle );
3133                                 CONSOLE_CONTROLER.show( currentElement, _w, _h );
3134                                 INFOMATION_WINDOW.update( currentElement );
3135                         };
3136                         function show( _currentElement ){
3137                                 currentElement === null && RESIZE_OPERATOR.show( _currentElement );
3138                                 if( currentElement !== _currentElement ){
3139                                         currentElement = _currentElement;
3140                                         
3141                                         currentIsTextElement = ( _currentElement.type === PANEL_ELEMENT_TYPE_TEXT );
3142                                         currentIsTextElement === true ? TAIL_OPERATOR.show( _currentElement ) : TAIL_OPERATOR.hide();
3143                                         
3144                                         flipV = currentIsTextElement === false ? _currentElement.flipV() : 0;
3145                                         flipH = currentIsTextElement === false ? _currentElement.flipH() : 0;
3146                                         
3147                                         resize(
3148                                                 _currentElement.x, _currentElement.y, _currentElement.w, _currentElement.h,
3149                                                 currentIsTextElement === true ? _currentElement.angle() : 0
3150                                         );
3151                                 };
3152                         };
3153                         
3154                 return {
3155                         init: function(){
3156                                 TAIL_OPERATOR.init();
3157                                 RESIZE_OPERATOR.init();
3158                                 POSITION_OPERATOR.init();
3159                                 
3160                                 app.addKeyEventListener( 'keychange', function( e ){
3161                                         currentOperator !== null && currentOperator.onShiftUpdate && currentOperator.onShiftUpdate();
3162                                         return false;
3163                                 }, 16 );
3164                                 app.addKeyEventListener( 'keychange', function( e ){
3165                                         currentOperator !== null && currentOperator.onCtrlUpdate && currentOperator.onCtrlUpdate();
3166                                         return false;
3167                                 }, 17 );
3168                                 app.addKeyEventListener( 'keydown', function( e ){
3169                                         currentOperator !== null && currentOperator.onCancel && currentOperator.onCancel();
3170                                         currentOperator = null;
3171                                         return false;
3172                                 }, 27, false, false );
3173                                 
3174                                 delete PANEL_ELEMENT_OPERATION_MANAGER.init;
3175                         },
3176                         open: function(){
3177                                 PANEL_ELEMENT_OPERATION_MANAGER.hide();
3178                                 
3179                                 delete PANEL_ELEMENT_OPERATION_MANAGER.open;
3180                         },
3181                         close: function(){
3182                                 
3183                         },
3184                         hide: function(){
3185                                 currentElement !== null && RESIZE_OPERATOR.hide();
3186                                 currentElement = null;
3187                                 updateMouseCursor( '' );
3188                                 TAIL_OPERATOR.hide();
3189                                 CONSOLE_CONTROLER.hide();
3190                                 INFOMATION_WINDOW.update( null );
3191                         },
3192                         resize: resize,
3193                         restoreState: function( arg ){
3194                                 if( arg && arg.length !== 8 ) return;
3195                                 var _currentElement = arg[ 0 ],
3196                                         _x = arg[ 1 ], _y = arg[ 2 ], _w = arg[ 3 ], _h = arg[ 4 ],
3197                                         _a = arg[ 5 ],
3198                                         _flipV = arg[ 6 ], _flipH = arg[ 7 ];
3199                                 if( !_currentElement && !currentOperator ) return;
3200                                 _currentElement.type === PANEL_ELEMENT_TYPE_IMAGE ?
3201                                         _currentElement.animate( _x, _y, _w, _h, _flipV, _flipH ) :
3202                                         _currentElement.animate( _x, _y, _w, _h, _a );
3203                                 currentOperator !== null && currentOperator.onCancel && currentOperator.onCancel();
3204                                 currentOperator = null;
3205                                 currentElement === _currentElement ? resize( _x, _y, _w, _h, _a ) : show( _currentElement );
3206                         },
3207                         saveStatus: function( startX, startY, startW, startH, startA, startFilpV, startFilpH ){
3208                                 startX = startX !== undefined ? startX : currentX;
3209                                 startY = startY !== undefined ? startY : currentY;
3210                                 startW = startW !== undefined ? startW : currentW;
3211                                 startH = startH !== undefined ? startH : currentH;
3212                                 startA = startA !== undefined ? startA : angle;
3213                                 startFilpV = startFilpV !== undefined ? startFilpV : flipV;
3214                                 startFilpH = startFilpH !== undefined ? startFilpH : flipH;
3215                                 currentElement && HISTORY_CONTROL.saveState( PANEL_ELEMENT_OPERATION_MANAGER.restoreState,
3216                                         [ currentElement, startX, startY, startW, startH, startA, startFilpV, startFilpH],
3217                                         [ currentElement, currentX, currentY, currentW, currentH, angle, flipV, flipH]
3218                                 );
3219                         },
3220                         busy: function(){
3221                                 return currentOperator !== null;
3222                         },
3223                         hitTest: function( _mouseX, _mouseY, _panelElement ){
3224                                 var _x, _y, _w, _h;
3225                                 if( _panelElement === currentElement ){
3226                                         var _consoleX = CONSOLE_CONTROLER.x;
3227                                         _x = currentX +( _consoleX < 0 ? _consoleX : 0 ) - HIT_AREA;
3228                                         _y = currentY - HIT_AREA;
3229                                         var _consoleW = CONSOLE_CONTROLER.w;
3230                                         _w = ( _consoleW < currentW ? currentW : _consoleW ) + HIT_AREA * 2;
3231                                         var _consoleY = CONSOLE_CONTROLER.y;
3232                                         _h = ( _consoleY < currentH ? currentH : _consoleY + CONSOLE_CONTROLER.h ) + HIT_AREA * 2;
3233                                 } else {
3234                                         _x = _panelElement.x - HIT_AREA;
3235                                         _y = _panelElement.y - HIT_AREA;
3236                                         _w = _panelElement.w + HIT_AREA *2;
3237                                         _h = _panelElement.h + HIT_AREA *2;
3238                                 }
3239                                 return _x <= _mouseX && _mouseX <= _x + _w && _y <= _mouseY && _mouseY <= _y + _h;
3240                         },
3241                         mousedown: function( _currentElement, _mouseX, _mouseY ){
3242                                 //show( _currentElement);
3243                                 if( currentIsTextElement === true && TAIL_OPERATOR.onStart( _currentElement, _mouseX, _mouseY) === true){
3244                                         currentOperator = TAIL_OPERATOR;
3245                                 } else
3246                                 if( RESIZE_OPERATOR.onStart( _currentElement, _mouseX, _mouseY) === true){
3247                                         currentOperator = RESIZE_OPERATOR;
3248                                 } else {
3249                                         POSITION_OPERATOR.onStart( _currentElement, _mouseX, _mouseY)
3250                                         currentOperator = POSITION_OPERATOR;
3251                                 }
3252                         },
3253                         mousemove: function( _currentElement, _mouseX, _mouseY ){
3254                                 show( _currentElement);
3255                                 if( currentOperator !== null){
3256                                         currentOperator.onDrag( _mouseX, _mouseY );
3257                                 } else
3258                                 if( currentElement !== null){
3259                                         CONSOLE_CONTROLER.mousemove( _mouseX - currentX, _mouseY - currentY );
3260                                         if( currentIsTextElement === false || TAIL_OPERATOR.hitTest( _mouseX -currentX, _mouseY -currentY) === false){
3261                                                 RESIZE_OPERATOR.index( _mouseX, _mouseY);
3262                                         }
3263                                 }
3264                         },
3265                         mouseup: function( _currentElement, _mouseX, _mouseY ){
3266                                 currentOperator !== null && currentOperator.onFinish();
3267                                 currentOperator = null;
3268                         }
3269                 }
3270         })();
3271         /*
3272          *  // PANEL_ELEMENT_OPERATION_MANAGER
3273          */
3274
3275         var AbstractPanelElement = function( COMIC_ELM_TYPE ){
3276                 this.type = COMIC_ELM_TYPE;
3277                 this.hitTest = function( _mouseX, _mouseY ){
3278                         return PANEL_ELEMENT_OPERATION_MANAGER.hitTest( _mouseX, _mouseY, this );
3279                 }
3280                 this.shift = function( _shiftX, _shiftY ){
3281                         this.resize( this.x + _shiftX, this.y + _shiftY);
3282                 }
3283                 this.busy = function(){
3284                         return PANEL_ELEMENT_OPERATION_MANAGER.busy();
3285                 }
3286                 this.mousemove = function( _mouseX, _mouseY ){
3287                         PANEL_ELEMENT_OPERATION_MANAGER.mousemove( this, _mouseX, _mouseY );
3288                 }
3289                 this.mouseup = function( _mouseX, _mouseY ){
3290                         PANEL_ELEMENT_OPERATION_MANAGER.mouseup( this, _mouseX, _mouseY );
3291                 }
3292                 this.mousedown = function( _mouseX, _mouseY ){
3293                         PANEL_ELEMENT_OPERATION_MANAGER.mousedown( this, _mouseX, _mouseY );
3294                 }
3295         };
3296
3297 /* --------------------------------------------------------------------------------------------
3298  * ImageElementClass
3299  */
3300         var     jqImageElementOrigin;
3301         var ImageElementClass = function( data ){
3302                 jqImageElementOrigin = jqImageElementOrigin || $( app.fetchHTMLElement( 'imgElementTemplete' ) );
3303                 
3304                 var jqWrap          = jqImageElementOrigin.clone( true ),
3305                         flipH           = data.width  < 0 ? -1 : 1,
3306                         flipV           = data.height < 0 ? -1 : 1,
3307                         resourcePicture = data.resource_picture,
3308                         actualW         = data.resource_picture.width,
3309                         actualH         = data.resource_picture.height,
3310                         reversibleImage = null,
3311                         self            = this,
3312                         x, y, z, w, h;
3313                 function flipReversibleImage(){
3314                         reversibleImage && reversibleImage.resize( flipH * w, flipV * h );
3315                 };
3316                 function updateResourcePicture( _resourcePicture ){
3317                         resourcePicture = _resourcePicture;
3318                         
3319                         actualW = _resourcePicture.width;
3320                         actualH = _resourcePicture.height;
3321                         
3322                         var _reversibleImage = pettanr.image.createReversibleImage( 
3323                                         [ pettanr.CONST.RESOURCE_PICTURE_PATH, _resourcePicture.id, '.', _resourcePicture.ext ].join(''),
3324                                         flipH * w, flipV * h
3325                                 );
3326                         if( reversibleImage !== null ){
3327                                 jqWrap.children( reversibleImage.elm ).replaceWith( _reversibleImage.elm );
3328                                 reversibleImage.destroy();
3329                         } else {
3330                                 jqWrap.append( _reversibleImage.elm );
3331                         }
3332                         reversibleImage = _reversibleImage;
3333                 };
3334                 /* global methods */
3335                 this.$ = jqWrap;
3336                 //this.x = x;
3337                 //this.y = y;
3338                 //this.w = w;
3339                 //this.h = h;
3340                 this.z = data.z;
3341                 this.timing = data.t || PANEL_ELEMENT_ARRAY.length + 1;
3342                 this.keepSize = false;
3343                 this.init = function(){
3344                         updateResourcePicture( data.resource_picture );
3345                         self.resize( data.x, data.y, Math.abs( data.width ), Math.abs( data.height ) );
3346                         delete self.init;
3347                 };
3348                 this.flip = function( _updateH, _updateV ){
3349                         if( _updateH !== true && _updateV !== true ) return;
3350                         flipH = _updateH === true ? -flipH : flipH;
3351                         flipV = _updateV === true ? -flipV : flipV;
3352                         reversibleImage.resize( flipH * w, flipV * h );
3353                 };
3354                 this.flipV = function(){ return flipV;}
3355                 this.flipH = function(){ return flipH;}
3356                 this.resourcePicture = function( _resourcePicture ){
3357                         if( _resourcePicture && _resourcePicture !== resourcePicture ){
3358                                 HISTORY_CONTROL.saveState( updateResourcePicture, resourcePicture, _resourcePicture );
3359                                 updateResourcePicture( _resourcePicture );
3360                         };
3361                         return resourcePicture;
3362                 };
3363                 this.getArtistID = function(){
3364                         return resourcePicture.artist_id || resourcePicture.artist.id || -1;
3365                 };
3366                 this.actualW = function(){ return actualW;}
3367                 this.actualH = function(){ return actualH;}
3368                 this.resize = function( _x, _y, _w, _h, animate ){
3369                         self.x = x = Type.isFinite( _x ) === true ? _x : x;
3370                         self.y = y = Type.isFinite( _y ) === true ? _y : y;
3371                         self.w = w = Type.isFinite( _w ) === true ? _w : w;
3372                         self.h = h = Type.isFinite( _h ) === true ? _h : h;
3373                         jqWrap[ animate === true ? 'animate' : 'css' ]( { 
3374                                 left:   x,
3375                                 top:    y,
3376                                 width:  w,
3377                                 height: h
3378                         }, 250,  flipReversibleImage );
3379                         animate !== true && flipReversibleImage();
3380                 };
3381                 this.animate = function ( _x, _y, _w, _h, _flipH, _flipV ){
3382                         flipH = _flipH !== undefined ? _flipH : flipH;
3383                         flipV = _flipV !== undefined ? _flipV : flipV;
3384                         self.resize( _x, _y, _w, _h, true );
3385                 };
3386                 this.destroy = function(){
3387                         delete self.destroy;
3388                         
3389                         reversibleImage.destroy();
3390                         jqWrap.stop().remove();
3391                         jqWrap = reversibleImage = resourcePicture = data = self = null;
3392                 };
3393         };
3394         ImageElementClass.prototype = new AbstractPanelElement( PANEL_ELEMENT_TYPE_IMAGE );
3395 /*
3396  * / ImageElementClass
3397  * --------------------------------------------------------------------------------------------
3398  */
3399
3400
3401 /* --------------------------------------------------------------------------------------------
3402  * TextElementClass
3403  * 
3404  * type
3405  * 0.none
3406  * 1.speach balloon
3407  * 2.think
3408  * 3.bom
3409  * 4.black-box( dq style)
3410  * 5.blue-box( ff style)
3411  * 
3412  */
3413         var jqTextElementOrigin;
3414         var TextElementClass = function( data ){
3415                 jqTextElementOrigin = jqTextElementOrigin || ( function(){
3416                         var _OLD_IE = $( app.fetchHTMLElement( 'textElementTempleteForOldIE' ) ),
3417                                 _MODERN = $( app.fetchHTMLElement( 'textElementTemplete' ) );
3418                         return UA.isIE === true && UA.ieRenderingVersion < 8 ? _OLD_IE : _MODERN;
3419                 })();
3420                 
3421                 var JQ_WRAPPER = jqTextElementOrigin.clone( true ),
3422                         elmText = JQ_WRAPPER.find( 'td,.speach-inner' ).get( 0 ),
3423                         type     = data.balloon_template_id,
3424                         text     = ( function(){
3425                                 var _speachs = data.speeches_attributes;
3426                                 for( var k in _speachs ){
3427                                         return _speachs[ k ].content || '';
3428                                 }
3429                                 return '';
3430                         })(),
3431                         balloon = pettanr.balloon.createBalloon( data.width, data.height, data.tail, type ),
3432                         x, y, w, h, a,
3433                         self = this;
3434                 
3435                 JQ_WRAPPER.find( 'img' ).eq( 0 ).replaceWith( balloon.elm );
3436                 
3437                 function updateType( _type ){
3438                         if( type !== _type ){
3439                                 type = _type || type;
3440                                 balloon.type( type );
3441                         }
3442                 }
3443                 function updateAngle( _a ){
3444                         if( _a !== undefined && a !== _a ){
3445                                 a = _a !== undefined ? _a : a;
3446                                 balloon.angle( a );
3447                         }
3448                 }
3449                 function updateText( _text ){
3450                         text = _text || text || '';
3451                         elmText.firstChild.data = text;
3452                 }
3453                 function resizeBalloon(){
3454                         balloon && balloon.resize( a, w, h );
3455                 }
3456                 
3457                 /* global methods */
3458                 this.$ = JQ_WRAPPER;
3459                 //this.x = x;
3460                 //this.y = y;
3461                 //this.w = w;
3462                 //this.h = h;
3463                 this.z = data.z;
3464                 this.timing = data.t || PANEL_ELEMENT_ARRAY.length + 1;
3465                 this.init = function(){
3466                         updateText();
3467                         self.resize( data.x, data.y, data.width, data.height, data.tail );
3468                         delete self.init;
3469                 };
3470                 this.angle = function( _a ){
3471                         _a !== undefined && self.resize( x, y, w, h, _a );
3472                         return a;
3473                 };
3474                 this.text = function( _text ){
3475                         if( _text && text !== _text) {
3476                                 HISTORY_CONTROL.saveState( updateText, text || '', _text );
3477                                 updateText( _text );
3478                         }
3479                         return text;
3480                 };
3481                 this.resize = function( _x, _y, _w, _h, _a, animate ){
3482                         self.x = x = _x !== undefined ? _x : x;
3483                         self.y = y = _y !== undefined ? _y : y;
3484                         self.w = w = _w !== undefined ? _w : w;
3485                         self.h = h = _h !== undefined ? _h : h;
3486                         a = _a !== undefined ? _a : a;
3487                         
3488                         JQ_WRAPPER[ animate === true ? 'animate' : 'css']( {
3489                                         left:           x,
3490                                         top:            y,
3491                                         width:          w,
3492                                         height:         h
3493                                 }, 250, resizeBalloon
3494                         );              
3495                         animate !== true && resizeBalloon();
3496                 };
3497                 this.animate = function ( _x, _y, _w, _h, _a ){
3498                         self.resize( _x, _y, _w, _h, _a, true );
3499                 };
3500                 this.destroy = function(){
3501                         delete self.destroy;
3502                         
3503                         JQ_WRAPPER.stop().remove();
3504                         balloon.destroy();
3505                         JQ_WRAPPER = elmText = data = balloon = self = null;
3506                 };
3507         }
3508         TextElementClass.prototype = new AbstractPanelElement( PANEL_ELEMENT_TYPE_TEXT );
3509
3510 /* --------------------------------------------------------------------------------------------
3511  * PANEL_ELEMENT_CONTROL
3512  *  - mouseEventListener
3513  */
3514         var PANEL_ELEMENT_CONTROL = ( function(){
3515                 var     elmContainer,
3516                         currentElement  = null,
3517                         currentLockTest = false,
3518                         currentLock     = false,
3519                         panelX, panelY, panelW, panelH,
3520                         startX, startY;
3521         /*
3522          * append, remove, replace
3523          * 
3524          * panelElement には、z-position と dom-index がある。
3525          *   z-position は 表示上の位置。大きいほど前に表示される( z-index)
3526          *   dom-index は 意味上の順番。htmlタグの登場順で、検索結果や音声読み上げブラウザで正しく意味が取れる順番。
3527          * 
3528          * editerでは、実際には z-index は使わず、htmlの順序で前後を表現する。
3529          * dom-index は、数値のみ保持して、投稿時にpanelElementを適宜に並び替える。
3530          * 
3531          * append panelElement
3532          * 1. 新しい panelElement の z-position を得る
3533          * 2. z の同じ panelElementを見つけ、その前に加える。または一番先頭へ。(PANEL_ELEMENT_ARRAY)
3534          *    zが大きいほど、PANEL_ELEMENT_ARRAYの先頭へ。
3535          * 3. dom位置は、PANEL_ELEMENT_ARRAY とは反対に、前のものほど後ろへ。
3536          * 
3537          * 
3538          * remove panelElement
3539          * 1. remove
3540          * 2. renumber z
3541          */
3542                 function appendPanelElement( _panelElement ) {
3543                         var z = Type.isFinite( _panelElement.z ) === true ? _panelElement.z : -1,
3544                                 l = PANEL_ELEMENT_ARRAY.length,
3545                                 _jqElm = _panelElement.$.stop().css( {
3546                                         filter:         '',
3547                                         opacity:        ''
3548                                 });
3549                         if( z < 0 ){
3550                                 PANEL_ELEMENT_ARRAY.unshift( _panelElement );
3551                         } else {
3552                                 for( var i = 0; i < l; ++i ){
3553                                         if( PANEL_ELEMENT_ARRAY[ i ].z < z ) break;
3554                                 };
3555                                 if( i === l ){
3556                                         PANEL_ELEMENT_ARRAY.push( _panelElement );
3557                                 } else {
3558                                         PANEL_ELEMENT_ARRAY.splice( i, 0, _panelElement );
3559                                 };
3560                         };
3561                         renumber();
3562                         _jqElm.fadeIn();                        
3563                 };
3564
3565                 function onFadeOut(){
3566                         this.parentNode.removeChild( this );
3567                 };
3568                 /*
3569                  * PANEL_ELEMENT_ARRAY の順番を基準に、zの再計算
3570                  * jqElmの並び替え。
3571                  */
3572                 function renumber(){
3573                         var _panelElement, jqElm, jqNext;
3574                         for( var i = 0, l = PANEL_ELEMENT_ARRAY.length; i < l; ++i ){
3575                                 _panelElement = PANEL_ELEMENT_ARRAY[ i ];
3576                                 jqElm = _panelElement.$;
3577                                 i === 0 && elmContainer.appendChild( jqElm.get( 0 ) );
3578                                 jqNext && jqNext.before( jqElm );
3579                                 if( phase === 1 ) _panelElement.z = l - i - 1;
3580                                 jqNext = jqElm;
3581                         };
3582                 };
3583                 function onTextInput( _panelElement ){
3584                         appendPanelElement( _panelElement );
3585                         HISTORY_CONTROL.saveState( PANEL_ELEMENT_CONTROL.restore, [ false, _panelElement ], [ true, _panelElement ], true );
3586                 };
3587         
3588                 return {
3589                         init: function(){
3590                                 elmContainer = document.getElementById( 'comic-element-container' );
3591                                 delete PANEL_ELEMENT_CONTROL.init;
3592                         },
3593                         open: function(){
3594
3595                         },
3596                         close: function(){
3597                                 var _comicElm;
3598                                 while( PANEL_ELEMENT_ARRAY.length > 0 ){
3599                                         _comicElm = PANEL_ELEMENT_ARRAY.shift();
3600                                         _comicElm.destroy && _comicElm.destroy();
3601                                 }
3602                         },
3603                         remove: function( _panelElement ){
3604                                 var l = PANEL_ELEMENT_ARRAY.length;
3605                                 for( var i=0; i<l; ++i ){
3606                                         if( PANEL_ELEMENT_ARRAY[ i ] === _panelElement ){
3607                                                 PANEL_ELEMENT_ARRAY.splice( i, 1 );
3608                                                 renumber();
3609                                                 _panelElement.$.stop().css( {
3610                                                         filter:         '',
3611                                                         opacity:        ''
3612                                                 }).fadeOut( onFadeOut );
3613                                                 currentElement = currentElement === _panelElement ? null : currentElement;
3614                                                 return;
3615                                         };
3616                                 };
3617                         },
3618                         restore: function( arg ){
3619                                 var isAppend = arg[ 0 ],
3620                                         panelElement = arg[ 1 ];
3621                                 isAppend === true ? appendPanelElement( panelElement ) :  PANEL_ELEMENT_CONTROL.remove( panelElement );
3622                         },
3623                         replace: function( _panelElement, goForward ){
3624                                 // PANEL_ELEMENT_ARRAYの再構築
3625                                 var l = PANEL_ELEMENT_ARRAY.length,
3626                                         i = -1;
3627                                 for( var j = 0; j < l; ++j ){
3628                                         if( PANEL_ELEMENT_ARRAY[ j ] === _panelElement ){
3629                                                 i = j;
3630                                                 break;
3631                                         };
3632                                 }
3633                                 if( i === -1) return false;
3634                                 if( goForward === true ){
3635                                         if( i === 0 ) return false;
3636                                         PANEL_ELEMENT_ARRAY.splice( i, 1 );
3637                                         PANEL_ELEMENT_ARRAY.splice( i - 1, 0, _panelElement );
3638                                 } else {
3639                                         if( i === l - 1 ) return false;
3640                                         PANEL_ELEMENT_ARRAY.splice( i, 1 );
3641                                         PANEL_ELEMENT_ARRAY.splice( i + 1, 0, _panelElement );
3642                                 }
3643                                 renumber( true );
3644                                 return true;
3645                         },
3646                         restoreReplace: function( arg ){
3647                                 PANEL_ELEMENT_CONTROL.replace( arg[ 0 ], arg[ 1 ] );
3648                         },
3649                         onPanelResize : function ( _panelX, _panelY, _panelW, _panelH, isResizerTopAction ){
3650                         /*
3651                          * リサイズが、ResizerTopによって行われた場合、panelElementのyを動かして見かけ上動かないようにする。
3652                          */                                     
3653                                 if( isResizerTopAction === true){
3654                                         var     _shiftX = _panelW - panelW,
3655                                                 _shiftY = _panelH - panelH;
3656                                         for( var i = PANEL_ELEMENT_ARRAY.length; i; ){
3657                                                 PANEL_ELEMENT_ARRAY[ --i ].shift( _shiftX, _shiftY );
3658                                         };
3659                                 };
3660                                 elmContainer.style.cssText = [
3661                                         'width:',  panelW = _panelW, 'px;',
3662                                         'height:', panelH = _panelH, 'px;',
3663                                         'left:',   panelX = _panelX, 'px;',
3664                                         'top:',    panelY = _panelY, 'px'
3665                                 ].join( '' );
3666                         },
3667                         mousemove: function( _mouseX, _mouseY ){
3668                                 var l    = PANEL_ELEMENT_ARRAY.length,
3669                                         _x   = _mouseX - panelX,
3670                                         _y   = _mouseY - panelY,
3671                                         _elm = currentElement;
3672                                         
3673                                 if( _elm !== null ){
3674                                         currentLockTest = currentLockTest === true && _x === 0 && _y === 0;
3675                                         if( _elm.busy() === true ){
3676                                                 _elm.mousemove( _x, _y );
3677                                                 return true;
3678                                         }
3679                                         if( _elm.hitTest( _x, _y ) === true ){
3680                                                 _elm.mousemove( _x, _y ); // cursor
3681                                                 return true;
3682                                         }
3683                                         if( currentLock === true ){
3684                                                 currentLockTest = true;
3685                                                 return true;
3686                                         }
3687                                 };
3688                                 for( var i=0; i<l; ++i ){
3689                                         _elm = PANEL_ELEMENT_ARRAY[ i ];
3690                                         // hitTest
3691                                         if( _elm.hitTest( _x, _y ) === true ){
3692                                                 _elm.mousemove( _x, _y ); // cursor
3693                                                 currentElement = _elm;
3694                                                 return true;
3695                                         };
3696                                 };
3697                                 currentElement = null;                                                  
3698                                 PANEL_ELEMENT_OPERATION_MANAGER.hide();
3699                                 return false;
3700                         },
3701                         mouseup: function( _mouseX, _mouseY ){
3702                                 var ret = currentElement !== null && currentElement.busy() === true;
3703                                 ret === true && currentElement.mouseup( _mouseX -startX || panelX, _mouseY -startY || panelY );
3704                                 currentLock = currentLockTest === true && currentElement.hitTest( _mouseX -panelX, _mouseY -panelY ) === true;
3705                                 RESIZE_OPERATOR.lock( currentLock );
3706                                 INFOMATION_WINDOW.lock( currentLock );
3707                                 return ret;
3708                         },
3709                         mousedown: function( _mouseX, _mouseY ){
3710                                 startX = panelX;
3711                                 startY = panelY;
3712                                 if( currentElement === null) return false
3713                                 currentElement.mousedown( _mouseX -startX, _mouseY -startY);
3714                                 currentLockTest = true;
3715                                 return true;
3716                         },
3717                         busy: function(){
3718                                 return currentElement !== null;
3719                         },
3720                         createImageElement: function( data ){
3721                                 if( Type.isObject( data ) === false ){
3722                                         PremiumSatge.boot( 1, PANEL_ELEMENT_CONTROL.onImageSelect );
3723                                 } else {
3724                                         PANEL_ELEMENT_CONTROL.onImageSelect( data, true );
3725                                 }
3726                         },
3727                         onImageSelect: function( data, isPanelPictureData ){
3728                                 var _panelElement;
3729                                 if( isPanelPictureData !== true ){
3730                                         _panelElement = new ImageElementClass( {
3731                                                 resource_picture:data,
3732                                                 x:               Math.floor( panelW / 2 - data.width / 2 ),
3733                                                 y:               Math.floor( panelH / 2 - data.height / 2 ),
3734                                                 z:               -1,
3735                                                 t:               PANEL_ELEMENT_ARRAY.length + 1,
3736                                                 width:           1,
3737                                                 height:          1
3738                                         });
3739                                         _panelElement.init();
3740                                         appendPanelElement( _panelElement );
3741                                         _panelElement.animate( undefined, undefined, Math.abs( data.width ), Math.abs( data.height ) );
3742                                 } else {
3743                                         _panelElement = new ImageElementClass( data );
3744                                         _panelElement.init();
3745                                         appendPanelElement( _panelElement );
3746                                 }
3747                                 HISTORY_CONTROL.saveState( PANEL_ELEMENT_CONTROL.restore, [ false, _panelElement], [ true, _panelElement ], true );
3748                         },
3749                         createTextElement: function( data ){
3750                                 var _panelElement;
3751                                 if( Type.isObject( data ) === false ){
3752                                         data = {
3753                                                 balloon_template_id:1,
3754                                                 size:               1,
3755                                                 tail:               90,
3756                                                 x:                                      Math.floor( panelW / 2 - 100 + Math.random() * 10 ),
3757                                                 y:                  Math.floor( panelH / 2 - 100 + Math.random() * 10 ),
3758                                                 z:                  -1,
3759                                                 t:                  PANEL_ELEMENT_ARRAY.length + 1,
3760                                                 width:              200,
3761                                                 height:             200,
3762                                                 speeches_attributes: {
3763                                                         text1: {
3764                                                                 content:    'Hello'
3765                                                         }
3766                                                 }
3767                                         }
3768                                         _panelElement = new TextElementClass( data );
3769                                         _panelElement.init();
3770                                         TextEditor.boot( PANEL_CONTROL.x, PANEL_CONTROL.y, _panelElement, onTextInput );
3771                                 } else {
3772                                         _panelElement = new TextElementClass( data );
3773                                         _panelElement.init();
3774                                         onTextInput( _panelElement );
3775                                 }
3776                         }
3777                 }
3778         })();
3779
3780         /*
3781          * end of PANEL_ELEMENT_CONTROL
3782          */
3783
3784         function updateMouseCursor( _cursor ){
3785                 if( currentCursor !== _cursor ){
3786                         currentCursor = _cursor;
3787                         self.addAsyncCall( update );
3788                 };
3789                 function update(){
3790                         elmMouseEventChatcher.style.cursor = currentCursor;
3791                 };
3792         };
3793         function centering(){
3794                 self.onPaneResize( windowW, windowH );
3795         };
3796         function mouseEventRellay( e ){
3797                 var _mouseX = e.clientX,
3798                         _mouseY = e.clientY,
3799                         rellayMethod = e.type === 'mouseout' ? 'mouseup' : e.type;
3800                 if( currentListener !== null && currentListener.busy() === true ){
3801                         currentListener[ rellayMethod ]( _mouseX, _mouseY );
3802                 } else {
3803                         currentListener = null;
3804                         var l = MOUSE_LISTENER_ARRAY.length,
3805                                 _listener;
3806                         for( var i=0; i<l; ++i ){
3807                                 _listener = MOUSE_LISTENER_ARRAY[ i ];
3808                                 if( _listener[ rellayMethod ]( _mouseX, _mouseY ) === true ){
3809                                         currentListener = _listener;
3810                                         break;
3811                                 };
3812                         };
3813                 };
3814                 // 文字選択の禁止
3815                 //!document.selection && window.getSelection().removeAllRanges();
3816                 return false;
3817         };
3818
3819         /* grobal method */
3820         
3821         this.MIN_WIDTH   = 320;
3822         this.MIN_HEIGHT  = 320;
3823         this.onInit = function(){
3824                 app.rootElement.id = 'editor';
3825                 app.rootElement.innerHTML = [
3826                         '<div id="grid" style="display:none;"></div>',
3827                         '<div id="comic-element-container"></div>',
3828                         '<div id="whiteGlass-container">',
3829                                 '<div id="whiteGlass-top"></div>',
3830                                 '<div id="whiteGlass-left"></div>',
3831                                 '<div id="whiteGlass-right"></div>',
3832                                 '<div id="whiteGlass-bottom"></div>',
3833                         '</div>',
3834                         '<div id="panel-tools-container">',
3835                         '<div id="panel-resizer-top">▲</div>',
3836                                 '<div id="panel-resizer-bottom">▼</div>',
3837                                 '<div id="comic-element-resizer-container">',
3838                                         '<div class="comic-element-resizer" id="comic-element-resizer-top"></div>',
3839                                         '<div class="comic-element-resizer" id="comic-element-resizer-left"></div>',
3840                                         '<div class="comic-element-resizer" id="comic-element-resizer-right"></div>',
3841                                         '<div class="comic-element-resizer" id="comic-element-resizer-bottom"></div>',
3842                                         '<div class="comic-element-resizer" id="comic-element-resizer-top-left"></div>',
3843                                         '<div class="comic-element-resizer" id="comic-element-resizer-top-right"></div>',
3844                                         '<div class="comic-element-resizer" id="comic-element-resizer-bottom-left"></div>',
3845                                         '<div class="comic-element-resizer" id="comic-element-resizer-bottom-right"></div>',
3846                                         '<div id="balloon-tail-mover"></div>',
3847                                         '<div id="comic-element-consol-wrapper">',
3848                                                 '<div id="comic-element-consol-tail"></div>',
3849                                                 '<div id="comic-element-consol-wrapper-when-out">',
3850                                                         '<div id="image-element-consol">',
3851                                                                 '<div id="change-image-button"></div>',
3852                                                                 '<div id="layer-back-button"></div>',
3853                                                                 '<div id="delete-image-button"></div>',
3854                                                                 '<div id="layer-forward-button"></div>',
3855                                                         '</div>',
3856                                                         '<div id="text-element-consol">',
3857                                                                 '<div id="edit-text-button"></div>',
3858                                                                 '<div id="change-text-style-button"></div>',
3859                                                                 '<div id="back-text-button"></div>',
3860                                                                 '<div id="delete-text-button"></div>',
3861                                                                 '<div id="hide-text-tail-button"></div>',
3862                                                                 '<div id="forward-text-button"></div>',
3863                                                         '</div>',
3864                                                 '</div>',
3865                                         '</div>',
3866                                 '</div>',
3867                         '</div>',
3868                         '<div id="window-container"></div>',
3869                         '<div id="menu-bar"></div>',
3870                         '<div id="mouse-operation-catcher" unselectable="on"></div>',
3871                         
3872                         '<div id="templete-container" style="display: none;">',
3873                         
3874                                 '<div id="imgElementTemplete" class="comic-element-wrapper image-element"></div>',
3875                                 
3876                                 '<div id="textElementTemplete" class="comic-element-wrapper text-element">',
3877                                         '<img>',
3878                                         '<div class="speach">',
3879                                                 '<div class="speach-inner">&nbsp;</div>',
3880                                         '</div>',
3881                                 '</div>',
3882                                 
3883                                 '<div id="textElementTempleteForOldIE" class="comic-element-wrapper text-element">',
3884                                         '<img>',
3885                                         '<div class="speach">',
3886                                                 '<table><tr><td>&nbsp;</td></tr></table>',
3887                                         '</div>',
3888                                 '</div>',
3889                                 
3890                                 '<div id="imageGroupItemTemplete" class="image-group-item">',
3891                                         '<div class="image-group-item-title">img-title</div>',
3892                                 '</div>',
3893                                 
3894                                 '<div id="windowTemplete" class="window-wrapper">',
3895                                         '<div class="window-header">window title</div>',
3896                                         '<div class="window-close-button">x</div>',
3897                                         '<div class="window-body clearfix">',
3898                                                 '<div class="window-body-insert-position"></div>',
3899                                         '</div>',
3900                                         '<div class="window-footer">',
3901                                                 '<div class="window-resize-button">/</div>',
3902                                         '</div>',
3903                                 '</div>',
3904                                 
3905                                 '<div id="infomation-window">',
3906                                         '<div id="panel-background-information">',
3907                                                 '<div id="bg-pattern"></div>',
3908                                                 '<div id="select-bg-pattern-button">pattern</div>',
3909                                                 '<div id="reset-bg-pattern-button">x</div>',
3910                                                 '<div id="bg-color"></div>',
3911                                                 '<div id="select-bg-color-button">color</div>',
3912                                                 '<div id="reset-bg-color-button">x</div>',
3913                                                 '<!-- <div id="bg-pattern-x"></div>',
3914                                                 '<div id="bg-pattern-y"></div>',
3915                                                 '<div id="bg-pattern-repeat-x"></div>',
3916                                                 '<div id="bg-pattern-repeat-y"></div> -->',
3917                                         '</div>',
3918                                         
3919                                         '<div id="comic-element-infomation">',
3920                                                 '<div id="comic-element-x">',
3921                                                         '<span class="comic-element-attribute-label">x:</span>',
3922                                                         '<span id="comic-element-x-value" class="comic-element-attribute-value editable-value">0</span>',
3923                                                 '</div>',
3924                                                 '<div id="comic-element-y">',
3925                                                         '<span class="comic-element-attribute-label">y:</span>',
3926                                                         '<span id="comic-element-y-value" class="comic-element-attribute-value editable-value">0</span>',
3927                                                 '</div>',
3928                                                 '<div id="comic-element-z">',
3929                                                         '<span class="comic-element-attribute-label">z:</span>',
3930                                                         '<span id="comic-element-z-value" class="comic-element-attribute-value editable-value">0</span>',
3931                                                 '</div>',
3932                                                 '<div id="comic-element-a">',
3933                                                         '<span id="comic-element-a-value" class="comic-element-attribute-value editable-value">0</span>',
3934                                                         '<span class="comic-element-attribute-label">°</span>',
3935                                                 '</div>',
3936                                                 '<div id="comic-element-w">',
3937                                                         '<span class="comic-element-attribute-label">w:</span>',
3938                                                         '<span id="comic-element-w-value" class="comic-element-attribute-value editable-value">0</span>',
3939                                                 '</div>',
3940                                                 '<div id="comic-element-h">',
3941                                                         '<span class="comic-element-attribute-label">h:</span>',
3942                                                         '<span id="comic-element-h-value" class="comic-element-attribute-value editable-value">0</span>',
3943                                                 '</div>',
3944                                                 '<div id="comic-element-w-percent">',
3945                                                         '<span id="comic-element-w-percent-value" class="comic-element-attribute-value editable-value">0</span>',
3946                                                         '<span class="comic-element-attribute-label">%</span>',
3947                                                 '</div>',
3948                                                 '<div id="comic-element-h-percent">',
3949                                                         '<span id="comic-element-h-percent-value" class="comic-element-attribute-value editable-value">0</span>',
3950                                                         '<span class="comic-element-attribute-label">%</span>',
3951                                                 '</div>',
3952                                 '<div id="comic-element-keep-aspect"></div>',
3953                                         '</div>',
3954                                 '</div>',
3955                                 
3956                                 '<div id="toolbox-window">',
3957                                         '<div id="toolbox-add-image-button">add image</div>',
3958                                         '<div id="toolbox-add-text-button">add text</div>',
3959                                         '<div id="toolbox-edit-bg-button">edit bg</div>',
3960                                         '<div id="toolbox-switch-grid">grid</div>',
3961                                         '<div id="toolbox-popup-help-button">?</div>',
3962                                         '<div id="toolbox-post-button">post</div>',
3963                                 '</div>',
3964                                 
3965                                 '<div id="image-exproler"><div id="image-exproler-container"></div></div>',
3966                         
3967                         '</div>'
3968                 ].join( '' );
3969                 
3970                 app.fetchCSS( '/assets/peta.apps.css' );
3971                 
3972                 delete app.onInit;
3973         };
3974         this.onOpen = function( _w, _h, _file ){
3975                 elmMouseEventChatcher = document.getElementById( 'mouse-operation-catcher' );
3976                 
3977                 MENU_BAR_CONTROL.init();
3978                 HISTORY_CONTROL.init();
3979                 SAVE_CONTROL.init();
3980                 WINDOWS_CONTROL.init();
3981                 GRID_CONTROL.init();
3982                 WHITE_GLASS_CONTROL.init();
3983                 PANEL_CONTROL.init();
3984                 CONSOLE_CONTROLER.init();
3985                 PANEL_ELEMENT_OPERATION_MANAGER.init();
3986                 PANEL_ELEMENT_CONTROL.init();
3987                 
3988                 /*
3989                  * MOUSE_LISTENER_ARRAY は、表示順に格納.手前の要素が最初
3990                  * MENU_BAR_CONTROL,
3991                  * WINDOW_CONTROL,
3992                  * PANEL_ELEMENT_CONTROL,
3993                  * PANEL_CONTROL
3994                  * .busy() === true なら、そのままmousemove()にイベントを流す.
3995                  * mousemove()に流してみて、false が帰れば、次のリスナーにも流す.
3996                  */
3997                 MOUSE_LISTENER_ARRAY.push( MENU_BAR_CONTROL, WINDOWS_CONTROL, PANEL_RESIZER_TOP, PANEL_RESIZER_BOTTOM, PANEL_ELEMENT_CONTROL, PANEL_CONTROL );          
3998                 
3999                 comicID      = -1;
4000                 panelID      = -1;
4001                 panelTimming = -1;
4002                 phase        = 0;
4003                 
4004                 var panelW, panelH,
4005                         borderSize,
4006                         fileData, panelElements, panelElm;
4007
4008                 if( FileAPI.isFileInstance( _file ) === true ){
4009                         if( Driver.isPettanrFileInstance( _file ) === true ){
4010                                 if( _file.getType() === FILE_TYPE.COMIC ){
4011                                         fileData = _file.read();
4012                                         panelW   = fileData.width;
4013                                         panelH   = fileData.height;
4014                                         comicID  = fileData.id || -1;
4015                                 } else
4016                                 if( _file.getType() === FILE_TYPE.PANEL ){
4017                                         fileData      = _file.read();
4018                                         panelW        = fileData.width;
4019                                         panelH        = fileData.height;
4020                                         borderSize    = fileData.border;
4021                                         panelElements = fileData.panel_elements;
4022                                         comicID       = fileData.comic ? fileData.comic.id || -1 : -1;
4023                                         panelID       = fileData.id || -1;
4024                                         panelTimming  = fileData.t  || -1;
4025                                 };
4026                         } else {
4027                         };
4028                 } else {
4029                 };
4030                 
4031                 HISTORY_CONTROL.open();
4032                 SAVE_CONTROL.open();
4033                 WINDOWS_CONTROL.open();
4034                 
4035                 GRID_CONTROL.open();
4036                 PANEL_CONTROL.open( panelW, panelH, borderSize );
4037                 CONSOLE_CONTROLER.open();
4038                 PANEL_ELEMENT_OPERATION_MANAGER.open();
4039                 PANEL_ELEMENT_CONTROL.open();
4040                 
4041                 // last
4042                 MENU_BAR_CONTROL.open();
4043                 
4044                 windowW = _w;
4045                 windowH = _h;
4046                 self.onPaneResize( _w, _h );
4047                 
4048
4049                 if( Type.isArray( panelElements ) === true ){
4050                         for( var i=0; i<panelElements.length; ++i ){
4051                                 panelElm = panelElements[ i ];
4052                                 if( panelElm.resource_picture ){
4053                                         PANEL_ELEMENT_CONTROL.createImageElement( panelElm );
4054                                 } else
4055                                 if( panelElm.balloon_template_id ){
4056                                         PANEL_ELEMENT_CONTROL.createTextElement( panelElm );
4057                                 };
4058                         };
4059                 };
4060                 
4061         /*
4062          * centering
4063          */
4064                 self.addKeyEventListener( 'keydown', centering, 96, false, true );      // ctrl + 0
4065                 self.addKeyEventListener( 'krydown', centering, 48, false, true );      // ctrl + 0
4066                 MENU_BAR_CONTROL.EDIT.createOption( 'centering', 'ctrl + 0', centering, true, true, true);
4067         /*
4068          * jqMouseEventChacher は透明な要素で、
4069          * マウスイベントをcurrentElement(currentElement)に伝えるのが仕事
4070          * このような実装になるのは、ここの表示オブジェクトにイベントを設定した場合、表示が追いつかずマウスカーソルが外れたタイミングでイベントが終わってしまうため。
4071          */
4072                 self.addMouseEventListener( elmMouseEventChatcher, 'mousemove', mouseEventRellay );
4073                 self.addMouseEventListener( elmMouseEventChatcher, 'mousedown', mouseEventRellay );
4074                 self.addMouseEventListener( elmMouseEventChatcher, 'mouseup',   mouseEventRellay );
4075                 //self.addMouseEventListener( elmMouseEventChatcher, 'mouseout',  mouseEventRellay );
4076                 
4077                 phase   = 1;
4078                 
4079                 delete app.onOpen;
4080         };
4081         this.onClose = function(){
4082                 phase   = 2;
4083                 HISTORY_CONTROL.close();
4084                 
4085                 WINDOWS_CONTROL.close();
4086                 
4087                 GRID_CONTROL.close();
4088                 PANEL_CONTROL.close();
4089                 
4090                 PANEL_ELEMENT_OPERATION_MANAGER.close();
4091                 PANEL_ELEMENT_CONTROL.close();
4092                 
4093                 // last
4094                 MENU_BAR_CONTROL.close();
4095                 
4096                 phase = -1;
4097         };
4098         this.onPaneResize = function( _windowW, _windowH ){
4099                 windowW = _windowW || windowW;
4100                 windowH = _windowH || windowH;
4101                 /*
4102                  * ieは +'px'が不要みたい
4103                  */
4104                 self.rootElement.style.height = _windowH + 'px';
4105                 elmMouseEventChatcher.style.height = _windowH + 'px';
4106                 
4107                 WINDOWS_CONTROL.onWindowResize( _windowW, _windowH );
4108                 MENU_BAR_CONTROL.onWindowResize( _windowW, _windowH );
4109                 PANEL_CONTROL.onWindowResize( _windowW, _windowH );
4110         };
4111 }, false, true, 'Panel Editor', 'paneleditor', null, '#2D89F0' );
4112
4113
4114 var ComicConsole = gOS.registerApplication( function(){
4115         var elmHeader, elmProgress,
4116                 winW, winH,
4117                 inputTitle, inputW, inputH,
4118                 comboboxVisible, // comboboxEditable,
4119                 buttonSubmit, buttonCancel,
4120                 elmUploader = null,
4121                 elmScript   = null,
4122                 elmIframe   = null,
4123                 elmForm     = null,
4124                 isUploading = false,
4125                 instance    = this;
4126         //pettanr.key.addKeyDownEvent( ID, 69, false, false, clickOK);
4127         
4128         function clickOK(){
4129                 if( !elmForm || !elmIframe || isUploading === true ) return false;
4130                 // validate
4131                 isUploading = true;
4132                 elmProgress.innerHTML = '■';
4133                 copyAndSubmit();
4134         };
4135
4136                 function copyAndSubmit(){
4137                         var _inputList = elmForm.getElementsByTagName( 'input' ),
4138                                 _input, _name;
4139                         for( var i = _inputList.length; i; ){
4140                                 _input = _inputList[ --i ];
4141                                 _name = _input.name;
4142                                 if( _name === 'comic[title]'){
4143                                         _input.value = inputTitle.value();
4144                                 } else
4145                                 if( _name === 'comic[width]'){
4146                                         _input.value = inputW.value();
4147                                 } else
4148                                 if( _name === 'comic[height]'){
4149                                         _input.value = inputH.value();
4150                                 };
4151                         };
4152                         var _selectList = elmForm.getElementsByTagName( 'select' ),
4153                                 _select, _optionList;
4154                         for( i = _selectList.length; i; ){
4155                                 _select = _selectList[ --i ];
4156                                 _name = _select.name;
4157                                 _optionList = _select.getElementsByTagName( 'option' )
4158                                 if( _name === 'comic[visible]'){
4159                                         _select.selectedIndex = comboboxVisible.selectIndex();
4160                                 } else
4161                                 if( _name === 'comic[editable]'){
4162                                         // _select.selectedIndex = comboboxEditable.selectIndex();
4163                                 };
4164                         };
4165                         try {
4166                                 elmForm.submit();
4167                         } catch( e ){
4168                                 elmProgress.innerHTML = 'submit() err..';
4169                                 isUploading = false;
4170                                 instance.addTimer( clickCancel , 3000, true );
4171                                 return;
4172                         };
4173                         if( UA.isIE ){
4174                                 elmIframe.onreadystatechange = detectIframe;
4175                         } else {
4176                                 elmIframe.onload = onIframeUpdate;
4177                         };
4178                         elmProgress.innerHTML = 'uploading..';
4179                 };
4180         /*
4181          * ie の 場合、readyState をチェック.
4182          */
4183                         function detectIframe(){
4184                     if ( elmIframe.readyState === 'complete' ){
4185                         elmIframe.onreadystatechange = new Function();
4186                         elmIframe.onreadystatechange = null;
4187                         onIframeUpdate();
4188                     };
4189                         };
4190                                 function onIframeUpdate(){
4191                                         elmIframe.onload = null;
4192                                         try {
4193                                                 console.log( ( elmIframe.contentWindow || elmIframe.contentDocument.parentWindow ).document.body.innerHTML );
4194                                         } catch(e){
4195                                                 
4196                                         }
4197                                         
4198                                         ( elmIframe.contentWindow || elmIframe.contentDocument.parentWindow ).close();
4199                                         elmIframe = null;
4200                                         elmProgress.innerHTML = 'success!';
4201                                         instance.addTimer( clickCancel , 1000 );
4202                                         isUploading = false;
4203                                 };
4204                         
4205         function clickCancel(){
4206                 if( isUploading === true ) return false;
4207                 ComicConsole.shutdown();
4208         };
4209         function detectForm(){
4210                 elmForm = elmUploader.getElementsByTagName( 'form' )[ 0 ];
4211                 if( elmForm ){
4212                         var selectList = elmForm.getElementsByTagName( 'select' ),
4213                                 select,
4214                                 j, m,
4215                                 optionList, option;
4216                         for( var i=0, l=selectList.length; i<l; ++i ){
4217                                 select = selectList[ i ];
4218                                 optionList = select.getElementsByTagName( 'option' );
4219                                 for( j=0, m=optionList.length; j<m; ++j ){
4220                                         option = optionList[ j ];
4221                                         if( select.name === 'comic[visible]' ){
4222                                                 comboboxVisible.createOption( option.innerHTML, option.value, option.selected );
4223                                         } else
4224                                         if( select.name === 'comic[editable]' ){
4225                                                 // comboboxEditable.createOption( option.innerHTML, option.value, option.selected );
4226                                         };
4227                                 };
4228                         };
4229                         
4230                         instance.removeTimer( detectForm );
4231                         Util.createIframe( 'targetFrameCreateComic', onCreateIframe );
4232                         elmProgress.innerHTML = 'create iframe';
4233                         
4234                         instance.onPaneResize( winW, winH );
4235                         inputTitle.focus();
4236                 };
4237         };
4238         function onCreateIframe( _iframe ){
4239                 elmUploader.appendChild( _iframe );
4240                 elmIframe             = _iframe;
4241                 elmForm.target        = _iframe.name;
4242                 elmProgress.innerHTML = '';
4243         };
4244
4245         /* grobal method */
4246         this.MIN_WIDTH   = 320;
4247         this.MIN_HEIGHT  = 320;
4248         this.onInit = function(){
4249                 instance.rootElement.id = 'comic-console-wrapper';
4250                 instance.rootElement.className = 'console-wrapper';
4251                 instance.rootElement.innerHTML = [
4252                         '<div id="comic-console-header" class="console-header">Create New Comic</div>',
4253                         '<div id="comic-console" class="console-inner">',
4254                                 '<div id="comic-console-title" class="field">',
4255                                         '<span class="field-label">Title:</span>',
4256                                         '<span id="comic-console-title-value" class="comic-console-value editable-value">No Title</span>',
4257                                 '</div>',
4258                                 '<div id="comic-console-width" class="field">',
4259                                         '<span class="field-label">Default Width:</span>',
4260                                         '<span id="comic-console-width-value" class="comic-console-value editable-value">300</span>',
4261                                 '</div>',
4262                                 '<div id="comic-console-height" class="field">',
4263                                         '<span class="field-label">Default Height:</span>',
4264                                         '<span id="comic-console-height-value" class="comic-console-value editable-value">200</span>',
4265                                 '</div>',
4266                                 '<div id="comic-console-visible" class="field">',
4267                                         '<span class="field-label">Visible:</span>',
4268                                         '<span id="comic-console-visible-value" class="comic-console-value combobox"></span>',
4269                                 '</div>',
4270                                 //'<div id="comic-console-editable" class="field">',
4271                                 //      '<span class="field-label">Editable:</span>',
4272                                 //      '<span id="comic-console-editable-value" class="comic-console-value combobox"></span>',
4273                                 //'</div>',
4274                                 '<div class="console-button-container">',
4275                                         '<div id="comic-console-post-button" class="button console-submit-button">create</div>',
4276                                         '<div id="comic-console-cancel-button" class="button console-cancel-button">cancel</div>',
4277                                 '</div>',
4278                                 '<div id="comic-console-progress" class="console-progress">&nbsp;</div>',
4279                         '</div>'
4280                 ].join( '' );
4281                 
4282                 instance.fetchCSS( '/assets/peta.apps.css' );
4283                 
4284                 delete instance.onInit;
4285         };
4286         this.onOpen = function( w, h ){
4287                 var ui           = instance.createUIGroup();
4288                 
4289                 inputTitle       = ui.createInputText( document.getElementById( 'comic-console-title') );
4290                 inputW           = ui.createInputText( document.getElementById( 'comic-console-width') );
4291                 inputH           = ui.createInputText( document.getElementById( 'comic-console-height') );
4292                 comboboxVisible  = ui.createCombobox( document.getElementById( 'comic-console-visible') );
4293                 // comboboxEditable = ui.createCombobox( document.getElementById( 'comic-console-editable') );
4294                 buttonSubmit     = ui.createButton( document.getElementById( 'comic-console-post-button'), clickOK );
4295                 buttonCancel     = ui.createButton( document.getElementById( 'comic-console-cancel-button'), clickCancel );
4296                 
4297                 elmHeader        = document.getElementById( 'comic-console-header' );
4298                 elmProgress      = document.getElementById( 'comic-console-progress' );
4299                 
4300                 elmUploader      = document.createElement( 'div' );
4301                 instance.rootElement.appendChild( elmUploader );
4302                 elmUploader.id   = 'newcomic';
4303                 elmUploader.style.cssText = 'height:1px;line-height:1px;visibility:hidden;overflow:hidden;';
4304                 
4305                 elmScript        = document.createElement( 'script' );
4306                 document.body.appendChild( elmScript );
4307                 elmScript.type   = 'text\/javascript';
4308                 elmScript.src    = pettanr.CONST.CREATE_COMIC_JS;
4309                 
4310                 elmProgress.innerHTML = 'loading form.';
4311                 
4312                 instance.addTimer( detectForm, 250 );
4313                 instance.onPaneResize( w, h );
4314                 
4315                 delete instance.onOpen;
4316         };
4317         this.onPaneResize = function( _w, _h ){
4318                 winW = _w;
4319                 winH = _h;
4320                 instance.rootElement.style.cssText = [
4321                         'left:', Math.floor( ( _w - instance.rootElement.offsetWidth  ) /2 ), 'px;',
4322                         'top:',  Math.floor( ( _h- instance.rootElement.offsetHeight ) /2 ), 'px;'
4323                 ].join( '' );
4324         };
4325         this.onClose = function(){
4326                 elmHeader = elmProgress = elmForm  = elmUploader = instance = null;
4327                 isUploading = false;
4328         };
4329 }, true, true, 'Comic Console', 'comicConsole', null, '#D44A26' );
4330
4331 var UploadConsole = gOS.registerApplication( function(){
4332         var windowW, windowH,
4333                 TARGET_FRAME_NAME = 'targetFrame',
4334                 elmContainer,
4335                 elmProgress,
4336                 elmScript   = null,
4337                 elmForm     = null,
4338                 elmFile     = null,
4339                 elmIframe   = null,
4340                 isUploading = false,
4341                 instance    = this;
4342         /*
4343          * upload ボタンが押されたらまず iframe をつくる.
4344          */
4345         function clickOK(){
4346                 if( !elmForm || !elmIframe || isUploading === true ) return false;
4347                 if( elmFile.value.length === 0 ) return false;
4348                 elmProgress.innerHTML = 'uploading.';
4349                 isUploading = true;
4350                 submit();
4351                 return false;
4352         };
4353         /*
4354          * form の target に iframe を指定したのち submit();
4355          */
4356                 function submit(){
4357                         try {
4358                                 elmForm.submit();
4359                         } catch( e){
4360                                 elmProgress.innerHTML = 'submit() err..';
4361                                 isUploading = false;
4362                                 instance.addTimer( clickCancel , 3000, true );
4363                                 return;
4364                         };
4365                         
4366                         if( UA.isIE){
4367                                 elmIframe.onreadystatechange = detectIframe;
4368                         } else {
4369                                 elmIframe.onload = onLoad;
4370                         };
4371                         elmProgress.innerHTML = 'uploading..';
4372                 };
4373         /*
4374          * ie の 場合、readyState をチェック.
4375          */
4376                         function detectIframe(){
4377                     if ( elmIframe.readyState === 'complete') {
4378                         elmIframe.onreadystatechange = new Function();
4379                         elmIframe.onreadystatechange = null;
4380                         onLoad();
4381                     };
4382                         };
4383                                 function onLoad(){
4384                                         elmIframe.onload = null;
4385                                         ( elmIframe.contentWindow || elmIframe.contentDocument.parentWindow ).close();
4386                                         elmProgress.innerHTML = 'success!';
4387                                         instance.addTimer( clickCancel , 1000 );
4388                                         isUploading = false;
4389                                 };
4390         
4391         function detectForm(){
4392                 elmForm = elmContainer.getElementsByTagName( 'form' )[ 0 ];
4393                 if( elmForm ){
4394                         var _inputList = elmForm.getElementsByTagName( 'input' ),
4395                                 _input;
4396                         for( var i = _inputList.length; i; ){
4397                                 _input = _inputList[ --i ];
4398                                 if( _input.type === 'file' ){
4399                                         elmFile = _input;
4400                                 };
4401                                 if( _input.type === 'submit' ){
4402                                         _input.style.display = 'none';
4403                                 };
4404                         };
4405                         instance.removeTimer( detectForm );
4406                         Util.createIframe( TARGET_FRAME_NAME, onCreateIframe );
4407                         elmProgress.innerHTML = 'create iframe';
4408                 };
4409         };
4410         function onCreateIframe( _iframe ){
4411                 elmContainer.appendChild( _iframe );
4412                 elmIframe = _iframe;
4413                 elmForm.target = _iframe.name;
4414                 elmProgress.innerHTML = '';
4415                 instance.onPaneResize( windowW, windowH );
4416         };
4417         function clickCancel(){
4418                 if( isUploading === true ) return false;
4419                 UploadConsole.shutdown();
4420                 return false;
4421         };
4422
4423         /* grobal method */
4424         this.MIN_WIDTH   = 320;
4425         this.MIN_HEIGHT  = 320;
4426         this.onInit = function(){
4427                 instance.rootElement.id = 'upload-console-wrapper';
4428                 instance.rootElement.className = 'console-wrapper';
4429                 instance.rootElement.innerHTML = [
4430                         '<div id="upload-console-header" class="console-header">Upload Picture</div>',
4431                         '<div id="upload-console" class="console-inner">',
4432                                 '<div id="uploader"></div>',
4433                                 '<div class="console-button-container">',
4434                                         '<div id="upload-console-post-button" class="button console-submit-button">upload</div>',
4435                                         '<div id="upload-console-cancel-button" class="button console-cancel-button">cancel</div>',
4436                                 '</div>',
4437                                 '<div id="upload-console-progress" class="console-progress">&nbsp;</div>',
4438                         '</div>'
4439                 ].join( '' );
4440                 
4441                 instance.fetchCSS( '/assets/peta.apps.css' );
4442                 
4443                 delete instance.onInit;
4444         }
4445         this.onOpen = function( w, h ){
4446                 elmContainer = document.getElementById( 'uploader' );
4447                 elmProgress  = document.getElementById( 'upload-console-progress' );
4448                 
4449                 instance.addMouseEventListener( document.getElementById( 'upload-console-post-button' ), 'click', clickOK );
4450                 instance.addMouseEventListener( document.getElementById( 'upload-console-cancel-button' ), 'click', clickCancel );
4451                 /*
4452                  * ie 6, 7 で fadeIn 中の要素に appendChild すると クラッシュするので、document.body に追加.
4453                  */                             
4454                 elmScript      = document.createElement( 'script' );
4455                 document.body.appendChild( elmScript );
4456                 elmScript.type = 'text\/javascript';
4457                 elmScript.src  = pettanr.CONST.UPLOAD_PICTURE_JS;
4458
4459                 instance.addTimer( detectForm, 250 );
4460                 instance.onPaneResize( w, h );
4461                 
4462                 elmProgress.innerHTML = 'loading form.';
4463         };
4464         this.onPaneResize = function( _windowW, _windowH){
4465                 windowW = _windowW;
4466                 windowH = _windowH;
4467                 instance.rootElement.style.cssText = [
4468                         'left:', Math.floor( ( _windowW - instance.rootElement.offsetWidth  ) /2 ), 'px;',
4469                         'top:',  Math.floor( ( _windowH - instance.rootElement.offsetHeight ) /2 ), 'px;'
4470                 ].join( '' );
4471         }
4472         this.onClose = function(){
4473                 elmHeader = elmProgress = elmForm  = elmUploader = instance = null;
4474                 isUploading = false;
4475         }
4476 }, true, true, 'Upload Console', 'uploadConsole', null, '#01A31C' );
4477
4478 var PanelConsole = gOS.registerApplication( function(){
4479         var windowW, windowH,
4480                 TARGET_FRAME_NAME = 'targetFrameCreateNewPanel',
4481                 elmContainer, elmProgress,
4482                 elmScript = null,
4483                 elmForm = null,
4484                 elmIframe = null,
4485                 isUploading = false,
4486                 instance = this;
4487         /*
4488          * upload ボタンが押されたらまず iframe をつくる.
4489          */
4490         function clickOK(){
4491                 if( !elmForm || !elmIframe || isUploading === true ) return false;
4492                 elmProgress.innerHTML = 'uploading.';
4493                 isUploading = true;
4494                 submit();
4495                 return false;
4496         }
4497         /*
4498          * form の target に iframe を指定したのち submit();
4499          */
4500                 function submit(){
4501                         try {
4502                                 elmForm.submit();
4503                         } catch( e ){
4504                                 elmProgress.innerHTML = 'submit() err..';
4505                                 isUploading = false;
4506                                 instance.addTimer( clickCancel , 3000, true );
4507                                 return;
4508                         }
4509                         
4510                         if( UA.isIE ){
4511                                 elmIframe.onreadystatechange = detectIframe;
4512                         } else {
4513                                 elmIframe.onload = onLoad;
4514                         }
4515                         elmProgress.innerHTML = 'uploading..';
4516                 }
4517         /*
4518          * ie の 場合、readyState をチェック.
4519          */
4520                         function detectIframe(){
4521                     if ( elmIframe.readyState === 'complete' ){
4522                         elmIframe.onreadystatechange = new Function();
4523                         elmIframe.onreadystatechange = null;
4524                         onLoad();
4525                     };
4526                         };
4527                                 function onLoad(){
4528                                         try {
4529                                                 console.log( ( elmIframe.contentWindow || elmIframe.contentDocument.parentWindow ).document.body.innerHTML );
4530                                         } catch(e){
4531                                                 
4532                                         }
4533                                         elmIframe.onload = null;
4534                                         ( elmIframe.contentWindow || elmIframe.contentDocument.parentWindow ).close();
4535                                         elmProgress.innerHTML = 'success!';
4536                                         instance.addTimer( clickCancel , 1000, true );
4537                                         isUploading = false;
4538                                 };
4539         
4540         function detectForm(){
4541                 elmForm = elmContainer.getElementsByTagName( 'form' )[ 0 ];
4542                 if( elmForm){
4543                         var _inputList = elmForm.getElementsByTagName( 'input' ),
4544                                 _input;
4545                         for( var i = _inputList.length; i; ){
4546                                 _input = _inputList[ --i ];
4547                                 if( _input.type === 'submit' ){
4548                                         _input.style.display = 'none';
4549                                 };
4550                         };
4551                         instance.removeTimer( detectForm );
4552                         Util.createIframe( TARGET_FRAME_NAME, onCreateIframe );
4553                         elmProgress.innerHTML = 'create iframe';
4554                 };
4555         };
4556         function onCreateIframe( _iframe ){
4557                 elmContainer.appendChild( _iframe );
4558                 elmIframe = _iframe;
4559                 elmForm.target = _iframe.name;
4560                 elmProgress.innerHTML = '';
4561                 instance.onPaneResize( windowW, windowH );
4562         };
4563         function clickCancel(){
4564                 if( isUploading === true) return false;
4565                 PanelConsole.shutdown();
4566                 return false;
4567         };
4568
4569         /* grobal method */
4570         this.MIN_WIDTH   = 320;
4571         this.MIN_HEIGHT  = 320;
4572         this.onInit = function(){
4573                 instance.rootElement.id = 'panel-console-wrapper';
4574                 instance.rootElement.className = 'console-wrapper';
4575                 instance.rootElement.innerHTML = [
4576                         '<div id="panel-console-header" class="console-header">Create New Panel (dev)</div>',
4577                         '<div id="panel-console" class="console-inner">',
4578                                 '<div id="newpanel"></div>',
4579                                 '<div class="console-button-container">',
4580                                         '<div id="panel-console-post-button" class="button console-submit-button">post</div>',
4581                                         '<div id="panel-console-cancel-button" class="button console-cancel-button">cancel</div>',
4582                                 '</div>',
4583                                 '<div id="panel-console-progress" class="console-progress">&nbsp;</div>',
4584                         '</div>'
4585                 ].join( '' );
4586
4587                 instance.fetchCSS( '/assets/peta.apps.css' );
4588
4589                 delete instance.onInit;
4590         }
4591         this.onOpen = function( w, h ){
4592                 elmContainer = document.getElementById( 'newpanel' );
4593                 elmProgress  = document.getElementById( 'panel-console-progress' );
4594                 
4595                 instance.addMouseEventListener( document.getElementById( 'panel-console-post-button' ), 'click', clickOK );
4596                 instance.addMouseEventListener( document.getElementById( 'panel-console-cancel-button' ), 'click', clickCancel );
4597                 /*
4598                  * ie 6, 7 で fadeIn 中の要素に appendChild すると クラッシュするので、document.body に追加.
4599                  */                             
4600                 elmScript = document.createElement( 'script' );
4601                 document.body.appendChild( elmScript );
4602                 elmScript.type = 'text\/javascript';
4603                 elmScript.src  = pettanr.CONST.CREATE_PANEL_JS;
4604
4605                 instance.addTimer( detectForm, 250 );
4606                 instance.onPaneResize( w, h );
4607                 
4608                 elmProgress.innerHTML = 'loading form.';
4609         };
4610         this.onPaneResize = function( _windowW, _windowH ){
4611                 windowW = _windowW;
4612                 windowH = _windowH;
4613                 instance.rootElement.style.cssText = [
4614                         'left:', Math.floor( ( _windowW - instance.rootElement.offsetWidth  ) /2 ), 'px;',
4615                         'top:',  Math.floor( ( _windowH - instance.rootElement.offsetHeight ) /2 ), 'px;'
4616                 ].join( '' );
4617         };
4618         this.onClose = function(){
4619                 elmHeader = elmProgress = elmForm  = elmUploader = instance = null;
4620                 isUploading = false;
4621         };
4622 }, true, true, 'Panel Console', 'panelConsole', null, '#603CBA' );
4623
4624 var ArtistConsole = gOS.registerApplication( function(){
4625         var windowW, windowH,
4626                 TARGET_FRAME_NAME = 'targetFrameRegisterArtist',
4627                 elmContainer, elmProgress,
4628                 elmScript   = null,
4629                 elmForm     = null,
4630                 elmIframe   = null,
4631                 isUploading = false,
4632                 instance    = this;
4633         /*
4634          * upload ボタンが押されたらまず iframe をつくる.
4635          */
4636         function clickOK(){
4637                 if( !elmForm || !elmIframe || isUploading === true ) return false;
4638                 elmProgress.innerHTML = 'uploading.';
4639                 isUploading = true;
4640                 submit();
4641                 return false;
4642         }
4643         /*
4644          * form の target に iframe を指定したのち submit();
4645          */
4646                 function submit(){
4647                         try {
4648                                 elmForm.submit();
4649                         } catch( e){
4650                                 elmProgress.innerHTML = 'submit() err..';
4651                                 isUploading = false;
4652                                 instance.addTimer( clickCancel , 3000, true );
4653                                 return;
4654                         }
4655                         
4656                         if( UA.isIE){
4657                                 elmIframe.onreadystatechange = detectIframe;
4658                         } else {
4659                                 elmIframe.onload = onLoad;
4660                         }
4661                         elmProgress.innerHTML = 'uploading..';
4662                 }
4663         /*
4664          * ie の 場合、readyState をチェック.
4665          */
4666                         function detectIframe(){
4667                     if ( elmIframe.readyState === 'complete' ){
4668                         elmIframe.onreadystatechange = new Function();
4669                         elmIframe.onreadystatechange = null;
4670                         onLoad();
4671                     }
4672                         }
4673                                 function onLoad(){
4674                                         elmIframe.onload = null;
4675                                         ( elmIframe.contentWindow || elmIframe.contentDocument.parentWindow ).close();
4676                                         elmProgress.innerHTML = 'success!';
4677                                         instance.addTimer( clickCancel , 1000, true );
4678                                         isUploading = false;
4679                                 }
4680         
4681         function detectForm(){
4682                 elmForm = elmContainer.getElementsByTagName( 'form' )[ 0 ];
4683                 if( elmForm){
4684                         var _inputList = elmForm.getElementsByTagName( 'input' ),
4685                                 _input;
4686                         for( var i = _inputList.length; i; ){
4687                                 _input = _inputList[ --i ];
4688                                 if( _input.type === 'submit' ){
4689                                         _input.style.display = 'none';
4690                                 }
4691                         }
4692                         instance.removeTimer( detectForm );
4693                         Util.createIframe( TARGET_FRAME_NAME, onCreateIframe);
4694                         elmProgress.innerHTML = 'create iframe';
4695                 }
4696         }
4697         function onCreateIframe( _iframe ){
4698                 elmContainer.appendChild( _iframe );
4699                 elmIframe = _iframe;
4700                 elmForm.target = _iframe.name;
4701                 elmProgress.innerHTML = '';
4702                 instance.onPaneResize( windowW, windowH );
4703         }
4704         function clickCancel(){
4705                 if( isUploading === true) return false;
4706                 ArtistConsole.shutdown();
4707                 return false;
4708         }
4709
4710         /* grobal method */
4711         this.MIN_WIDTH   = 320;
4712         this.MIN_HEIGHT  = 320;
4713         this.onInit = function(){
4714                 instance.rootElement.id = 'artist-console-wrapper';
4715                 instance.rootElement.className = 'console-wrapper';
4716                 instance.rootElement.innerHTML = [
4717                         '<div id="artist-console-header" class="console-header">Register Artist</div>',
4718                         '<div id="artist-console" class="console-inner">',
4719                                 '<div id="register"></div>',
4720                                 '<div class="console-button-container">',
4721                                         '<div id="artist-console-post-button" class="button console-submit-button">register</div>',
4722                                         '<div id="artist-console-cancel-button" class="button console-cancel-button">cancel</div>',
4723                                 '</div>',
4724                                 '<div id="artist-console-progress" class="console-progress">&nbsp;</div>',
4725                         '</div>'
4726                 ].join( '' );
4727                 
4728                 instance.fetchCSS( '/assets/peta.apps.css' );
4729                 
4730                 delete instance.onInit;
4731         };
4732         this.onOpen = function( w, h ){
4733                 elmContainer = document.getElementById( 'register');
4734                 elmProgress  = document.getElementById( 'artist-console-progress');
4735                 
4736                 instance.addMouseEventListener( document.getElementById( 'artist-console-post-button' ), 'click', clickOK );
4737                 instance.addMouseEventListener( document.getElementById( 'artist-console-cancel-button' ), 'click', clickCancel );
4738                 /*
4739                  * ie 6, 7 で fadeIn 中の要素に appendChild すると クラッシュするので、document.body に追加.
4740                  */                             
4741                 elmScript = document.createElement( 'script' );
4742                 document.body.appendChild( elmScript );
4743                 elmScript.type = 'text\/javascript';
4744                 elmScript.src = pettanr.CONST.REGISTER_ARTIST_JS;
4745
4746                 instance.addTimer( detectForm, 250 );
4747                 instance.onPaneResize( w, h );
4748                 
4749                 elmProgress.innerHTML = 'loading form.';
4750         };
4751         this.onPaneResize = function( _windowW, _windowH ){
4752                 windowW = _windowW;
4753                 windowH = _windowH;
4754                 instance.rootElement.style.cssText = [
4755                         'left:', Math.floor( ( _windowW - instance.rootElement.offsetWidth  ) /2 ), 'px;',
4756                         'top:',  Math.floor( ( _windowH - instance.rootElement.offsetHeight ) /2 ), 'px;'
4757                 ].join( '' );
4758         };
4759         this.onClose = function(){
4760                 elmHeader = elmProgress = elmForm  = elmUploader = instance = null;
4761                 isUploading = false;
4762         };
4763 }, true, true, 'Artist Console', 'artistConsole', null, '#FFC40D' );
4764
4765 var OutputConsole = gOS.registerApplication( function(){
4766         var FORMAT_LIST = [ 'json[POST]', 'json[GET]', 'XML', 'HTML', 'XHTML', 'MT export', 'Blogger ATOM' ];
4767         var elmOutputArea,
4768                 comboboxFormat, inputOption,
4769                 buttonGenerate, buttonClose,
4770                 windowW, windowH,
4771                 timing = 0,
4772                 comicID, panelID, panelTimming, panelW, panelH, borderSize, panelElementArray,
4773                 instance = this;
4774         //pettanr.key.addKeyDownEvent( ID, 69, false, false, clickOK);
4775         
4776         function clickOK(){
4777                 OutputConsole.shutdown();
4778         };
4779
4780         function getPanelElementByTiming(){
4781                 var i, l = panelElementArray.length;
4782                 while( timing < l * 2){
4783                         for( i=0; i<l; ++i ){
4784                                 if( timing === panelElementArray[ i ].timing ){
4785                                         ++timing;
4786                                         return panelElementArray[ i ];
4787                                 }
4788                         }
4789                         ++timing;
4790                 }
4791                 return null;
4792         };
4793
4794         function getAsHtmlString( isAbsoluteUrl, isXHTML ){
4795                 timing = 0;
4796                 
4797                 var HTML_ARRAY = [],
4798                         l = panelElementArray.length,
4799                         _panelElement;
4800
4801                 while( HTML_ARRAY.length < l ){
4802                         _panelElement = getPanelElementByTiming();
4803                         if( _panelElement === null) break;
4804                         HTML_ARRAY.push( panelElementToHtml( _panelElement, isAbsoluteUrl, isXHTML ));
4805                 };
4806
4807                 HTML_ARRAY.unshift(
4808                         [
4809                                 '<div class="panel" ',
4810                                         'style="',
4811                                                 'height:', panelH, 'px;',
4812                                                 'background-color:', ';',
4813                                         '"',
4814                                 '>'
4815                         ].join( '')
4816                 );              
4817                 HTML_ARRAY.push( '</div>');
4818                 
4819                 return HTML_ARRAY.join( pettanr.LINE_FEED_CODE_TEXTAREA);
4820         };
4821
4822                 function panelElementToHtml( _panelElement, isAbsoluteUrl, isXHTML ){
4823                         var url;
4824                         if( _panelElement.type === 0 ){
4825                                 url = [ pettanr.CONST.RESOURCE_PICTURE_PATH, _panelElement.resourcePicture().id, '.', _panelElement.resourcePicture().ext ].join( '' );
4826                                 return [
4827                                         '<img ',
4828                                                 'src="',        isAbsoluteUrl !== true ? url : Util.getAbsolutePath( url ), '" ',
4829                                                 'width="',      _panelElement.w, '" ',
4830                                                 'height="',     _panelElement.h, '" ',
4831                                                 'style="',
4832                                                         'left:',    _panelElement.x, 'px;',
4833                                                         'top:',     _panelElement.y, 'px;',
4834                                                         'z-index:', _panelElement.z, ';',
4835                                                 '"',
4836                                         isXHTML !== true ? '>' : ' \/>'
4837                                 ].join( '');                            
4838                         } else {
4839                                 url = pettanr.balloon.getBalloonUrl( _panelElement.w, _panelElement.h, _panelElement.angle() );
4840                                 return [
4841                                         '<img ',
4842                                                 'src="',        isAbsoluteUrl !== true ? url : Util.getAbsolutePath( url ), '" ',
4843                                                 'width="',      _panelElement.w, '" ',
4844                                                 'height="',     _panelElement.h, '" ',
4845                                                 'style="',                                                                      
4846                                                         'left:',    _panelElement.x, 'px;',
4847                                                         'top:',     _panelElement.y, 'px;',
4848                                                         'z-index:', _panelElement.z, ';',
4849                                                 '"',
4850                                         isXHTML !== true ? '>' : ' \/>',
4851                                         pettanr.LINE_FEED_CODE_TEXTAREA,
4852                                         '<div class="balloon" style="',
4853                                                 'left:',        _panelElement.x, 'px;',
4854                                                 'top:',         _panelElement.y, 'px;',
4855                                                 'width:',       _panelElement.w, 'px;',
4856                                                 'height:',      _panelElement.h, 'px;',
4857                                                 'z-index:',     _panelElement.z,
4858                                         '"><span>', _panelElement.text(), '<\/span>', '<\/div>'
4859                                                 
4860                                 ].join( '');                            
4861                         };
4862                 };
4863         
4864         function getJsonGetString(){
4865                 timing = 0;
4866                 
4867                 var JSON_STRING_ARRAY = [],
4868                         ELEMENT_ARRAY     = [],
4869                         l                 = panelElementArray.length,
4870                         cr                = pettanr.LINE_FEED_CODE_TEXTAREA,
4871                         _panelElement;
4872
4873                 while( ELEMENT_ARRAY.length <= l){
4874                         _panelElement = getPanelElementByTiming();
4875                         if( _panelElement === null ) break;
4876                          
4877                         ELEMENT_ARRAY.push( _panelElement.type === 0 ? getImageJsonGET( _panelElement ) : balloonToJson( _panelElement ));
4878                 };
4879                 return [
4880                         '{', cr,
4881                                 '"panel": {', cr,
4882                                         '"id": ',               panelID, ',', cr,
4883                                     '"border": ',           borderSize, ',', cr,
4884                                     '"comic_id": ',         comicID, ',', cr,
4885                                     '"resource_picture_id": 1,', cr,
4886                                         '"x": ',                0, ',', cr,
4887                                         '"y": ',                0, ',', cr,
4888                                         '"z": ',                0, ',', cr,
4889                                         panelTimming !== -1 ? ( '"t": ' + panelTimming + ',' + cr ) : '',
4890                                     '"width": ',            panelW, ',', cr,
4891                                     '"height": ',           panelH, ',', cr,
4892                                     '"panel_elements": [', cr,
4893                                         ELEMENT_ARRAY.join( ',' + cr ), cr,
4894                                     ']', cr,
4895                                 '}', cr,
4896                         '}'
4897                 ].join( '' );
4898         };
4899                 function getImageJsonGET( _imageElement ){
4900                         var cr = pettanr.LINE_FEED_CODE_TEXTAREA;
4901                         return [
4902                                 '{', cr,
4903                                         '"resource_picture": {', cr,
4904                                                 '"id": ',              _imageElement.resourcePicture().id, ',', cr,
4905                                                 '"ext": ',             '"',_imageElement.resourcePicture().ext, '"', cr,
4906                                         '},', cr,
4907                                         '"x": ',                   _imageElement.x, ',', cr,
4908                                         '"y": ',                   _imageElement.y, ',', cr,
4909                                         '"z": ',                   _imageElement.z, ',', cr,
4910                                         '"width": ',               _imageElement.flipH() * _imageElement.w, ',', cr,
4911                                         '"height": ',              _imageElement.flipV() * _imageElement.h, ',', cr,
4912                                         '"t": ',                   timing, cr,
4913                                 '}'
4914                         ].join( '');
4915                 };
4916         
4917         function getJsonPostString(){
4918                 timing = 0;
4919                 
4920                 var JSON_STRING_ARRAY = [],
4921                         IMAGE_ARRAY = [],
4922                         BALLOON_ARRAY = [],
4923                         l = panelElementArray.length,
4924                         _panelElement,
4925                         cr = pettanr.LINE_FEED_CODE_TEXTAREA;
4926
4927                 while( IMAGE_ARRAY.length + BALLOON_ARRAY.length <= l){
4928                         _panelElement = getPanelElementByTiming();
4929                         if( _panelElement === null) break;
4930                         _panelElement.type === 0 ? 
4931                                 IMAGE_ARRAY.push( [ '"new', timing, '": ', imageToJson( _panelElement ) ].join( '' )) :
4932                                 BALLOON_ARRAY.push( [ '"new', timing, '": ', balloonToJson( _panelElement ) ].join( '' ) );
4933                 };
4934                 return [
4935                         '{', cr,
4936                                 '"panel": {', cr,
4937                                         '"id": ',               panelID, ',', cr,
4938                                     '"border": ',           borderSize, ',', cr,
4939                                     '"comic_id": ',         comicID, ',', cr,
4940                                     '"resource_picture_id": 1,', cr,
4941                                         '"x": ',                0, ',', cr,
4942                                         '"y": ',                0, ',', cr,
4943                                         '"z": ',                0, ',', cr,
4944                                         '"t": ',                                panelTimming, ',', cr,
4945                                     '"width": ',            panelW, ',', cr,
4946                                     '"height": ',           panelH, ',', cr,
4947                                     '"panel_pictures_attributes": {', cr,
4948                                         IMAGE_ARRAY.join( ',' + cr ), cr,
4949                                     '},', cr,
4950                                     '"balloons_attributes": {', cr,
4951                                         BALLOON_ARRAY.join( ',' + cr ), cr,
4952                                     '}', cr,
4953                                 '}', cr,
4954                         '}'
4955                 ].join( '' );
4956         };
4957                 function imageToJson( _imageElement ){
4958                         var cr = pettanr.LINE_FEED_CODE_TEXTAREA;
4959                         return [
4960                                 '{', cr,
4961                                         '"resource_picture_id": ', _imageElement.resourcePicture().id, ',', cr,
4962                                         '"x": ',                   _imageElement.x, ',', cr,
4963                                         '"y": ',                   _imageElement.y, ',', cr,
4964                                         '"z": ',                   _imageElement.z, ',', cr,
4965                                         '"width": ',               _imageElement.flipH() * _imageElement.w, ',', cr,
4966                                         '"height": ',              _imageElement.flipV() * _imageElement.h, ',', cr,
4967                                         '"t": ',                   timing, cr,
4968                                 '}'
4969                         ].join( '');
4970                 };
4971
4972                 function balloonToJson( _textElement ){
4973                         var cr = pettanr.LINE_FEED_CODE_TEXTAREA;
4974                         return [
4975                                 '{', cr,
4976                                         '"balloon_template_id": ', 1, ',', cr,
4977                                         '"system_picture_id": ',   1, ',', cr,
4978                                         '"size": ',                1, ',', cr,
4979                                         '"tail": ',                _textElement.angle(), ',', cr,
4980                                         '"x": ',                   _textElement.x, ',', cr,
4981                                         '"y": ',                   _textElement.y, ',', cr,
4982                                         '"z": ',                   _textElement.z, ',', cr,
4983                                         '"t": ',                   timing, ',', cr,
4984                                         '"width": ',               _textElement.w, ',', cr,
4985                                         '"height": ',              _textElement.h, ',', cr,
4986                                         '"speeches_attributes": {', cr,
4987                                                 '"newf', timing, '": {', cr,
4988                                                 '"content": "', _textElement.text(), '",', cr,
4989                                                         '"x": ',        _textElement.x, ',', cr,
4990                                                         '"y": ',        _textElement.y, ',', cr,
4991                                                         '"t": ',        timing, ',', cr,
4992                                                         '"width": ',    _textElement.w, ',', cr,
4993                                                         '"height": ',   _textElement.h, cr,
4994                                                 '}', cr,
4995                                         '}', cr,
4996                                 '}'
4997                         ].join( '');
4998                 };
4999         
5000         function clickGenerate(){
5001                 var i = comboboxFormat.selectIndex(),
5002                         text = 'sorry...';
5003                 if( i === 0 ){
5004                         text = getJsonPostString();
5005                 } else
5006                 if( i === 1 ){
5007                         text = getJsonGetString();
5008                 } else
5009                 if( i === 3 ){
5010                         text = getAsHtmlString( false, false );
5011                 } else {
5012                         
5013                 };
5014                 elmOutputArea.value = text;
5015         };
5016         function clickClose(){
5017                 OutputConsole.shutdown();
5018                 return false;
5019         };
5020         
5021         /* grobal method */
5022         this.MIN_WIDTH   = 320;
5023         this.MIN_HEIGHT  = 320;
5024         this.onInit = function(){
5025                 instance.rootElement.id = 'output-console-wrapper';
5026                 instance.rootElement.className = 'console-wrapper';
5027                 instance.rootElement.innerHTML = [
5028                         '<div id="output-console-header" class="console-header">Output Console</div>',
5029                         '<div id="output-console" class="console-inner">',
5030                                 '<div id="output-console-format" class="field">',
5031                                         '<span class="field-label">Format:</span>',
5032                                         '<span id="output-console-format-value" class="output-console-value combobox"></span>',
5033                                 '</div>',
5034                                 '<div id="output-console-option" class="field">',
5035                                         '<span class="field-label">Options:</span>',
5036                                         '<span id="output-console-option-value" class="output-console-value editable-value">absolute-path</span>',
5037                                 '</div>',
5038                                 '<div id="output-console-button-container" class="clearfix">',
5039                                         '<div id="output-console-generate-button" class="button console-submit-button">generate</div>',
5040                                         '<div id="output-console-close-button" class="button console-cancel-button">close</div>',
5041                                 '</div>',
5042                                 '<textarea id="output-area" readonly></textarea>',
5043                         '</div>'
5044                 ].join( '' );
5045
5046                 instance.fetchCSS( '/assets/peta.apps.css' );
5047
5048                 delete instance.onInit;
5049         };
5050         this.onOpen = function( _w, _h, _comicID, _panelID, _panelTimming, _panelW, _panelH, _borderSize, _panelElementArray ){
5051                 elmOutputArea = document.getElementById( 'output-area' );
5052                 
5053                 var ui = instance.createUIGroup();
5054                 comboboxFormat = ui.createCombobox( document.getElementById( 'output-console-format' ), clickGenerate );
5055                 
5056                 for( var i=0; FORMAT_LIST[ 0 ]; ++i ){
5057                         comboboxFormat.createOption( FORMAT_LIST.shift(), null, i === 0 );
5058                 };
5059                 inputOption    = ui.createInputText( document.getElementById( 'output-console-option' ), null );
5060                 buttonGenerate = ui.createButton( document.getElementById( 'output-console-generate-button' ), clickGenerate );
5061                 buttonClose    = ui.createButton( document.getElementById( 'output-console-close-button' ), clickClose );
5062                 instance.onPaneResize( _w, _h );
5063                 
5064                 comicID           = _comicID;
5065                 panelID           = _panelID;
5066                 panelTimming      = _panelTimming;
5067                 panelW            = _panelW;
5068                 panelH            = _panelH;
5069                 borderSize        = _borderSize;
5070                 panelElementArray = _panelElementArray;
5071                 
5072                 clickGenerate();
5073         };
5074         this.onPaneResize = function( _windowW, _windowH ){
5075                 windowW = _windowW;
5076                 windowH = _windowH;
5077                 instance.rootElement.style.cssText = [
5078                         'left:', Math.floor( ( _windowW - instance.rootElement.offsetWidth  ) /2 ), 'px;',
5079                         'top:',  Math.floor( ( _windowH - instance.rootElement.offsetHeight ) /2 ), 'px;'
5080                 ].join( '' );
5081         };
5082         this.onClose = function(){
5083                 elmOutputArea.value = '';
5084                 elmOutputArea = comboboxFormat = inputOption = buttonGenerate = buttonClose = panelElementArray = instance = null;
5085         };
5086 }, true, false, 'Output Console', 'outputConsole', null, '#2D89F0' );
5087
5088 })( pettanr, gOS, window );