// -- worker ants -- //

    // note popups //

    popnote = new Class({

        Implements: [Options, Events],
        options: { 'type' : null , 'timer' : 0 },
        initialize: function( options ) {
            this.setOptions(options);
            this.note = new Element( 'div' , { 'class' : 'popnote' } ).addClass( this.options.type );
            $$('body')[0].adopt(this.note);  
            this.size = window.getSize();
        },
        
        addNote: function( x , y , text ) { 
            this.note.set( 'opacity' , 0 );
            this.note.set( 'html' , text );
            x = ( !x ? ( this.size.x - 250 ) / 2 : x + 10 + Math.floor( Math.random() * 10 ) );
            if( !y ) y = ( ( this.size.y - this.note.getSize().y ) / 2 ) + window.getScroll().y;
            this.note.setStyles({ 'top' : y , 'left' : x });  
            this.note.addEvents({
                'mouseenter' : function() { this.setStyle( 'z-index' ,2 ); },
                'mouseleave' : function() { this.setStyle( 'z-index' ,1 ); },
                'click' : function() { this.destroy(); }
            });
            this.note.fade(1);
            if( this.options.timer != 0 ) ( function() { this.note.fade(0) }.bind(this) ).delay(this.options.timer);
        },
        
        deleteNote: function() { this.note.destroy(); }

    });

    // catches the delete button event and makes nice //

    function getDelete() {
        $$('.delete').addEvent( 'click' , function(e) {
            e.stop();
    		xy = this.getPosition();
            new popnote({'type':'delete'}).addNote( xy.x - 250 , xy.y , "<center><p>Are you sure you want to delete this?</p><p><strong id='delete_confirm'>Yes</strong> | No</p></center>" );
            $('delete_confirm').addEvent( 'click' , function() { 
                url_data = this.getProperty('href').split('/');
                trig = new Request.JSON({ url: this.getProperty('href') , onSuccess: function(result){ 
                    if( result.result == 1 ) {
                        deletewrap_ = $$('.deletewrap')[$$('.delete').indexOf(this)];
                        fade = new Fx.Morph( deletewrap_ , {duration: 'short', transition: Fx.Transitions.Sine.easeOut} );
                        fade.start({ opacity:[1,0] }).chain( function() {
                            deletewrap_.setStyle('height',deletewrap_.getSize().y);
                            deletewrap_.empty();
                            fade.start({height:[deletewrap_.getSize().y,0]}).chain(function() {
                            	if( $$('.deletewrap').length == 1 && deletewrap_.getParent().get('tag') == 'table' ) { deletewrap_.getParent().destroy(); }
                                deletewrap_.destroy();
                            }); 
                        });
                    } else { new popnote({'type':'error'}).addNote( xy.x - 250 , xy.y , result.result ); }
                }.bind(this)}).get({ 'jx' : 1 });
            }.bind(this));
        });
    }

