


//Class to unleash the enjinroom wheel

var EnjinWheel = new Class({

    initialize: function() {
        
    },

    showwheel: function() {
        $('enjinroom-wheel').fade('in');                
    },

    hidewheel: function() {
        (function(){$('enjinroom-wheel').fade('out');}).delay(3000);
    }

});

//global enjinwheel
enjinwheel = new EnjinWheel();



//Class to shrink long posts

var PostBeautifier = new Class({

    initialize: function(maxheight) {
        this.maxheight = maxheight;
        this.beautifiedposts = [];
    },



    beautifyclass: function(elements) {
        //go through every element of the class
        //shrink to maxheight
        //inject a div just after
            //width of the post
        //click the div
            //expand the post to it's full size
        //click again - shrink
        elements.each(this.beautifyitem,this);

    },


    //beautifyitem: function(a) {
    //
    //},



    setresizemonitor: function(elemclass) {
        window.addEvent('resize', function() {   
                elems =  $$(elemclass);
                this.clearbeautifiers(elems);
                this.beautifyclass(elems);
        }.bind(this));
    },

    

    clearbeautifiers: function(elemclass) {
        $$(elemclass).each(this.unbeautify,this);
    },

    unbeautify: function(elem) {
        //remove the event
        //need to get the element after this one
        //setheight to auto
        
    },

    
    beautifyitem: function(element) {
        //no need to beautify        
        if (element.getSize().y <= this.maxheight)
        {   
            return;
        }
        
        //dirty hack to allow for firefox overflow:hidden fails on flash objects
        var notflash = 1;
	//alert (element.get('html'));
	if (element.get('html').indexOf('application/x-shockwave-flash') != -1) {
	  return;
	}

	/**
        element.getChildren().each(
                        function(item,index){	
				    alert(typeof item);
	                            if(item.get('html').indexOf('application/x-shockwave-flash') != -1 )  
        	                    { notflash = 0; }    
                        },this);        
        if (notflash == 0)
        {
           return; 
        }
	**/

        var showhidetoggler = new Element('div', 
                                          {'styles': {  'backgroundColor': '#aec4d7', 
                                                        'fontWeight': 'bold',
                                                        'color': 'white',
                                                        'padding': '3px',
                                                        'paddingLeft': '5px',
                                                        'paddingRight': '5px'
                                                    }}
                                         ).injectAfter(element);
                
        //showhidetoggler.setHTML("show V");
        showhidetoggler.set('html',"show V");
        
        var maximized_ht = element.getSize().y;
        var minimized_ht = this.maxheight;

        element.set('styles', {'height': minimized_ht  +  'px'}); 

        showhidetoggler.addEvent('click',
            function (e) {
                new Event(e).stop();

                var toggler = showhidetoggler;
                var elem = element;
                var maximized_height = maximized_ht;
                var minimized_height = minimized_ht;


                var myFx = new Fx.Tween(elem);

                if (elem.getSize().y > minimized_height) 
                {
                    //element is maximized - so minimize
                    myFx.start('height', elem.getSize().y  +  'px', minimized_height  +  'px');                    
                    toggler.set('html',"show V");                            
                }    
                else
                {
                    //maximize
                    elem.set('styles', {'height': 'auto'});
                    maximized_height = elem.getSize().y; 
                    elem.set('styles', {'height': minimized_height  +  'px'});
                    myFx.start('height', elem.getSize().y  +  'px', maximized_height  +  'px');                   
                    toggler.set('html',"hide ^");
                }
            }
        );


    }


});


