/*
 * @namespace HYDRA
 */
var HYDRA   =   {};

$(document).ready( function()
{
	 /*
     * Summary: Scroll to the top of the page when ajax paginating
     *               
     */
	$('#pagination_block a').click( function()
	{
		window.scroll(0, 0);
	});
	
	
    /*
     * Summary: Search results toggling
     *               
     */
	$('.search_results').parent().hide();

	$('.heading a').click( function()
	{
		$(this).parent().next('dd < dl').slideToggle();
		return false;
	});


    /*
     * Summary: factory for making accordion objects
     *               
     */
    $('#sidebar.accordion').each( function()
    {
        HYDRA.sidebar   =   new HYDRA.Accordion( $(this).attr('id') );
    });
    
    
    /*
     * Summary: factory for making calendar filter objects
     *               
     */
    $('#content_wrap').each( function()
    {
        HYDRA.calendar  =   new HYDRA.CalendarFilter();
    });
    
    
    //  sets the show/hide checkout forms to hidden initially
    $('#checkout').hide();
    
    //  onclick show the checkout forms
    $('#checkout_link').click( function()
    {
        $('#checkout').slideToggle();
        return false;
    });
    
    
    /*
     * Summary: Makes a search field toggler
     *               
     */
    $('#search_form #search_field').click( function()
    {
        return false;
    });
    
    $('#search').click( function()
    {
        $(this).hide();
        $('#search_form').show();
        $('#search_form #search_field').select();
        $('#search_form #search_field').focus();
        
        $(document).click( function()
        {
            $('#search').show();
            $('#search_form').hide();
        });
        
        return false;
    });
    
});	//	end doc.ready




/*
 * @description:    A filtering sidebar for the calendar views
 *
 * Note: Now works on any content_wrap ID, not just those with calendar class.
 *   
 */