window.addEvents({

    'domready' : function() {
    
        base_url = $$('base')[0].getProperty('href');
        body_ = $$('body')[0];
        base_ = body_.getProperty('class').split('_');
        base_style = ( base_[1] > 0 ? base_url + 'static/styles/'+base_[1]+'/' : base_url + 'static/styles/1/' );

	/* -- load external scripts -- */
        
        var js_load = null;
        js_load = new Asset.javascript(base_url+'static/javascript/jscript_classes.js'); 
        if( $('map') || $$('.map_coords').length > 0 )     { js_load = new Asset.javascript(base_url+'static/javascript/jscript_maps.js'); }    
        if( $$('input[type=file]').length > 0 ) { 
            trig = new Asset.javascript( base_url + 'static/javascript/libs/upload/source/Swiff.Uploader.js' ); 
        }


	/* -- hook elements -- */

		var smsc = new SmoothScroll();
        $$('a[rel=external]').setProperty( 'target' , '_blank' );                               // open link in new window (gets around validator disallowing target=_blank)
        body_.addEvent( 'click' , function() { if( $('note') ) { $('note').destroy(); } });     // note remover
        $$('#strip_alpha a').addEvent( 'focus' , function() { this.blur(); } );
        
	/* -- blackout and canvas -- */
        
        $('blackout').addEvent( 'click' , function() {
            this.addClass('hide');
            $$('.form_overlay').addClass('hide');
        });

    /* -- hide and show rows on click (seen on pretty much every manage xxx page) -- */
    
        parentchild = function() {
            $$('.show_child').addClass( 'hide' );
            $$('.show_parent').addEvent( 'click' , function(e) {
                e.stop();
                $$('*[rel='+this.getProperty('name')+']').toggleClass('hide');
            });
        };
        
        parentchild();
        
    /* -- drop down navigation menus -- */
        
        var subnav_on = $$('.subnav_on');
        var subnav_a = [];
        var subnav_ul = [];
        var subnav_head = null;
            
        $$('.subnav').addEvents({
        
            'mouseenter' : function() {          

                subnav_head = this.getChildren('a[class$=subnav_head]')[0];
                subnav_a = this.getChildren('a[class~=subnav_head]');
                
                subnav_ul = this.getChildren('ul');
                subnav_ul.removeClass('hide');
                
                if( subnav_head ) {
                
                    if( Browser.Engine.version == 4 && Browser.Engine.trident ) {
                        subnav_ul.setStyles({ 'left': subnav_head.getCoordinates().left , 'top' : $('strip_alpha').getCoordinates().bottom -5 , 'z-index' : 3000  });
                    } else {
                        subnav_ul.setStyles({ 'left': subnav_head.getCoordinates().left , 'top' : $('strip_alpha').getCoordinates().bottom -5 , 'min-width' : subnav_head.getSize().x , 'z-index' : 3000  });
                    }
                }                
            },
            'mouseleave' : function() { subnav_ul.addClass('hide'); }   
            
        });

    /* -- form elements -- */

        if( $$('form').length > 0 ) {
            // Node hack for IE7. Bloody IE7 //
            trig = new Asset.javascript( base_url + 'static/javascript/jscript_formfetch.js', { onload: function(){ 
                $$('form[class!=nogo]').each( function( el ) { 
                    action_ = Browser.Engine.trident ? el.getAttributeNode('action').nodeValue : el.getProperty('action');
                    trig = new formfetch( el , { action: action_ , method: el.getProperty('method') }); 
                }); 
            }});
        }
        
        // -- adds tool tip -- //
        
        tips = new Tips('.help', {
            onShow: function(tip, el){ tip.set('opacity',0).fade(1); },
            onHide: function(tip, el){ tip.fade(0); }
        });
            
        // -- bots be gone : creates submit buttons -- //

        $$('span[class=submit]').each( function( el ) { 
            hidden = new Element( 'input' , { 'type' : 'hidden' , 'name' : 'action' , 'value' : el.getProperty('name') } );
            button = new Element( 'input' , { 'type' : 'submit' , 'name' : 'go' , 'value' : el.get('html') } );
            hidden.replaces(el);
            button.inject( hidden , 'after' );
        });
        
        
        // -- selectngo -- //

        $$('.selectngo').addEvent( 'change' , function() {
            location.href = this.getProperty('rel') + this.getProperty('value');
            return;           
        });

        // -- select populators -- //

        if( $('select_ch') ) {
            update_select_ch = function() {
                $$('.select_ch').addClass('hide');
                $$('div[rel=sel_'+$('select_ch').getProperty('value')+']').removeClass('hide');
            };
            $('select_ch').addEvent( 'change' , update_select_ch );
            update_select_ch();
        }

        // -- select show hide -- //

        $$('.showhide').each( function(el) { $$('*[rel='+el.getProperty('name')+'_'+el.getSelected().getProperty('value')+']').toggleClass('hide'); });
        $$('.showhide').addEvent( 'change' , function() { 
            $$('*[rel^='+this.getProperty('name')+']').addClass('hide');
            $$('*[rel='+this.getProperty('name')+'_'+this.getSelected().getProperty('value')+']').removeClass('hide'); 
        });

        // -- code editing textarea -- //

        $$('.code').addEvent( 'keydown' , function(e) {
            if( e.key == 'tab' ) {
                e.stop();
                this.insertAtCursor("    ");
                this.setCaretPosition(this.getCaretPosition()+4);
            }
        });
  
    /* -- ie6, you shall go to the ball -- */
    
        if( Browser.Engine.version == 4 && Browser.Engine.trident ) {
        
            // -- pngfix done the long way because otherwise IE cries like a girl. IDEK. -- //
            
            [$('container'),$('container_inner'),$$('.pin'),$$('*[src$=png]'),$('slider_search')].each( function( el ) { el.addClass('iefix'); } );
            DD_belatedPNG.fix('.iefix');

            // -- working around the css selectors. or lack thereof, as the case may be. -- //

            [$$('#content_beta input[type=submit]'),$$('#content_delta input[type=submit]'),$$('#content_beta input[type=button]'),$$('#content_delta input[type=button]')].each( function( el ) { el.addClass('submit'); } );
            
        } 

    /* -- clone -- */
        
        if( $('clone_go') && $('clone_tmpl') && $('clone_target') ) {
        
            $$('.clone_delete').addEvent( 'click' , function() { this.getParent().destroy(); });
            
            $('clone_go').addEvent( 'click' , function(e) {
                e.stop();
                $('clone_target').adopt( $('clone_tmpl').clone().removeClass('hide').removeProperty('id') );
                $$('.clone_delete').removeEvents();
                $$('.clone_delete').addEvent( 'click' , function() { this.getParent().destroy(); });
            });
        
        }
        
    /* -- images -- */    
    
        // -- img thumbs -- //
        
        $$('.img_thumb p').addEvent( 'click' , function() {
        
            this.toggleClass('on');
            
            if( $('img_delete') ) {
            
                delete_img = [];
                $$('.img_thumb p.on').each( function( el , i ) { delete_img[i] = el.getProperty( 'alt' ); });
                
                $('img_delete').setProperty( 'value' , delete_img.join('|') );
            
            }
            
        });
        
        // -- image display -- //
        
        $$('.main_latest ul li').addEvent( 'mouseenter' , function() {
            this.getSiblings().removeClass('on');
            this.addClass('on');
            url = ( this.getProperty('rel') != null ? 'large/'+this.getProperty('rel') : 'blank_lg.jpg' )
            this.getParent().getParent().getChildren('img')[0].setProperty( 'src' , base_url+'static/images/properties/listings/' + url );
        });
        
    /* -- load overlay form -- */
    
        $$('.load_form').addEvent( 'click' , function(e) { 
            e.stop();
            doc_size = $(document.body).getSize();
            doc_scroll_size = $(document.body).getScrollSize();
            doc_scroll = $(document.body).getScroll();
            if( this.getProperty('id') ) {
                if( $('passthru') ) { $('passthru').destroy(); }
                info = this.getProperty('id').split('_'); // type - id - name //
                if( $(info[0]) && info[2] ) $(info[0]).set( 'html' , $(info[0]).getProperty('rel') + info[2] );
                $(this.getProperty('rel')).adopt( new Element( 'input' , { 'id' : 'passthru' , 'type' : 'hidden' , 'name' : 'passthru' , 'value' : info[0]+'_'+info[1] } ) );
            }
            loading = ( this.getProperty('rel') ? $(this.getProperty('rel')) : $('global_contact_form') );
            $$('.form_overlay_close').addEvent( 'click' , function(e) {
                loading.addClass('hide');
                $('blackout').addClass('hide');
            });
            loading.setStyles({
                'top': 110 , 
                'left':(doc_size.x-413)/2 + 10
            }).removeClass('hide');
            new Fx.Scroll(window).toTop();
            $('blackout').set('opacity',0.4).setStyles({'height':doc_scroll_size.y, 'width':doc_size.x}).removeClass('hide');
        });

    /* -- table sort by headers -- */
        
        tbl_sort = function() {
        
            sort_ = $$('table.sort');
              
            if( sort_.length > 0 ) {
        
                sort_.each( function( el , i ) {
                    
                    if( el.getChildren('thead').length > 0 ) {
                    
                        parse = [];
                        el.getChildren('thead')[0].getChildren('tr')[0].getChildren('th').each( function(elb,ib) {  // get the header parsing types
                            if( elb.get('text') != '' ) { parse[ib] = ( elb.getProperty('rel') ? elb.getProperty('rel') : 'string' );  }
                        });
             
                        sort_table = new HtmlTable( el , {
                            parsers : parse,
                            classNoSort : 'nosort',
                            classZebra : (el.hasClass('zebra') ? 'light' : ''),
                            classHeadSort : 'sortasc' ,
                            classHeadSortRev: 'sortdesc' , 
                            zebra : (el.hasClass('zebra') ? true : false),
                            sortable : true,
                            sortIndex: null,
                            onSort: function() { tbl_alternate(); }
                        });
                        
                    }

                });
        
            }
        
        }
        
        tbl_sort();
        
    /* -- delete -- */      
        
        if( $$('.delete').length > 0 )          getDelete(); 
      
    /* -- wysiwyg -- */
    
        if( $$('.wysiwyg').length > 0 ) { js_load = new Asset.javascript(base_url+'static/javascript/libs/editor/ckeditor.js' , { onload : function() {
            
            wysiwyg_ = [];

            CKEDITOR.on('instanceReady', function(ev) {
                var tags = ['p','ol','ul','li','h1','h2','h3','h4','h5','div']; 
                for (var key in tags) {
                    ev.editor.dataProcessor.writer.setRules(tags[key], {
                        indent : false,
                        breakBeforeOpen : true,
                        breakAfterOpen : false,
                        breakBeforeClose : false,
                        breakAfterClose : true
                    });
                }
            });
    		
    		CKEDITOR.config.forcePasteAsPlainText = true;
    		CKEDITOR.config.resize_enabled = false;
    		CKEDITOR.config.pasteFromWordRemoveStyle = true; 
            CKEDITOR.config.disableNativeSpellChecker = false;
            CKEDITOR.config.forceSimpleAmpersand = true;
    		CKEDITOR.config.removePlugins = 'elementspath,save';
    		
            $$('.wysiwyg').each( function( el , i ) {
            
                if( el.getProperty('rel') == "advanced" ) {
                    wysiwyg_[i] = CKEDITOR.replace( el , { 
                        uiColor : '#AAAAAA',
                        toolbar : [['Bold','Italic','Underline','Strike'],['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],['Font','FontSize'],['NumberedList','BulletedList'],['Link','Unlink'],['TextColor','BGColor'],['Image','Table','HorizontalRule'],['Maximize','Source']]
                    });     
                } else { wysiwyg_[i] = CKEDITOR.replace( el , { uiColor : '#AAAAAA' , toolbar : [ [ 'Bold', 'Italic', 'Strike' , 'Underline', '-', 'TextColor' , 'FontSize', 'Font']] }); }               

                wysiwyg_[i].config.height = el.getStyle('height');

            });  
            
        }} ); }
        
    },
    
    'load': function() {

    /* -- slideshow -- */
    
        if( $('slideshow') ) {
        
            info = $('slideshow').getProperty('rel').split('_');
    
            new Request.JSON({url:base_url+'dynamic/slideshow.php?id='+info[0] , onComplete:function(img_list) {
            
                if( img_list ) {
                
                    ss_imgs = new Asset.images(img_list, {
                        onProgress: function(c,i) {
                            $('slideshow').set('html','<p style="padding:10px ; font-weight:bold">Loading image ' + (c+1) + ' of ' + ss_imgs.length + '</p>' );
                            if( (c+1) == ss_imgs.length ) { $('slideshow').set('html', ''); }
                        },
                        onComplete: function() {
                        
                            data = {};
                            ss_imgs.each( function( el, i ) {
                                this[el.getProperty('src')] = {'caption':'Image ' + (i+1) + ' of ' + ss_imgs.length };
                            },data);
                            
                            new Slideshow.KenBurns('slideshow', data, { controller: true, captions:false, loader:true, height: 315, duration:3000 , thumbnails: true, width: 560 });
                                
                            $$('.slideshow-thumbnails img').addEvents({
                                mouseenter : function() {
                                    body_.adopt( new Element( 'div' , { 'id' : 'slideshow_med' } ) );
                                    $('slideshow_med').adopt( new Element( 'img' , { 'src' : this.getProperty('src').replace(/small/,'medium') } ) );
                                    $('slideshow_med').setStyles({ 'top' : $('slideshow').getCoordinates().top + 230 , 'left' : this.getCoordinates().left - 52 + 13 });
                                },
                                mouseleave : function() { $('slideshow_med').destroy(); }
                            });       
                            
                            if( info[1] != 0 ) { $('slideshow').adopt( new Element( 'img' , {'src':base_url+'property/sales/over/'+info[1] } ).setStyles({'position':'absolute' , 'z-index':10000 , 'top':0 , 'left': 0}) ); }
                            
                        }
                        
                    });
                    
                }
     
            }}).get(); 
    
        }

    }
});