//global beautifier
var beautifier = new PostBeautifier(200);


		
//rollovers
//Rollover base class
var Rollover = new Class({
    options:{
        'offx': 0,
        'offy': 0,
        'placed': 'top'
    },

    initialize: function(elem, options) {
        //set up the rollover divs
        //make sure to set their classes
		this.setOptions(options);

        this.rollover = new Element('div', { 
			    'styles': { 'left': '-1000px', 
                            'opacity': 0, 
                            'position': 'absolute', 
                            'top': '-1000px',
                            'zIndex': 1000}
		}).injectInside(document.body);


        this.rollovercontent = new Element('div', { 
			    'styles': { 'backgroundColor': 'white', 
                            'border': '1px solid #ccc', 
                            'padding': '5px'}
		}).injectInside(this.rollover);

        //this.rollovercontent.setHTML(content);

        this.rolloverelem = elem;
        //set up fade effects on rollover
        //this.fx = new Fx.Style(this.rollover, 'opacity', {duration: 300, wait: false}).set(0);       
        this.fx = new Fx.Tween(this.rollover, {'property': 'opacity', 'duration': 300, 'link': 'cancel'});
        this.fx.set(0);       

        //set overlap variables
        //so that box stays a little while
        this.mousereentered = false;

        this.rollover.addEvent('mouseenter',this.menter.bind(this));
        this.rolloverelem.addEvent('mouseenter',this.menter.bind(this));
        this.rollover.addEvent('mouseleave',this.mleave.bind(this));
        this.rolloverelem.addEvent('mouseleave',this.mleave.bind(this));
    },

    getrollover: function() { return this.rollover; },

    getrollovercontent: function() { return this.rollovercontent; },

    menter: function() {
        this.mousereentered = true;
        coords = this.rolloverelem.getCoordinates();
        rocoords = this.rollover.getCoordinates();
        var xpos, ypos;

       // if (this.options.placed == 'top' || this.options.placed == 'bottom') {
        //    
        //}

        var pleft = 0;
        var pright = 0;
        var ptop = 2;
        var pbottom = 0;
        
        switch (this.options.placed) {
            case 'top':
                xpos = coords.left;
                ypos = coords.top - rocoords.height;
                break;
            case 'bottom':
                xpos = coords.left;
                ypos = coords.bottom;
                break;
            case 'left':
                xpos = coords.left - rocoords.width;
                ypos = coords.top;
                break;
            case 'right':
                xpos = coords.right;
                ypos = coords.top;
                break;
        }

        this.rollover.setStyles(
        {   'top': ypos + 'px', 
            'left': xpos +  'px', 
            'paddingLeft': pleft +  'px',                //opacity: 100
            'paddingRight': pright +  'px',
            'paddingTop': ptop +  'px',
            'paddingBottom': pbottom +  'px'
        });
        //fade in 
        this.fx.start(1);
    },


    mleave: function() {
        this.mousereentered = false;
        //after delay apply effect
        this.mleavehide.bind(this).delay(1000);        
    },


    mleavehide: function() {
        if (!this.mousereentered) {
            //fade out 
            this.fx.start(0).chain(
                (function () {this.rollover.setStyles({'top': '-1000px', 'left': '-1000px'}) ;}).bind(this)
            );
        }
    },

    mhide: function()  {
        this.mousentered = false;
        //fade out 
        this.fx.start(0).chain(
            (function () {this.rollover.setStyles({'top': '-1000px', 'left': '-1000px'}) ;}).bind(this)
        );
    }

});

Rollover.implement(new Options);








//notice divs inserted into the DOM
//to notify a user of AJAX results

var NoticeDiv = new Class({
    options:{
        'injecttype': 'after',
        'delay': 3000
    },

    initialize: function(text,element, options) {
        this.notice =  new Element('div', { 
			                                'styles': { 'class' : 'ajaxresponsenotice'}
		                                  }).inject(element,this.options.injecttype);
        this.notice.set('html', text);
        //set the timer running on the notice
        this.removenotice.bind(this).delay(this.options.delay);
    },

    removenotice: function() {
        this.notice.dispose();
    }

});
NoticeDiv.implement(new Options);


//Creates the html elements for a feed item