HYDRA.CalendarFilter    =   function()
{
    var cc          =   this;
    this.calendar   =   $("#content_wrap #content");
    this.sidebar    =   $('#sidebar');
    this.events     =   this.calendar.find('dl');
    this.selectionArray =   new Array();
    

    //	go through checkboxes on sidebar and find all filters
    this.findFilters    =   function()
    {
        this.selectionArray.length  =   0;
        var checkedInputs   =   this.sidebar.find('input:checked');
		this.selectionArray.push('nofilter');
		
        checkedInputs.each( function()
        {
            cc.selectionArray.push( $(this).attr('id').slice(5) );
        });
        this.runFilters();
    };
    
	//	check items on calendar for matches against the sidebar filters
    this.runFilters =   function()
    {
        this.events.each( function()
        {
            var eventItem   =   $(this);
            var keep    =   '';
        
            $(cc.selectionArray).each( function()
            {
                if ( eventItem.hasClass( $(this)[0] ) ) 
                {
                    keep    =   'yes'
                    cc.showItem( eventItem );
                    return false;
                }
            });
            
            if ( keep !== 'yes' ) 
            {
                cc.hideItem( eventItem );
            }
        });
    };
    
    this.showItem   =   function( item )
    {
        item.slideDown();
    };


    this.hideItem   =   function( item )
    {
        item.slideUp();
    };

    $('#select_all').click( function()
    {
        if ( $(this).attr('checked') ) {
            $('#filters input').attr('checked', 'checked');
        }
        else
        {
            $('#filters input').removeAttr('checked');
        }
        cc.findFilters()
    });
    
    this.sidebar.find('input:not(#select_all)').click( function( )
    {
        if ( $('#select_all').attr('checked') ) 
        {
            $('#select_all').removeAttr('checked');
            
        }
        cc.findFilters()
    });
    

    ////////////////////////
    // Thumbnail Slideshows
	$('#slideshow').each(function()
	{
		// if there actually are more than one image
		if( $('#slideshow img').length > 1)
		{
		    $('#slideshow').cycle({
		        fx:     'fade', 
		        prev:   '#prev1', 
		        next:   '#next1', 
		        nowrap:  1, 
		        timeout: 0 
		    });    
    
			//  figure out how high the slideshow div needs to be
			var maxHeight = 0;

			//	once the images are done loading...
			$('#slideshow img').load( function()
			{
				//  find out the largest image's height
				$('#slideshow img').each( function()
				{
					if( $(this).height() > maxHeight )
					{
						maxHeight   =   $(this).height();
					}
				});

				//   if it found a height, apply it
				if( maxHeight > 1)
				{
					$('#slideshow').css('height', maxHeight);   
				}  
			});	
		}            
	});
	
	HYDRA. setSlideHeight = function()
	{
			//  figure out how high the slideshow div needs to be
			var maxHeight = 0;

			//	once the images are done loading...
			$('#slideshow img').load( function()
			{
				//  find out the largest image's height
				$('#slideshow img').each( function()
				{
					if( $(this).height() > maxHeight )
					{
						maxHeight   =   $(this).height();
					}
				});

				//   if it found a height, apply it
				if( maxHeight > 1)
				{
					$('#slideshow').css('height', maxHeight);   
				}  
			});	
		
		
	};

    ////////////////////////////////////////
    // disable submit buttons after click...

    $('.form_standard').submit( function()
    {
        $('.form_standard .cloner').remove(); // so cloner won't submit
    
        inputTarget = $(this).find('.controls input');
        $('<img src="/images/layout/ajax_loader.gif" alt="loading..." class="submit_loader" />').insertAfter(inputTarget);
        inputTarget.attr('disabled', 'disabled');
    });

    /////////////////
    // set pagination

    HYDRA.setPagination = function (items_per_page, total_item_count, pagination_target, base_url)
    {
        var items_per_page          = items_per_page;
        var total_item_count        = total_item_count;
        var pagination_target       = pagination_target;
		var base_url                = base_url;
    
        // Create pagination element
        pagination_target.pagination(total_item_count, {
        	num_edge_entries: 2,
        	num_display_entries: 8,
        	link_to: base_url + '__id__',
        	items_per_page: items_per_page,
            callback: pageselectCallback
        });
        
        
        ///////////////////////
        // page change callback
        
        function pageselectCallback(page_id, paginationBlock) {
			// set count element, pagination target
            paginationTarget    = paginationBlock.parent().find('.pagination_section');
            totalCount          = paginationBlock.parent().find('.count span');

            // append loader animation
            $('body').append('<div id="TB_load" style="width: 66px; height: 66px;"><img src="/images/layout/ajax_pagination.gif" /></div>');//add loader to the page
            $('#TB_load').show();
			
			//Fade the element, to let the user know something is going on
			paginationTarget.fadeTo("slow", .25, function () {	
				$.ajax({
					type: "GET",
					url: base_url + parseInt(page_id + 1),
					error: function ( XMLHttpRequest, textStatus, errorThrown )
                    {
					  // typically only one of textStatus or errorThrown will have info
					  alert(textStatus + ': ' + errorThrown); //this; // the options for this ajax request
					},
					complete: function ( XMLHttpRequest, textStatus ) {
						paginationTarget.html( XMLHttpRequest.responseText ).fadeTo("slow", 1.0);
                        $('#TB_load').remove();
                        // set last count item for total count display
                        if ( (page_id * items_per_page) + items_per_page < total_item_count )
                            { new_total = (page_id * items_per_page) + items_per_page; }
                        else
                            { new_total = total_item_count; }
                        
                        // update total count display
                        totalCount.text( ((page_id * items_per_page) + 1) + ' - ' + new_total);
					}
				});
			});
			return false;
        }
    };
};


/*
 * @description:    very simple accordion for the sidebar
 *               
 */
HYDRA.Accordion =   function( sidebarId )
{
    var cc          =   this;
    this.sidebarId  =   $('#'+sidebarId);
    this.headers    =   $('.title > a');
    this.contents   =   $('.contents');
    
    this.contents.not('.current').hide();
    
    this.headers.click( function()
    {
        if($(this).parent().next().css('display') !== 'block' )
        {
            cc.contents.slideUp();
            $(this).parent().next().slideToggle();
        }
        
       return false;
    });
};