(function(jq){
    jq.fn.events = function() { 
        
        var close_all_open_events = function() {
            jq('.event_entry').each( function() {
                var cur_height = jq(this).height() ;
                if (cur_height > 138) {
                    jq(this).click() ; 
                }
            }) ; 
        }
    
        
        jq('.event_entry').each(function(){
            var _self = jq(this) ; 
            var _image = _self.find('img') ; 
            var _open = false ; 
            var _text_block = _self.find('.event_text') ;
            var _link_block = _self.find('.event_link') ; 
            var _closed_height = 138 ; 
            var _open_height = Math.max(
                parseInt(_self.find('.event_image_wrap').height()), 
                parseInt(_self.find('.event_text_wrap').height() + 40),
                _closed_height
            ) ; 
            
            _self.css({height:"138px"}) ; 

            _self.hover(
                function () {
                    if (!_open) {
                        _image.css("opacity", 0.6) ; 
                        jq(this).css("cursor", "pointer") ; 
                    }
                }, 
                function () {
                    if (!_open) {
                        _image.css("opacity", 1.0) ; 
                    }
                }
            ) ; 
            
            _self.unbind('click') ; 
            _self.click(
                function () { 
                    if (_open) { close_event() ; }
                    else { open_event() ; }
                }
            ) ;
             
            var open_event = function() {
                
                _open_height = Math.max(
                    parseInt(_self.find('.event_image_wrap').height()), 
                    parseInt(_self.find('.event_text_wrap').height() + 40),
                    _closed_height
                ) ;


                _self.animate({
                    'height':  _open_height + 'px'
                }, 500, function() {
                    jq.scrollTo(_self, 500, {offset:-100}) ; 
                }) ; 
            
                _open = true ;  
                _image.css("opacity", 1.0) ;  
                _text_block.css({'visibility':'visible'}) ; 
                _link_block.css({'visibility':'visible'}) ; 
                close_all_open_events() ; 
            }
            
            var close_event = function() {
                _self.animate({
                    height: _closed_height
                }, 500) ; 
                _open = false ; 
                _form_open = false ; 
                _image.css("opacity", 0.6) ; 
                _text_block.css({'visibility':'hidden'}) ; 
                _link_block.css({'visibility':'hidden'}) ; 
            }
        }) ; 
    }
})(jQuery);