var FeedItem = new Class({
    initialize: function(filling,containerelem,injectposition,beautifier) {
        this.beautifier = beautifier;
        this.fillingid = filling.id;
        this.feeditem = new Element('div', { 
                  'id': 'e-listitem-wrapper-'+filling.id, 
                  'class': 'e-listitem-wrapper',
                  'styles': {'backgroundColor': '#ffffff', 'overflow':'hidden', 'opacity': 0}
        });         
        this.feeditem.set('html',filling.content);
        this.containerelem = containerelem;
        this.injectposition = injectposition;
    },


    setoncomplete: function(chainfn) {
        this.chainfn = chainfn;
    },


    inject: function() {
        this.feeditem.inject(this.containerelem,this.injectposition);
        this.beautifier.beautifyitem($('e-listitem-description-'+this.fillingid));
        
        var feeditemheight = this.feeditem.getSize().y;
        var flashfx = new Fx.Tween(this.feeditem, {property: 'height'});
        var testfx = new Fx.Morph(this.feeditem, {duration: 700});  //,transition: Fx.Transitions.Sine.easeOut



        if($chk(this.chainfn))
        {
            //alert("chain inject called");
            //var myFx = new Fx.Slide(this.feeditem).hide().slideIn().chain(this.chainfn);
            var chainfn = this.chainfn;
            //var myFx = new Fx.Slide(this.feeditem).hide().slideIn().chain(function(){ flashfx.start('#ccc').chain(function(){flashfx.start('#fff').chain(chainfn);});});
            //flashfx.start('#d9d6dd').chain(function(){flashfx.start('#fff').chain(chainfn);});
            testfx.start({
                'opacity': [0,1],
                'height': [1,feeditemheight],
                'margin-bottom':[feeditemheight-1,0],
                'background-color': ['#E4F0F9','#FFFFFF']
            }).chain(function(){ flashfx.set('auto'); testfx.callChain(); },chainfn);
        }
        else
        {
            //var myFx = new Fx.Slide(this.feeditem).hide().slideIn().chain(function(){ flashfx.start('#ccc').chain(function(){flashfx.start('#fff');});});
            //flashfx.start('#d9d6dd').chain(function(){flashfx.start('#fff');});
            //alert("non chain inject called");
            testfx.start({
                'opacity': [0,1],
                'height': [1,feeditemheight],
                'margin-bottom':[feeditemheight-1,0],
                'background-color': ['#E4F0F9','#FFFFFF']
            }).chain(function(){flashfx.set('auto');});

        }
 

    }


});


//Page and tag widget refresh class
var RefreshHandler = new Class({

    initialize: function(updatetime, numresults, requesturl,olderurlstem, beautifier) {
        this.beautifier = beautifier;        
        this.requesturl = requesturl;        
        this.olderurlstem = olderurlstem;
        this.updatetime  = updatetime;
        this.numresults = numresults;
        this.contentitems = [];
        //Start updating every 3 minutes
        this.refresh_periodical_id = this.refreshhandler.periodical(60000,this);
    },


    refreshhandler: function() {
        //get the enjinroom wheel spinning        
        //enjinwheel.showwheel();
        var jsonRequest = new Request.JSON(
            {   url: this.requesturl,
                method: 'get', 
                onComplete: this.refreshresponse.bind(this)
            }
        ).get({'lref': this.updatetime});
    },    

    refreshresponse: function(json, text) {
	//alert(json.hits);

        //get the enjinroom wheel spinning        
        //enjinwheel.hidewheel();

 
        $('pagingtop-numresults').set('html',json.hits);        
        if($chk(json.updatetime))
        {
            this.updatetime = json.updatetime;
        }
        if($chk(json.olderurl))
        {
            $('pagingbottom-olderlink').set('html','<a href="'+ json.olderurl +'">older entries</a>');
        }


        

        var jsoncarray = json.contentlist;
        var newclistlength = jsoncarray.length + this.contentitems.length;
        //alert(text);
        for (var i=0; i< newclistlength -this.numresults ;i++)
        {
            var item = this.contentitems.pop();
            $('e-listitem-wrapper-'+item).dispose();
        }            
        //start adding the json elements
        jsoncarray.reverse();
        //jsoncarray.each(function (item, index) {
                            //this.additemtocontentarray(item.id);
                            

                            //done without removing whole list 
                            //var item_element = new FeedItem(item,beautifier);
                            //item_element.inject($('contentlist'), 'top')
                            
        //                }, this);
        feeditemarr = [];;
        for (var j=0; j< jsoncarray.length ;j++)
        {
            feeditemarr[j] = new FeedItem(jsoncarray[j],$('contentlist'), 'top',beautifier);
            //item_element.inject($('contentlist'), 'top')
            if(j > 0) 
            {
                feeditemarr[j-1].setoncomplete(feeditemarr[j].inject.bind(feeditemarr[j]));
            }
        }
	
	
        if (feeditemarr.length > 0)
        {
            //tip the dominoes
	    
            feeditemarr[0].inject();
	    
        }

	//alert('feeditem injected?');
    },

    additemtocontentarray: function(fid) {
       //add to array
       this.contentitems.unshift(fid);        
    }


});











