// global namespace to keep variables clean
//
var HYDRA = {};

// Encapsulate this to be able to use jQuery in no conflicts mode and still use the $ name
(function () {
    var currentSlide = 0;
    var $ = jQuery;
    /**
     * Remove the link that the user tried removing, or clear the input
     * boxes if there is only one link input remaining in the form. Also,
     * if they clear the first input then hide the remove link
     */
    function profile_link_remove ()
    {
        var linkrows = $('.add_link');
        var link = $(this).parent().parent().parent();
        
        if ( linkrows.length > 1 )
        {
            // Remove the fieldset that holds this link
            link.remove();
        }
        else
        {
            // Clear out input boxes in this row
            link
                .find('input').each(function() {
                    $(this).val('');
                });
                
            // Hide the remove link
            $(this).hide();
        }
        
        // Don't allow the link event to continue
        return false;
    }
    
    /**
     * Shows or hides the story and images fields for the contribute form
     * depending on the contribute type selected
     */
    function contribute_inputs () {
        if ( $('#contribute_type').length > 0 )
        {
            if ( $('#contribute_type').val().match(/Story/) )
            {
                $('.contribute_story').show();
            }
            else
            {
                $('.contribute_story').hide();
            }
            
            if ( $('#contribute_type').val().match(/Images/) )
            {
                $('.contribute_image').show();
            }
            else
            {
                $('.contribute_image').hide();
            }
        }
           
        return true;
    }
    
    // Starting slide for image cycle
    // This will be overriden in any template that shows an image gallery
    // if the starting image needs to be different
    HYDRA.starting_slide = 0;
    HYDRA.current_brief = 1;
    
    //  once the document is loaded
    //
    $( document ).ready( function() {
	    
        //////////////
        // set up tabs
        //
        $('.tabs').tabs({ fx: {opacity: 'toggle', duration: 150 } });
    
    
    
        ////////////////////
        // hide comment form
        //
        $('#form_comment').hide();
    
    
    
        //////////////////////
        // expand comment form
        //
        $('.open_comment .open_comment').toggle(
            
            function() { $(this).parent().parent().find('#form_comment').slideDown('fast'); },
            function() { $(this).parent().parent().find('#form_comment').slideUp('fast'); }
        
        );
        
        /////////////
        // slideshows
        //
        $('#albumimage.slideshow > dt').cycle({ 
            
            fx:     'fade', 
            speed:  'slow', 
            timeout: 0, 
            next:   '.forward', 
            prev:   '.previous',
            startingSlide: HYDRA.starting_slide,
                    
            before: onBefore = function() {
                $('#albumimage.slideshow .caption').html($(this).find('img').attr('alt'));
            },
            
            after:  onAfter = function() {
                
                // increase slide count
                HYDRA.slide_count++;
                    
                $('#albumimage.slideshow .caption').html(this.alt);
            
            }
            
            // adjusting the currentSlide count
            // and rendering the total number of slides
            // are both handled in the cycle.js file
            // with custom HYDRA calls
            
        });

        // ///////////////////
        // // LARGE slideshows
        // //
        $('#albumimage.slideshow_large > dt').cycle({ 
            
            fx:     'fade', 
            speed:  'slow', 
            timeout: 0, 
            next:   '.forward', 
            prev:   '.previous',
            startingSlide: HYDRA.starting_slide,
                    
            before: onBefore = function() {
                $('#albumimage.slideshow_large .caption').html($(this).attr('alt'));
            },
            
            after:  onAfter = function() {
                
                // increase slide count
                HYDRA.slide_count++;
                    
                $('#albumimage.slideshow_large .caption').html($(this).attr('alt'));
            
            }
            
            // adjusting the currentSlide count
            // and rendering the total number of slides
            // are both handled in the cycle.js file
            // with custom HYDRA calls
            
        });

        $('#albumvideo.slideshow_large > dt ').cycle({ 
            
            fx:     'fade', 
            speed:  'slow', 
            timeout: 0, 
            next:   '.forward', 
            prev:   '.previous',
            startingSlide: HYDRA.starting_slide,
                    
            before: onBefore = function() {
                $('#albumvideo.slideshow_large .caption').html($(this).find('.video').attr('title'));
            },
            
            after:  onAfter = function() {
                
                // increase slide count
                HYDRA.slide_count++;
                    
                $('#albumvideo.slideshow_large .caption').html($(this).find('.video').attr('title'));
            
            }
            
            // adjusting the currentSlide count
            // and rendering the total number of slides
            // are both handled in the cycle.js file
            // with custom HYDRA calls
        });



// AlbumVideo for GA 2009 Page
        $('#albumvideo2.slideshow_large > dt ').cycle({ 
            
            fx:     'fade', 
            speed:  'slow', 
            timeout: 0, 
            pager:  '#albumvideo2.slideshow_large dd ul',            
            startingSlide: HYDRA.starting_slide,
                    
            before: onBefore = function() {
                $('#albumvideo2.slideshow_large .caption').html($(this).find('.video').attr('title'));
            },
            
            after:  onAfter = function() {
                
                // increase slide count
                HYDRA.slide_count++;
                    
                $('#albumvideo2.slideshow_large .caption').html($(this).find('.video').attr('title'));
            
            },

            pagerAnchorBuilder: function(idx, slide) {
                return '#albumvideo2.slideshow_large #' + slide.id + '_thumb'; 
            }

            
            // adjusting the currentSlide count
            // and rendering the total number of slides
            // are both handled in the cycle.js file
            // with custom HYDRA calls
        });



        // Special slideshow for new multimedia page

        $('#albumvideo.slideshow_large_index > dt').cycle({ 
            
            fx:     'fade', 
            speed:  'slow', 
            timeout: 0, 
            next:   '.forward', 
            prev:   '.previous',
            startingSlide: HYDRA.starting_slide,
                    
            before: onBefore = function() {
                $('#albumvideo.slideshow_large_index .caption').html($(this).find('.video').attr('title'));
            },
            
            after:  onAfter = function() {
                
                // increase slide count
                HYDRA.slide_count++;
                    
                $('#albumvideo.slideshow_large_index .caption').html($(this).find('.video').attr('title'));
            }  
            
            // adjusting the currentSlide count
            // and rendering the total number of slides
            // are both handled in the cycle.js file
            // with custom HYDRA calls
            
        });

        $('#albumvideo.slideshow_large_index .previous').click(function(){
            if (currentSlide == 0){
	            totalSlides = $('#albumvideo.slideshow_large_index').find('`object`').size() - 1;
	            currentSlide = totalSlides;
            } else {
	            currentSlide = currentSlide -1;
            }
            var id = $('.video_block:eq(' + currentSlide + ')').find('object').attr('id'); 
            id = id.substr(9);            
            $('.article_sharing_link').attr('id', 'article_sharing_link_' + id);
        });

        $('#albumvideo.slideshow_large_index .forward').click(function(){

            if (currentSlide == $('#albumvideo.slideshow_large_index').find('object').size() - 1){
	            currentSlide = 0;
            } else {
	            currentSlide = currentSlide +1;
            }
            var id = $('.video_block:eq(' + currentSlide + ')').find('object').attr('id');
            id = id.substr(9);
            $('.article_sharing_link').attr('id', 'article_sharing_link_' + id);
        });

        ///////////////////
        // Featured multimedia
        //
        $('.featuredmedia div.image').cycle({ 
            
            fx:     'fade', 
            speed:  'slow', 
            timeout: 0, 
            pager:  '.featuredmedia dd ul',
            
            before: onBefore = function () {
                if ($(this).find('img').attr('alt') == null){
                    $('.featuredmedia .caption p').css('display','none'); 
                } else {

                    $('.featuredmedia .caption p').html($(this).find('img').attr('alt'));
                    $('.featuredmedia .caption p').css('display','block');

                }        


                if (typeof lastFeatureMedia != 'undefined' 
                    && lastFeatureMedia != this
                    && $(lastFeatureMedia).find('.video').length > 0) {
                    $(lastFeatureMedia).find('.video').hide();
                }
                
                lastFeatureMedia = this;
            },
            
            after: onAfter = function () {
                HYDRA.slide_count++;
                
                $('.featuredmedia .caption p').html($(this).find('img').attr('alt'));

                if ($(this).find('.video').length > 0) {
                    var cur = this;
                    
                    if (parseInt($('#featuremediaView').css('height')) == 287) {
                        $('#featuremediaView').animate({
                                height: '359px'
                            }, 
                            "normal",
                            "linear",
                            function () {
                                $(cur).find('.video').show();
                            }
                        );
                        $('#featuremediaScroll').animate({
                            height: '293px'
                        });
                    }
                } else {
                    if (parseInt($('#featuremediaView').css('height')) == 359) {
                        $('#featuremediaView').animate({
                            height: '287px'
                        });
                        $('#featuremediaScroll').animate({
                            height: '221px'
                        });
                    }
                }
            },
                    
            pagerAnchorBuilder: function(idx, slide) {
                return '.featuredmedia #' + slide.id + '_thumb'; 
            }
        });
        
        var featuredScrollVelocity = 100; // pixels per second
        
        ///////////////////////////////
        // Featured multimedia scroller
        //
        $('#featured_down').mouseover(function () {
            var el = $('.featuredmedia ul');
            var d = (el.get(0).scrollHeight - el.height()) - el.get(0).scrollTop;
            
            // calculate speed
            var t = d / (featuredScrollVelocity / 1000);
            
            $('.featuredmedia ul').animate({scrollTop: el.get(0).scrollHeight}, t, "linear");
        });
        $('#featured_down').mouseout(function () {
            $('.featuredmedia ul').stop();
        });
        $('#featured_down').click(function () {
            return false;
        });
        
        $('#featured_up').mouseover(function () {
            var el = $('.featuredmedia ul');
            var d = el.get(0).scrollTop;
            
            // calculate speed
            var t = d / (featuredScrollVelocity / 1000);
            
            $('.featuredmedia ul').animate({scrollTop: 0}, t, "linear");
        });
        $('#featured_up').mouseout(function () {
            $('.featuredmedia ul').stop();
        });
        $('#featured_up').click(function () {
            return false;
        });
        
        /////////////////////////
        // paginating news briefs
        //
        var briefs_count = $('#briefs_cycle .listings_alt').length;
    
        // Set up auto paginate timer for briefs
        HYDRA.nextBriefAuto = true;
        HYDRA.nextBriefTimer = setTimeout(function () { HYDRA.nextBrief(); }, 30000);
        
        // Add nextBrief function to the global namespace so that it can be used by timers
        HYDRA.nextBrief = function ( )
        {
        
    	    if(HYDRA.close_news === true)
    	    {
    	        if(HYDRA.current_brief >= briefs_count){
    	            
    	            $('#brief_list_' + HYDRA.current_brief).fadeOut(
    	                300,
    	                function()
    	                {
    	                    HYDRA.current_brief = 1;
    	                    $('#brief_list_' + HYDRA.current_brief).fadeIn(300);
    	                }
    	            );
    	        }
    	        else
    	        {
    	            $('#brief_list_' + HYDRA.current_brief).fadeOut(
    	                300,
    	                function() {
    	                    HYDRA.current_brief += 1;
    	                    $('#brief_list_' + HYDRA.current_brief).fadeIn(300);
    	                }
    	            );
    	        }
    	    }
    	    
    	    if ( HYDRA.nextBriefAuto === true )
    	    {
    	       HYDRA.nextBriefTimer = setTimeout(function () { HYDRA.nextBrief(); }, 30000);
    	    }
    	    
    	    return false;
    	    
    	};
    	
    	// Stop auto pagination
    	HYDRA.nextBriefStopTimer = function ( )
    	{
    	   
    	   HYDRA.nextBriefAuto = false;
    	   clearTimeout(HYDRA.nextBriefTimer);
    	};
    
        
        // hide list, show first item
        $('#briefs_cycle .listings_alt').hide();
        $('#briefs_cycle #brief_list_1').show();
        
        // functions for clicking next
        $('#next_brief').click(
            
            function() {
                
                // Stop auto scrolling
                HYDRA.nextBriefStopTimer();
                
                // Paginate
                return HYDRA.nextBrief();
        
            }
            
        );
        
        // functions for clicking prev
        $('#prev_brief').click(
        
            function() {
            
                // Stop auto scrolling
                HYDRA.nextBriefStopTimer();
                
                if(HYDRA.close_news === true)
                {
                    if(HYDRA.current_brief == 1)
                    {    
                        $('#brief_list_' + HYDRA.current_brief).fadeOut(
                            300,
                            function() {
                                HYDRA.current_brief = briefs_count;
                                $('#brief_list_' + HYDRA.current_brief).fadeIn(150);
                            }
                        );
                    }
                    else
                    {
                        $('#brief_list_' + HYDRA.current_brief).fadeOut(
                            300,
                            function() {
                                HYDRA.current_brief -= 1;
                                $('#brief_list_' + HYDRA.current_brief).fadeIn(150);
                            }
                        );
                    }
                }
                return false;
            }
        );
        
        ////////////////
        // View All News
        
        $('#view_all_news a').click(
        
            function() {
            
                // Stop auto scrolling
                HYDRA.nextBriefStopTimer();
                
                if( HYDRA.close_news === true )
                {
                    // expand lists
                    HYDRA.current_brief = 1;
                    $(this).parent().parent().find('.listings_alt').slideDown(200);
                    HYDRA.close_news = false;
                    $('#nav_briefs').fadeOut(150);
                    $(this).html('Close');
                    $(this).css('background-image','url(img/layout/button_up.gif)');
                }
                else
                {
                    // close lists
                    $(this).parent().parent().find('ul:not(#brief_list_1)').slideUp(200);
                    HYDRA.current_brief = 1;
                    //$(this).parent().parent().find('#brief_list_1').fadeIn(150);
                    HYDRA.close_news = true;
                    $('#nav_briefs').fadeIn(150);
                    $(this).html('View All');
                    $(this).css('background-image','url(img/layout/button_down.gif)');
                }
                
                return false;
            
            }
        
        );
        
        
        // Stop the timer on click to the latest briefs widget
        $("#latest_briefs").click(
            
            function() {
            
                HYDRA.nextBriefStopTimer();
                
            }
            
        );
        
        HYDRA.close_news = true;
    
    
        /////////////////////////
        // Article sharing widget
        //
        $('.article_sharing_link').click(
            function () 
            {
                // Fetch the ID for the article being shared
                var entry_id = this.id.match(/article_sharing_link_([0-9]+)/)[1];
                var widget = $('#article_sharing_' + entry_id);
                
                if ( widget.is(':hidden') )
                {
                    // Set up the widget position based on the clicked link
                    var top = $(this).offset().top;
                    var left = $(this).offset().left;
                    
                    // Class under on the link specifies that the link should be under the widget
                    if ($(this).hasClass('under'))
                    {
                        top -= (widget.height() + $(this).height());
                    }
                    else
                    {
                        top += $(this).height() + 5;
                    }
                    
                    // Moving the widget to the root of body so its at the same level in the hiearchy as the overlay
                    // Also top and left position will be based on body instead of the current parent div
                    $('body').append(
                        widget
                            .css('z-index', 6002)
                            .css('left', $(this).offset().left)
                            .css('top', top)
                            .fadeIn()
                    );
                    
                    // Create an overlay div that takes up the whole screen but sits under this widget
                    // with a click event handler that will close the widget and destroy the overaly
                    $('body').append('<div id="overlay"></div>');
                    $('#overlay')
                        .css('position', 'fixed')
                        .css('left', 0)
                        .css('top', 0)
                        .width($('body').width())
                        .height($('body').height())
                        .css('z-index', 6001)
                        .click(function () {
                            if ( !widget.is(':hidden') )
                            {
                                widget.fadeOut(); 
                            }
    
                            $('#overlay').remove();
                        });
    
    				// Add event for Close link
    				widget.find('.article_sharing_close').click(function () {
    					widget.fadeOut();
    				});
    
                    return false;
                }
            }
        );
        
        
        //////////////////////////////////////////
        // Update share count for social bookmarks
        //
        $('.social_bookmark_link').click(
            function () {
                // send post to update_share_count action
                var ACT = 26;
                var url_title = $('#url_title').val();
                
                $.post(window.location + '?ACT=' + ACT,
                    {
                        url_title: url_title
                    }
                );
            }
        );
        
        
        /////////////////////////////////////////
        // clear/unclear search box on focus/blur
        //
        $('#search_keyword')
            .focus(
                function () {
                    if ($(this).val().match(/^Search\s.*/))
                    {
                    	HYDRA.searchBar = $(this).val();
                    	jta_search_keyword_color = $(this).css('color');
                    	$(this).val('').css('color', 'black');
                    }
                }
            )
            .blur(
                function () {
                    if ($(this).val() === '')
                    {
                        $(this).val(HYDRA.searchBar).css('color', jta_search_keyword_color);
                    }
                }
            );
            
            
        /////////////////////////////
        // privacy settings checkboxs
        //
        if( $('#account_privacy').attr('checked') )
        {
            $(document).find('.check_alls').show();
        }    
        else
        {
            $(document).find('.check_alls').hide();
        }
            
        // Show and hide sub-checkboxes
        $('#account_privacy').click( function() {
            
            var checkedValue = $('#account_privacy').attr('checked') ? 'checked' : '';
            
            // check all
            if( $(this).attr('checked') )
            {    
                $(document).find('.check_alls').show();
            }
            // uncheck all
            else
            {
                $(document).find('.check_alls').hide();
            }
        }); 
        
        /////////////////////////////
        // Handle adding new link boxes on profile settings page
        //
        $('#profile_link_add').click(
            function() {
                var linkrows = $('.add_link');
                var linkrow = {};
                
                // Get the last link id
                var id = 1;
                linkrows.each(function() {
                    id = $(this).find('[name^=link_title]').attr('id').match(/link_title_([0-9]+)/)[1];
                    linkrow = this;
                });
                
                // Create a clone of the last link row
                linkrow = $(linkrow).clone().insertAfter(linkrow);
                
                // Set the next id for the new linkrow
                $(linkrow).find('[name^=link_title]').attr('id', 'link_title_' + (++id));
                
                // Make sure all inputs are cleared
                $(linkrow).find('input').val('');
                
                // Make sure remove button is visible
                $(linkrow).find('a').show().click(profile_link_remove);
                
                // Don't allow the link event to continue
                return false;
            }
        );
        
        
        /////////////////////////////
        // Handle link removal
        //
        $('.add_link a').click(profile_link_remove);
        
        // Create event to show hidden comments
        //
        $('.comment_toggle').click (
            function () {
                var id = $(this).attr('id').match(/comment_toggle_([0-9]+)/)[1];
                
                if ( id )
                {
                    var content = $('#comment_content_' + id);
                    if ( content.is(':hidden') )
                    {
                        content.slideDown();
                        $(this).html('Hide');
                    }
                    else
                    {
                        content.slideUp();
                        $(this).html('Show');
                    }
                }
                
                // Don't let the link event continue
                return false;
            }
        );
        
        /////////////////////////////
        // Create event for the contribute type dropdown
        // It will hide or show the story/image fields depending on the selected option
        //
        $('#contribute_type').change (function () {
            contribute_inputs();
        });
        
        // Also, load the proper contribute type on page load
        if ( $('#contribute_type') )
        {
            contribute_inputs();
        }
        
        /////////////////////////////
        // Create event for contribute image add
        //
        $('#contribute_image_add').click (
            function () {
                var rows = $('.contribute_image_input');
                
                // Insert new row
                $(rows[0])
                    .clone()
                    .insertAfter(
                        $(rows[rows.length-1])
                );
                
                // Clear new row's value
                $('.contribute_image_input:last').find('input')
                    .val('');
                
                return false;
            }
        );

        /////////////////////////////
        // Handle login labels
        //
        // Set the proper values on load
        if ($('#ambush_login_email').length > 0) 
        {
            login_reset($('#ambush_login_email').get(0), 'Email');
            login_reset($('#ambush_login_password').get(0), 'Password', true);
        }
        
        $('#ambush_login_email').focus(function () {
            login_reset(this, 'Email');
        });
        $('#ambush_login_email').blur(function () {
            login_reset(this, 'Email');
        });
        
        $('#ambush_login_password').focus(function () {
            login_reset(this, 'Password', true);
        });
        $('#ambush_login_password').blur(function () {
            login_reset(this, 'Password', true);
        });
        
        $('#ambush_signup_email').focus(function () {
            login_reset(this, 'Email');
        });
        $('#ambush_signup_email').blur(function () {
            login_reset(this, 'Email');
        });
           
        function login_reset (input, val, pass_field, original_type)
        {
            if (input.value == val)
            {
                input.value = '';
                $(input).css('color', '#4D4D4D');
                
                if (pass_field === true)
                {
                    replace_pass_field(input, val, 'password');
                }
            }
            else if (input.value === '')
            {
                input.value = val;
                $(input).css('color', '#999');
                
                if (pass_field)
                {
                    replace_pass_field(input, val, original_type);
                }
            }
        }
        
        function replace_pass_field (input, val, type)
        {
            // See comments in the block above
            var new_input = $('<input type="' + type + '">')
                .attr('id', 'ambush_login_password')
                .attr('name', 'password')
                .addClass('text_input')
                .val(input.value);
            
            $(input).replaceWith(new_input);
            
            // Cannot focus until the element is actually rendered
            if (type == 'password')
            {
                new_input.focus();
                
                // Add blur to revert back to text
                new_input.blur(function () {
                    login_reset(this, val, true, 'text');
                });
            }
            else
            {
                new_input.focus(function () {
                    login_reset(this, val, true);
                });
            }
        }
        
        
        /////////////////////////////
        // Handle friend requests
        //
        $('#approve_all').click(function () {
            var checked = this.checked;
            
            $('#deny_all').attr('checked', false);
            
            $('.deny_request').each(function () {
                this.checked = false;
            });
            
            $('.approve_request').each(function () {
                this.checked = checked;
            });
        });
        $('#deny_all').click(function () {
            var checked = this.checked;
            
            $('#approve_all').attr('checked', false);
            
            $('.approve_request').each(function () {
                this.checked = false;
            });
            
            $('.deny_request').each(function () {
                this.checked = checked;
            });
        });

        $('#select_all').click(function () {
            var checked = this.checked;

            $('.delete_message').each(function () {
                this.checked = checked;
            });
        });
        
        $('.approve_request').click(function () {
            // get record numeric id
            var id = this.id.match(/(\d+)$/)[0];
            $('#deny_' + id).attr('checked', false);
        });
        
        $('.deny_request').click(function () {
            // get record numeric id
            var id = this.id.match(/(\d+)$/)[0];
            $('#approve_' + id).attr('checked', false);
        });
        
        $('.deny_request').click(function () {
            // get record numeric id
            var id = this.id.match(/(\d+)$/)[0];
            $('#approve_' + id).attr('checked', false);
        });
        
        
        $('.myprofile').hover(
            function () {
                $(this).find('.profilenav').show();            
            },
            function () {
                $(this).find('.profilenav').hide();
            }
        );
        
        $('.delete_friend').click(function () {
            if ( !confirm("Are you sure you want to delete this friend?") )
            {
                return false;
            } 
        });
	
        /////////////////////////////
        // Handle image cropper
        //
        if ($('#jcrop').length > 0)
        {
            $('#jcrop').Jcrop({
    			onChange: jcropPreview,
    			onSelect: jcropPreview,
    			aspectRatio: 1,
    			setSelect: [0, 0, 100, 100],
    			boxWidth: 500,
    			boxHeight: 500
    		});
    		
    		function jcropPreview (coords)
    		{
    			var rx = 100 / coords.w;
    			var ry = 100 / coords.h;
    
    			$('#jcrop_preview').css({
    				width: Math.round(rx * $('#jcrop').width()) + 'px',
    				height: Math.round(ry * $('#jcrop').height()) + 'px',
    				marginLeft: '-' + Math.round(rx * coords.x) + 'px',
    				marginTop: '-' + Math.round(ry * coords.y) + 'px'
    			});
    			
    			$('#jcrop_input_x1').val(coords.x);
    			$('#jcrop_input_y1').val(coords.y);
    			$('#jcrop_input_x2').val(coords.x2);
    			$('#jcrop_input_y2').val(coords.y2);
    		}
        }

    }); //  end of ducument ready
    
    $('#jta_welcome_hide').click(function () {
        var date = new Date();
        date.setTime(date.getTime()+(10*365*24*60*60)); // 10 years
        document.cookie = "exp_jta_welcome=1; expires=" + date.toGMTString() +"; path=/";
        
        $('#jta_welcome').animate({
            opacity: 0,
            height: 0
        });
        
        return false;
    });    

})();