// -- worker ants -- //

    // dynamic select //
    
    selectpop = new Class({
        Implements : [Options,Events],
        options: { select : null },
        initialize : function(options) {
            this.setOptions(options);
            this.update_select();
            this.options.select.addEvent( 'change' , this.update_select.bind(this) );
            this.items = null;
        },
        update_select : function() {
            this.index = $$('.select_snd').indexOf(this.options.select);
            if( $$('.select_pop')[this.index] ) {
                this.select_rcv = $$('.select_rcv')[this.index];
                this.select_pop = $$('.select_pop')[this.index];
                this.cat_id = this.options.select.getSelected().getProperty('value');
                this.select_options = this.select_pop.getChildren('ul[rel=cat_'+this.cat_id+']')[0].getChildren('li');
                this.select_tags = ( this.select_rcv.getProperty('rel') !== null ? this.select_rcv.getProperty('rel').split('|') : [] );
                this.select_rcv.empty();
                this.select_options.each( function( el ) {
                    this.sel = ( this.select_tags.contains( el.get('rel').replace(/&amp;/,'&') ) ? 'selected' : '' );
                    this.hl = ( this.select_tags.contains( el.get('rel').replace(/&amp;/,'&') ) ? 'highlight' : '' );
                    this.value = ( el.getProperty('rel') !== null ? el.getProperty('rel') : el.get('html').replace(/&amp;/,'&') );
                    this.select_rcv.adopt( new Element( 'option' , { 'html' : el.get('html') , 'value' : this.value , 'selected' : this.sel , 'class' : this.hl } ) );
                }.bind(this));
            } else {
                this.select_rcv = $$('.select_rcv')[this.index].empty();
                selected = this.options.select.getSelected().getProperty('value');
                if( !this.items ) {
                    var jsonRequest = new Request.JSON({ url: base_url + 'static/json/' + $$('.select_rcv')[this.index].getProperty('name') + '.json', onSuccess: function(items){
                        this.items = items;
                        this.items.each( function( el ) { if( el.b == selected && el.n ) this.select_rcv.adopt( new Element( 'option' , { 'html' : el.n , 'value' : el.i } ) ); }.bind(this));
                    }.bind(this)}).get();
                } else { this.items.each( function( el ) {  if( el.b == selected && el.n ) this.select_rcv.adopt( new Element( 'option' , { 'html' : el.n , 'value' : el.i } ) );  }.bind(this)); }
            }
        }
    });

    // 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');
            base_zonearea = $$('body')[0].getProperty('title');
            
 			/* -- navigation -- */
 			
 			$$('#navigation_top span').addEvents({
 				mouseenter : function() { this.getChildren('ul').removeClass('hide'); },
 				mouseleave : function() { this.getChildren('ul').addClass('hide'); }
 			})
            
            /* -- stupid xhtml -- */
            
            $$('.code').setProperty( 'wrap', 'off' );
            $$('a[rel=out]').setProperty( 'target', '_blank' );
            
            /* -- slider -- */
            
            if( $('tmpl_slide') ) { slide = new Fx.Slide( $('tmpl_slide') ).hide(); }

            /* -- input file types -- */

            if( $$('input[type=file]').length > 0 ) { trig = new Asset.javascript( base_url + 'static/javascript/libs/upload/source/Swiff.Uploader.js' );  }
            
            /* -- dynamic selects -- */
            
        	$$('.select_snd').each( function( el ) { trig = new selectpop({ select : el }); } );
            
            /* -- and the tabbed panels -- */

            if( $$('.panel').length > 0 ) {
                trig = new Asset.javascript( base_url + 'static/javascript/class/jscript_tabpanel.js', { onload: function(){ 
                    tabp = [];
                    $$('.panel').each( function( el , i ) { tabp[i] = new tabpanel( el , { cprog: base_zonearea }); }); 
                }});
            }
                 
            /* -- grab the forms -- */
            
            if( $$('form').length > 0 ) {
            	// hack for IE7. Bloody IE7 //
                trig = new Asset.javascript( base_url + 'static/javascript/class/jscript_formfetch.js', { onload: function(){ 
                    $$('form[class!=sa]').each( function( el ) { trig = new formfetch( el , { action: el.getAttributeNode('action').nodeValue , method: el.getProperty('method') }); }); 
                }});
            }
                        
            /* -- delete -- */
            
            if( $$('.delete').length > 0 )          getDelete(); 
            
            $$('.togglee').addClass('hide');
            $$('.toggler').addEvent( 'click', function() {
                index = $$('.toggler').indexOf(this);
                $$('.togglee')[index].toggleClass('hide');
            });
           
            /* -- select stuff -- */
                        
            $$('.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'); 
            });
            
            $$('.selectngo').addEvent( 'change' , function() {
                location.href = this.getProperty('rel') + this.getSelected().getProperty('value');
            });
            
            /* -- image list -- */
            
            if( $('image_list') ) {
            	
            	imgs_ = $$('#image_list img');
            	imgs_.set('opacity',0);
            	
            	list_ = [];
            	$$('#image_list img').each( function(el,i){ list_[i] = el.getProperty('src').replace(/small/,'large');  });

            	Asset.images(list_,{onComplete:function(){
            		
            		imgs_.fade(1);
            		
	            	fx = new Fx.Morph( 'image_holder' , {duration:400} );
	            	imgs_.addEvent('click', function() {
	            		fx.start({ 'height' : [0] }).chain( function() {
	            			dim = this.getProperty('alt').split('x');
	            			$('image_holder').setProperty('src', this.getProperty('src').replace(/small/,'large') );
	            			fx.start({ 'height' : [dim[1]] })
	            		}.bind(this));
	            	});
            	
            	}});

            }
            
            /* -- carousel -- */
            
            if( $('carousel') ) {
            	
            	text_ = $('carousel_txt').getChildren('span');
            	imgs_ = $$('#carousel img');
            	imgs_.setOpacity(0);
            	img_curr = 0;
            	title = $('carousel').getElement('h1');
            	text = $('carousel').getElement('div');
            	
           		carousel_ = function() {      
           			imgs_[img_curr].fade(0);
           			img_curr = (img_curr+1 == imgs_.length ? 0 : img_curr+1);
           			imgs_[img_curr].fade(1);
           			title.set( 'html' , imgs_[img_curr].getProperty('alt') != null ? '<a href="'+imgs_[img_curr].getProperty('alt')+'">'+imgs_[img_curr].getProperty( 'title' )+'</a>' : imgs_[img_curr].getProperty( 'title' ));
           			text.set( 'html' , text_[img_curr].get('html') );
            	}
            	
            	carousel_();
           		carousel_.periodical(10000);
            
            }

            if( $('map') ) {
            
                coords = $('map').getProperty('rel').split(',');
                latlng = new google.maps.LatLng(coords[0],coords[1]);
                                    
                map_ = new google.maps.Map( $('map'), {
                    zoom: 14, 
                    center: latlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    mapTypeControl: true,
                    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
                    navigationControl: true,
                    navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL}
                });
    
                marker_cranford = new google.maps.Marker({
                    position: latlng, 
                    map: map_,
                    draggable:false,
                    title:'Watson & Sole'
                });			
                marker_cranford.setZIndex(500);
                
            }  
 
            /* -- aaaaand the wysiwyg -- */
            
            if( $$('.wysiwyg').length > 0 ) {
                wysiwyg_ = [];
                $$('.wysiwyg').each( function( el , i ) {
                    if( el.getProperty('value') == '' ) el.setProperty('value','&#160;');
                    if( !el.hasClass( 'tmpl' ) ) {
                        toolbar_ = [['Source','Templates','Maximize','-','Undo','Redo'],['ShowBlocks'],['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar'],['Link','Unlink','Anchor'],['TextColor','BGColor'],
                        '/',['Bold','Italic','Underline','Strike'], ['NumberedList','BulletedList'],['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],['Format','Font','FontSize']];
                    } else toolbar_ = [[]];
                    wysiwyg_[i] = CKEDITOR.replace( el , { uiColor : '#AAAAAA' , toolbar: toolbar_ , 
                        filebrowserBrowseUrl : base_url + 'static/javascript/libs/editor/filemanager/browser/default/browser.html?Connector=' + base_url + 'static/javascript/libs/editor/filemanager/connectors/php/connector.php',
                        filebrowserImageBrowseUrl : base_url + 'static/javascript/libs/editor/filemanager/browser/default/browser.html?Type=Image&Connector=' + base_url + 'static/javascript/libs/editor/filemanager/connectors/php/connector.php',
                        filebrowserFlashBrowseUrl : base_url + 'static/javascript/libs/editor/filemanager/browser/default/browser.html?Type=Flash&Connector=' + base_url + 'static/javascript/libs/editor/filemanager/connectors/php/connector.php'});         
                    wysiwyg_[i].config.height = el.getStyle('height');
                    wysiwyg_[i].config.resize_enabled = 0;
                    wysiwyg_[i].config.removePlugins = 'elementspath,save';
                    wysiwyg_[i].config.pasteFromWordRemoveStyle = true; 
                    wysiwyg_[i].config.forceSimpleAmpersand = true;
                    wysiwyg_[i].on( 'instanceReady' , function(e) { e.editor.dataProcessor.writer.lineBreakChars = ''; });
                });  
            }
                       
            /* -- then we clean up -- */
            
            $$('body')[0].removeProperty('title'); // get rid of this so we don't have annoying yellow title thingy

        },
        
        load : function() {
        
            /* -- slider -- */
        
            if( $('tmpl_slide') ) { 
                slide.toggle(); 
                ( function() { slide.toggle(); } ).delay( 5000 );
            }

        }
        
    });
