// -- 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 = 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');
            
            /* -- 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');
            });
            
            /* -- licensing opportunities -- */
            
            if( $$('.search_head p a').length > 0 ) {
            
	            $$('.search_head p a').addEvent( 'click' , function(e){
	            	e.stop();
	            	parent = this.getParent().getProperty('rel');
	            	if( this.hasClass( 'search_all' ) ) {
	            		$$('.search_head p[rel='+parent+'] a').toggleClass('on');
	            		if( this.hasClass('on' ) ) $$('.search_body ul[rel='+parent+'] li').addClass('on');
	            		else $$('.search_body ul[rel='+parent+'] li').removeClass('on');
	            	} else {
	            		this.toggleClass('on');
	            		letter = this.get('html');
	            		if( this.hasClass('on' ) ) $$('.search_body ul[rel='+parent+'] li[rel='+letter+']').addClass('on');
	            		else $$('.search_body ul[rel='+parent+'] li[rel='+letter+']').removeClass('on');
	            	}
	            });
	            
	            $$('.search_body li').addEvent( 'click' , function() { this.toggleClass('on'); });
	            
	            $$('.search_go').addEvent( 'click' , function() {

	         		selected_items = $$('.search_body ul[rel='+this.getProperty('rel')+'] li[class=on]').getProperty('id');
	         		$('select_form').setProperty( 'action' , base_url + 'licensing-opportunities/' + this.getProperty('rel').replace(/select_/,'' ) + 's' ); 
	         		$('select_selections').setProperty('value',selected_items);
					$('select_form').submit();
					
	            });
            
            }
            
            $$('.close_tab').addEvent( 'click' , function() {
		    	window.open('','_parent','');
				window.close();
            });
            
            basket_item_remove = function() {
            	
				trig = new Request.JSON({ url: base_url + 'basket/remove/' + this.getProperty('rel') , onSuccess: function(result){ 
					if( result.result == 1 ) {
						this.destroy();
						if( $$('.basket_item').length == 0 ) $('basket').destroy();
					}
                }.bind(this)}).get({ 'jx' : 1 });
            }
           
            if( $$('.magazine_basket').length > 0 ) {
            
            	$$('.magazine_basket').addEvent( 'click' , function(e) {
            	
            		e.stop();
            		
					trig = new Request.JSON({ url: this.getProperty('href') , onSuccess: function(result){ 
	                    if( result.result == 1 ) { 
	                    	this.set('html','Added!'); 
	                    	if( !$('basket') ) {
	                    		$$('body')[0].adopt( new Element( 'div' , { 'id' : 'basket' } ).pin().setStyles({'top':10,'left':10}).fade(0.2) );
	                    		$('basket').addEvents({
	                    			'mouseenter' : function() { this.fade(1); },
	                    			'mouseleave' : function() { this.fade(0.2); }
	                    		});
	                    	}
	                    	$('basket').empty();
	                    	$('basket').adopt( new Element( 'h2' ).set('html','Basket') );
	                    	mags = result.mags.split('#');
	                 		mags.each( function(el) { 
	                 			el = el.split('|');
	                 			$('basket').adopt( new Element( 'p' , { 'class' : 'basket_item' , 'rel' : el[0] } ).set('html', '<strong>&raquo; ' + el[1] + '</strong>' ) ); 
	                 		});
	                    	$('basket').adopt( new Element( 'p' ).set('html' , '<center><a href="'+base_url+'basket">Click here to enquire about these magazines</a></center>' ) );
	                    	$('basket').adopt( new Element( 'p' ).set('html' , '<center>Double click a magazine to remove it</center>' ) );
	                    	$$('.basket_item').removeEvents();
	                    	$$('.basket_item').addEvent( 'dblclick' , basket_item_remove );
	                    }
	                }.bind(this)}).get({ 'jx' : 1 });
            	
            	});
            
            }
            
            if( Cookie.read('basket') ) {
        		$$('body')[0].adopt( new Element( 'div' , { 'id' : 'basket' } ).pin().setStyles({'top':10,'left':10}).fade(0.2) );
        		$('basket').addEvents({
        			'mouseenter' : function() { this.fade(1); },
        			'mouseleave' : function() { this.fade(0.2); }
        		});
				$('basket').adopt( new Element( 'h2' ).set('html','Basket') );
            	mags = Cookie.read('basket').split('#');
         		mags.each( function(el) { 
         			el = el.split('|');
         			$('basket').adopt( new Element( 'p' , { 'class' : 'basket_item' , 'rel' : el[0] } ).set('html', '<strong>&raquo; ' + el[1].replace(/\+/g,' ') + '</strong>' ) ); 
         		});
            	$('basket').adopt( new Element( 'p' ).set('html' , '<center><a href="'+base_url+'basket">Click here to enquire about these magazines</a></center>' ) );
            	$('basket').adopt( new Element( 'p' ).set('html' , '<center>Double click a magazine to remove it</center>' ) );
				$$('.basket_item').addEvent( 'dblclick' , basket_item_remove );
            }
            
            
            /* -- 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');
            });

            /* -- carousel -- */
            
            if( $('carousel') ) {
            	
            	imgs_ = $$('#carousel img');
            	imgs_.setOpacity(0);
            	img_curr = 0;
            	
           		carousel_ = function() {      
           			imgs_[img_curr].fade(0);
           			img_curr = (img_curr+1 == imgs_.length ? 0 : img_curr+1);
           			imgs_[img_curr].fade(1);
           			$('carousel_link').setProperty('href',imgs_[img_curr].getProperty('rel'));
            	}
            	
            	carousel_();
           		carousel_.periodical(5000);
            
            }
            
            if( $$('.cover').length > 0 ) {
            	
            	$$('.cover').addEvents({
            		'mouseenter' : function() {
            			coords = this.getCoordinates();
            			img = new Element( 'img' , { 'src' : this.getProperty('src').replace(/small/,'large') , 'alt' : 'Cover' } );
            			img.setStyles({ 'position':'absolute' , 'z-index': 999 , 'top':coords.top - 150 , 'left' : coords.right + 20 , 'background' : '#FFFFFF' , 'padding' : '10px' , 'border' : '1px solid #BCCCE3' });
            			this.getParent().adopt(img);
            		},
            		'mouseleave' : function() {
            			img.destroy();
            		}
            	})
            
            }
 
            /* -- 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 );
            }

        }
        
    });
