window.addEvents({

    'domready' : function() {

        doc_size = window.getSize();
        doc_scroll_size = window.getScrollSize();
        doc_scroll = window.getScroll();
                       
        if( $('chat_container') ) {

             $('chat_info_window').set('opacity',0);
            fx_info_window = new Fx.Morph( 'chat_info_window' ); 

            chat_info_ = [];
            $$('input[type=hidden]').each( function( el , i ) { chat_info_[i] = el.getProperty('value'); });
       
            /* -- getting -- */
       
            function chat_get_msgs(f) {
            
                new Request.JSON({url: base_url+"imps/chat?r="+new Date().getTime() , onComplete: function(response){ if( response ) {
                
                    if( response == "leave" ) {
                        location.href = base_url + 'chat';
                        return;
                    }
                    
                    pvtmsg_on_ = $$('.pvtmsg_on').getProperty('id');
                
                    $('chat_messages').set('html',response.messages);
                    
                    if( chat_info_[10] == 1 ) $('chat_middle').scrollTo(0, $('chat_middle').getScrollSize().y); 

                    $$('.delete_message').addEvent( 'click' , function() {
                        $('op').setProperty('value', 'delete_msg');
                        $('mmessage').setProperty('value', this.getProperty('rel') );
                        new Request.JSON({url: base_url+"imps/chat", onComplete: function(response){ if( response ) {
                            $('op').setProperty('value', '');
                            CKEDITOR.instances.mmessage.setData('');
                            CKEDITOR.instances.mmessage.focus();
                            if( response.success == 1 ) chat_get_msgs(1);
                        }}}).post($('chat_form'));
                    });
                    
                    $('chat_online').set('html',response.online);
                    
                    if( $$('.tag').length > 0 ) {
                        $$('.chat_online').addEvents({
                            'mouseenter' : function() { 
                                tags_ = this.getChildren('span');
                                if( tags_[0] ) window.status = tags_[0].get('html').replace(/&amp;/,'&'); 
                            },
                            'mouseleave' : function() { window.status = ''; }
                        });
                    }
                    
                    $$('.pvtmsg').each( function( el ) { pvtmsg_on_.contains( el.getProperty('id') ) ? el.addClass( 'pvtmsg_on' ) : el.addClass( 'pvtmsg_off' ); });
                    
                    $$('.pvtmsg').addEvents({ 
                        'click' : function() {
                            this.toggleClass( 'pvtmsg_on' );
                            this.toggleClass( 'pvtmsg_off' );
                        }
                    });
                    
                    var last_mid = 0;
                    var last_cid = 0;
                     
                    $$('.chat_info_window').addEvent( 'click' , function(e) {
                    
                        e.stop();

                        if( this.getProperty('rel') != last_mid || this.getProperty('name') != last_cid || ( last_mid == 0 && last_cid == 0 ) ) {
   
                            if( !$('chat_info_window').hasClass('on') ) $('chat_info_window').addClass( 'on' );

                            new Request.JSON({url: base_url+"imps/chat", onComplete: function(info){ if( info ) {
                                $('info_name').set('html',info.mname);
                                $('info_title').set('html',info.mtitle);
                                $('info_sig').set('html',info.msig);
                                $('info_group').set('html',info.gname);
                                $('info_group').setProperty('class',info.gstyle);
                                $('info_icon').setProperty('src',base_url + 'static/images/members/icons/'+info.micon);
                                info.charactersheet ? $('info_charactersheet').set('html',info.charactersheet) : $('info_charactersheet').set('html','');
                                info.cname ? $('info_cname').set('html',info.cname) : $('info_cname').set('html','');
                                info.cpersonae ? $('info_cpersonae').set('html',info.cpersonae) : $('info_cpersonae').set('html','');
                                info.cpersonae_img ? $('info_cpersonaeimg').setProperty('src',base_url + 'static/images/venues/personae/'+info.cpersonae_img) : $('info_cpersonaeimg').removeProperty('src');
                                fx_info_window.start({'opacity':[1]});
                            }}}).get({'chat_get_player': this.getProperty('rel'), 'scid':this.getProperty('name')});
                                
                            last_mid = this.getProperty('rel');
                            last_cid = this.getProperty('name');
                        
                        } else {
                            $('chat_info_window').removeClass( 'on' );
                            fx_info_window.start({'opacity':[0]});
                            last_mid = 0;
                            last_cid = 0;
                        }

                     });
                
                }}}).get({ 'cgm' : chat_info_ , 'force' : f });
            
            }
            
            var chat_get_msgs_peri = chat_get_msgs.periodical(10000);
            chat_get_msgs(1);
            
            if( $('chat_weather') ) {
            
                function chat_get_weather(f) {
                
                    new Request.JSON({url: base_url+"imps/chat", onComplete: function(weather){ if( weather ) {
                        $('chat_weather').set('html',"<img src='"+base_url+"static/images/chat/weather/"+weather.code+".gif' title='"+weather.text+" ("+weather.temp+"C) "+weather.date+"' />");
                    }}}).get({ 'chat_get_weather' : $('chat_weather').getProperty('name') , 'force' : f });
                
                }
                
                var chat_get_weather_peri = chat_get_weather.periodical(86400);
                chat_get_weather(1);
                
            }

            /* -- posting -- */
     
            if( $('chat_op_system') ) {
                 $('chat_op_system').addEvent( 'click' , function() { this.toggleClass( 'chat_sys_on' ); });
            }
        
            if( $('chat_op_send') ) {
            
                function chat_send_msg() {
                
                    if( Browser.Engine.presto ) $('mmessage').focus();
                    
                    $('dice_number') ? dn = $('dice_number').getProperty('value') : dn = 0;
                    
                    editor_data = CKEDITOR.instances.mmessage.getData();

                    if( editor_data || dn != 0 ) {

                        $('op').setProperty('value', 'send');
                        $('mmessage').setProperty('value', editor_data);
                        $('pms').setProperty('value',$$('.pvtmsg_on').getProperty('id').join('|'));
                        
                        $('chat_op_system') && $('chat_op_system').hasClass( 'chat_sys_on' ) ? $('sys').setProperty('value' , 1 ) : $('sys').setProperty('value' , 0 );
            
                        new Request.JSON({url: base_url+"imps/chat", onComplete: function(response){ if( response ) {
       
                            if( response.success == 1 ) {
                                CKEDITOR.instances.mmessage.setData('');
                                if( !Browser.Engine.webkit ) CKEDITOR.instances.mmessage.focus();
                                chat_get_msgs(1);
                                $$('.pvtmsg_on').removeClass('pvtmsg_on');
                                $$('.pvtmsg').addClass('pvtmsg_off');
                                if( $('dice_number') ) $('dice_number').setProperty('value',0);
                                $('pms').setProperty('value','');
                                $('op').setProperty('value', '');

                            } else {
                            
                                location.href = base_url + 'chat';
                                return;
                                
                            }
                    
                        }}}).post($('chat_form'));
                    
                    }

                }
                
                $('chat_op_send').addEvents({
                    'focus' : chat_send_msg
                });
                
            }

            $('chat_op_tag').addEvent( 'click' , function() {

                    
                $('op').setProperty('value', 'tag');
                $('mmessage').setProperty('value', CKEDITOR.instances.mmessage.getData() );
            
                new Request.JSON({url: base_url+"imps/chat", onComplete: function(response){ if( response ) {
                    
                    if( response.success == 1 ) {
                        $('op').setProperty('value', '');
                        CKEDITOR.instances.mmessage.setData('');
                        CKEDITOR.instances.mmessage.focus();
                        chat_get_msgs(1);
                    } else {
                        location.href = base_url + 'chat';
                        return;
                    }
                    
                }}}).post($('chat_form'));
        
            });

            if( $('chat_op_boot') ) { $('chat_op_boot').addEvent( 'click' , function(e) {
            
                e.stop();

                if( $$('.pvtmsg_on').length > 0 ) {

                    x = e.client.x - 90;
                    y = e.client.y - 193 + getScroll().y;
            
                    add_note( x , y , "<p><a href='#' id='boot_confirm'><b>Yes, I definitely want to boot these players</b></a></p><p><a href='#' id='boot_remove'>I've changed my mind!</a></p>" );

                    $('boot_confirm').addEvent( 'click' , function(e) {
                        
                        e.stop();
                        
                        $('op').setProperty('value', 'boot');
                        $('pms').setProperty('value',$$('.pvtmsg_on').getProperty('id').join('|'));
                    
                        new Request.JSON({url: base_url+"imps/chat", onComplete: function(response){ if( response ) { 

                            if( response.success == 1 ) {
                                $$('.pvtmsg_on').removeClass('pvtmsg_on');
                                $$('.pvtmsg').addClass('pvtmsg_off');
                                $('note').destroy();
                                $('pms').setProperty('value','');
                                $('op').setProperty('value', '');
                                get_chat_msgs(1);
                            } else {
                                location.href = base_url + 'chat';
                                return;
                            }
                        }}}).post($('chat_form'));
                    });
            
                    $('boot_remove').addEvent( 'click' , function(e) {
                        e.stop();
                        $$('.pvtmsg_on').removeClass('pvtmsg_on');
                        $$('.pvtmsg').addClass('pvtmsg_off');
                        $('note').destroy();
                    });
                
                }
                
            }); }

            if( $('chat_op_clear') ) { $('chat_op_clear').addEvent( 'click' , function(e) {

                e.stop();
                x = e.client.x - 90;
                y = e.client.y - 193 + getScroll().y;
            
                add_note( x , y , "<p><a href='#' id='clear_confirm'><b>Yes, I definitely want to clear this room in all zones</b></a></p><p><a href='#' id='clear_remove'>I've changed my mind!</a></p>" );

                $('clear_confirm').addEvent( 'click' , function(e) {
                    $('op').setProperty('value', 'clear');
                    e.stop();
                    new Request.JSON({url: base_url+"imps/chat", onComplete: function(response){ if( response ) { if( response.success == 1 ) { location.href = base_url+'chat/';  }}}}).post($('chat_form'));
                });
            
                $('clear_remove').addEvent( 'click' , function(e) {
                    e.stop();
                    $('note').destroy();
                });

            }); }
           
            if( $('chat_op_leave') ) { $('chat_op_leave').addEvent( 'click' , function(e) {

                e.stop();
                x = e.client.x - 90;
                y = e.client.y - 193 + getScroll().y;
                
                if( $('chat_op_leave').getProperty( 'rel' ) ) {
                
                    add_note( x , y , "<p><a href='#' class='required' id='transcript_save'><b>Save Transcript!</b></a></p><p><a href='#' id='leave_confirm'><b>Yes, I definitely want to leave</b></a></p><p><a href='#' id='leave_remove'>I've changed my mind!</a></p>" );

                    $('transcript_save').addEvent( 'click' , function(e) {
                        e.stop();
                        $('op').setProperty('value', 'transcript');
                        new Request.JSON({url: base_url+"imps/chat", onComplete: function(response){ if( response ) { 
                            $('op').setProperty('value', '');
                            if( response.success == 1 ) $('transcript_save').set('html',"<b>Your transcript has been saved to archive!</b>");
                            if( response.transcript ) {
                                location.href = base_url+'chat/transcript/'+response.transcript+'/';
                                alert( "hwww" );
                            }
                        }}}).post($('chat_form'));
                    });

                } else  add_note( x , y , "<p><a href='#' id='leave_confirm'><b>Yes, I definitely want to leave</b></a></p><p><a href='#' id='leave_remove'>I've changed my mind!</a></p>" );

                $('leave_confirm').addEvent( 'click' , function(e) {
                    e.stop();
                    $('op').setProperty('value', 'leave');
                    new Request.JSON({url: base_url+"imps/chat", onComplete: function(response){ if( response ) { if( response.success == 1 ) location.href = base_url+'chat/'; }}}).post($('chat_form'));
                });
            
                $('leave_remove').addEvent( 'click' , function(e) {
                    e.stop();
                    $('note').destroy();
                });

            }); }
            

            
            $$('#dice input[type=text]').addEvents({
                'keydown' : function() { curr_val = this.getProperty('value'); },
                'keyup' : function() { if( isNaN( this.getProperty('value') ) ) this.setProperty( 'value' , curr_val ); }
            });
            
        }
    
        /* -- enter chat form -- */
        
        $$('.enter_chat').addEvent( 'click' , function(e) {
        
            e.stop();

            doc_size = window.getSize();
            doc_scroll_size = window.getScrollSize();
            doc_scroll = window.getScroll();
            
            ['enter_password','enter_char','enter_zone'].each( function( el ) { if( $(el) ) $(el).removeClass('hide'); });
            
            info = this.getProperty('rel').split('#');

            $('enter_title').set( 'html', 'Enter ' + info[1] );
            $('enter_id').setProperty( 'value', info[0] );
            
            if( info[4] < 0 && $('enter_char') ) $('enter_char').addClass('hide');
            if( info[3] != 1 ) $('enter_password').addClass('hide');
            if( info[2] != '||' ) {
                zone_html = "<input type='radio' name='szone' value='0' checked='checked' /> Current time ";
                info[2].split('|').each( function(z) {
                    if( z == 1 ) zone_html += "<input type='radio' name='szone' value='1' /> Day ";
                    if( z == 2 ) zone_html += "<input type='radio' name='szone' value='2' /> Night ";
                    if( z == 3 ) zone_html += "<input type='radio' name='szone' value='3' /> Umbra ";
                    if( z == 4 ) zone_html += "<input type='radio' name='szone' value='4' /> Shadowlands ";
                });
                $('enter_zones').set('html',zone_html);
            } else $('enter_zone').addClass('hide');
            
            $('blackout').set('opacity',0.6).setStyles({'height':doc_scroll_size.y, 'width':doc_size.x}).removeClass('hide');
            $('canvas').removeClass('hide');
            $('canvas').set( 'html' , "<form method='post' name='chat'>" + $('enter').get('html') + "</form>" );
            $('canvas').setStyles({ 'top': ( (doc_size.y-$('canvas').getSize().y)/2 ) + doc_scroll.y , 'left':(doc_size.x-$('canvas').getSize().x)/2 });

            form_load();
        
        });
        
        /* -- page chat -- */

        $$('.pager').addEvent( 'click' , function() {
            
            
            $('blackout').set('opacity',0.6).setStyles({'height':doc_scroll_size.y, 'width':doc_size.x}).removeClass('hide');
            $('pager').removeClass('hide');
            $('pager').setStyles({ 'top': ( (doc_size.y-$('pager').getSize().y)/2 ) + doc_scroll.y , 'left':(doc_size.x-$('pager').getSize().x)/2 });

        });

        $$('.pager_location').addEvent( 'click' , function() {
            if( $('pager_location') ) $('pager_location').destroy();
            $('pager_form').adopt( new Element( 'input' , { 'type' : 'hidden' , 'id' : 'pager_location' , 'name' : 'mlid' , 'value' : this.getProperty('rel') } ) );
        });

        $$('.pager_session').addEvent( 'click' , function() {
            if( $('pager_session') ) $('pager_session').destroy();
            $('pager_form').adopt( new Element( 'input' , { 'type' : 'hidden' , 'id' : 'pager_session' , 'name' : 'msid' , 'value' : this.getProperty('rel') } ) );
        });

        $$('.online_listing').addEvents({
            'mouseenter' : function() { if( this.getChildren('span').length == 1 ) { window.status = this.getChildren('span')[0].get('html') } },
            'mouseleave' : function() { window.status = ''; }
        });
        
    },
    
    'load' : function() {
    

        
        if( $('chat_container') ) {

            CKEDITOR.replace( 'mmessage' , { 
                uiColor : '#AAAAAA' ,
                toolbar :
                [
                    [ 'Bold', 'Italic', 'Strike' , 'Underline', '-', 'TextColor' , 'FontSize', 'Font' , '-' , 'Smiley']
                ]

            }); 
            
            CKEDITOR.config.height = $('mmessage').getStyle('height');
            CKEDITOR.config.resize_enabled = 0;
            CKEDITOR.config.startupFocus = true;
            CKEDITOR.config.tabIndex = 1;
            CKEDITOR.config.tabSpaces = 0;
            CKEDITOR.config.removePlugins = 'elementspath,save';
            CKEDITOR.config.pasteFromWordRemoveStyle = true; 
            CKEDITOR.config.forcePasteAsPlainText = true;
            CKEDITOR.config.disableNativeSpellChecker = false;

            CKEDITOR.on( 'instanceReady' , function(e) {
     
                doc_size = window.getSize();
                doc_scroll_size = window.getScrollSize();
                doc_scroll = window.getScroll();
                  
                $('chat_middle').setStyle( 'height' , $('chat_middle_container').getSize().y );
                $('chat_info_window').setStyles({ 'left':(doc_size.x-$('chat_info_window').getSize().x)/2 , 'top' : $('chat_middle').getPosition().y + 1 , 'height' : $('chat_middle').getSize().y - 2 });
               
                e.editor.dataProcessor.writer.lineBreakChars = '';

            });

        }

        /* -- coords -- */

        if( $$('.map_coords').length > 0 ) {

            var geocoder = new google.maps.Geocoder();

            function geocodePosition(pos) {
                geocoder.geocode( {latLng: pos } , function(responses) {
                    if (responses && responses.length > 0) $('map_address').set('html',responses[0].formatted_address);
                    else $('map_address').set('html','Cannot determine address at this location.');
                });
            }

            $$('.map_coords').addEvent( 'click' , function(e) {

                e.stopPropagation();
                
                input_ = this;

                var ll = [];
                this.getProperty('value') != "" ? ll = this.getProperty('value').replace(/\(/,'').replace(/\)/,'').split(',') : ll = [42.483981,-2.8125];

                var latlng = new google.maps.LatLng(ll[0]*1,ll[1]*1);
                $('body_').adopt( 
                    new Element( 'div' , {'id':'map', 'style':'width:'+this.getSize().x+'px;position:absolute;z-index:100;top:'+this.getPosition().y+'px;left:'+this.getPosition().x+'px'} ).adopt(
                        new Element( 'div' , {'id':'map_canvas', 'style':'height:'+this.getSize().x+'px' } ),
                        new Element( 'b' , {'id':'map_close','html':'Close'} )
                    )
                );
                
                $('map').addEvent( 'click' , function(e) { e.stopPropagation() } );
                $('map_close').addEvent( 'click' , function() { $('map').destroy() });
                
                var map = new google.maps.Map(document.getElementById("map_canvas"), {zoom: 1, center: latlng, mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}, mapTypeId: google.maps.MapTypeId.ROADMAP});
                var marker = new google.maps.Marker({
                    position: latlng, 
                    map: map,
                    title: 'Drag Me',
                    draggable:true
                });

                google.maps.event.addListener(marker, "dragend", function(event) {
                    input_.setProperty( 'value' , marker.get_position() ); 
                    geocodePosition(marker.get_position());
                });
 
            });

        }
        
        if( $('map_lg') ) {

            var geocoder = new google.maps.Geocoder();

            function geocodePosition(pos) {
                geocoder.geocode({latLng: pos}, function(responses) {
                    if (responses && responses.length > 0) $('map_address').set('html',responses[0].formatted_address);
                    else $('map_address').set('html','Cannot determine address at this location.');
                });
            }

            function handleNoFlash(errorCode) {
                if (errorCode == FLASH_UNAVAILABLE) {
                    alert("Error: Flash doesn't appear to be supported by your browser");
                    return;
                }
            }  
    
            ll = $('map_lg').getProperty('rel').replace(/\(/,'').replace(/\)/,'').split(',')

            var latlng = new google.maps.LatLng(ll[0]*1,ll[1]*1); 
            
            var map = new google.maps.Map($("map_lg"), {
                zoom: 11,
                center: latlng,
                mapTypeControlOptions: {
                    style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
                },
                navigationControl: true,
                navigationControlOptions: {
                    style: google.maps.NavigationControlStyle.DEFAULT
                }, 
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            
            if( $$('#map_coords li').length > 0 ) {
                marker = [];
                info = [];
                $$('#map_coords li').each( function( el, i ) {
                    coords = el.getProperty('rel').replace(/\(/,'').replace(/\)/,'').split(',');
                    img = el.getProperty('name');
                    
                    if( img != null ) {
                    
                        marker[i] = new google.maps.Marker({
                            position: new google.maps.LatLng(coords[0]*1,coords[1]*1), 
                            map: map,
                            icon: base_url + 'static/images/chat/locations/maps/sm_'+img,
                            title: el.get('html')
                        });

                        content_ = '<div id="map_wrap"><h3>' + el.get('html') + '</h3><img src="'+base_url+'static/images/chat/locations/maps/'+img+'" height="200" width="200" /></div>'

                    } else {
                    
                        marker[i] = new google.maps.Marker({
                            position: new google.maps.LatLng(coords[0]*1,coords[1]*1), 
                            map: map,
                            title: el.get('html')
                        });
                        
                        content_ = '<div id="map_wrap"><h3>' + el.get('html') + '</h3></div>'
                    
                    }
                    
                    info[i] = new google.maps.InfoWindow({ content:  content_ });

                    google.maps.event.addListener(marker[i], "click", function(event) {
                        info[i].open(map,marker[i]);
                    });
                });
                
            }
            

        }
        

    },
    'resize' : function() {
    
    }
    
}); 