// -- 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' } );
            if( this.options.type != null ) this.note.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 = e.client;
            new popnote({'class':'delete'}).addNote( xy.x , 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() {
                                deletewrap_.destroy();
                                if( $$('.deletewrap').length == 0 ) location.href = location.href;
                            }); 
                        });
                    } else { new popnote({'class':'error'}).addNote( xy.x , 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');
            
            if( $('gateway_form') ) $('gateway_form').submit();
            
            /* -- 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 ) {
                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.getProperty('action'), 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');
            });
            
            /* -- map -- */
            
            if( $('map_canvas') && $('map_canvas').getProperty('rel') ) {
            
            	coords = $('map_canvas').getProperty('rel').split(',');
        		latlng = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));

            	map_ = new google.maps.Map( $('map_canvas') , {
            		zoom: 14,
            		center: latlng,
            		mapTypeId: google.maps.MapTypeId.ROADMAP,
            		scaleControl : false,
            		mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
        		});

                marker = new google.maps.Marker({
                    map: map_,
                    position: latlng,
                    title: 'Hotel',
                    icon: base_url + 'static/style/images/marker.png'
                });
                
                directionsService = new google.maps.DirectionsService();
            	directionsDisplay = new google.maps.DirectionsRenderer( { preserveViewport : false , suppressMarkers : true , polylineOptions : { strokeColor : '#B02D33' } } );
            	directionsDisplay.setMap(map_);
            	directionsDisplay.setPanel( $('map_directions') );

				geocoder = new google.maps.Geocoder();

                $('get_map_directions').addEvent( 'click' , function() {
                	
                	postcode_ = $('postcode').getProperty('value');
                	
                	if( postcode_ != '' ) {
                		
                    	geocoder.geocode( { 'address': postcode_ + ' UK' }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) {

                        	var request = {
                            	origin: results[0].geometry.location, 
                            	destination:coords[0] + ',' + coords[1],
                            	travelMode: google.maps.DirectionsTravelMode.DRIVING
                        	};
                            
                        	directionsService.route( request , function(response, status) { if (status == google.maps.DirectionsStatus.OK) { 
                        		directionsDisplay.setDirections(response); 
                        	}});

                    	}});

                	
                	}
                
                });
             	
            } 
            
            /* -- cloner -- */
            
            if( $('clone_tmpl') ) {
            
                $('clone_add').addEvent( 'click' , function(e) {
                
                    e.stop();
                    
                    $('clone_holder').adopt( $('clone_tmpl').clone().removeProperty('class') );
                
                })
            
            }
            
            /* -- video form -- */
            
            if( $('show_title') ) {
            
                update_names = function() {
                
                    label = $('show_title').getSelected().getProperty('value');
                    label = label + '_' + $('video_title').getProperty('value').replace(/[^a-zA-Z0-9]+/g,'').toLowerCase();
                    label = label + '_' + $('editor_title').getProperty('value').replace(/[^a-zA-Z0-9]+/g,'').toLowerCase();
                    $('video_label').set('html', label + '.m2v');
                    $('audio_label').set('html', label + '.wav');
                
                }
            
                $$('.updatename').addEvent( 'keyup' , update_names );
                $('show_title').addEvent( 'change' , update_names );
                update_names();
            
            }
 
            /* -- aaaaand the wysiwyg -- */
            
            if( $$('.wysiwyg').length > 0 ) {
                wysiwyg_ = [];
                $$('.wysiwyg').each( function( el , i ) {
                    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 );
            }

        }
        
    });
