$(function() {
	showFlashMessage();
	
    // Initalise resources menu.
    objResourcesMenu.init();
    
    // Initalise sidebar resources list on resources pages.
    objResourcesList.init();
    
    // Initialise JS functionality relating to groups.
    objGroups.init();
    
    // Initialise JS functionality relating to messages.
    objMessages.init();
});

/* Code relating to the horizontal resources menu that appears near the top of each page. */
var objResourcesMenu = {
    init: function() {
        var domResourcesMenu = $('#resources-menu').get();
        
        // Remove right-most resource menu's right border.
        $(domResourcesMenu).find('.resource-menu-root-wrap:last .resource-menu-root').css('border-right', '0 none');
        
        // Limit expanded menu's height to 300px, hiding those outside this height.
        // Stick a 'more' button at end of each list that has hidden elements to expand list completely.
        function displayMoreButtons() {
            $(domResourcesMenu).find('li:visible').each(function() {
                $(this).each(function() {
                    if($(this).position().top > 300) {
                        $(this).hide();
                        $(this).parent('ul').find('.more').show();
                        $(this).parent('ul').data('truncated', true);
                    }
                });
            });
        }
        displayMoreButtons();
        
        // Display all resource menu links after clicking a 'More...' button
        $(domResourcesMenu).find('li.more').click(function(e) {
            e.preventDefault();
            
            // Cache the height of the menu after being expanded, but before hitting "More".
            $(domResourcesMenu).data('intTruncatedHeight', $(domResourcesMenu).height());
            
            // Fade links in (or show immediately, if using IE, to avoid dodgy blur effect).
            if($.browser.msie) {
                $(domResourcesMenu).find('li').not('.toggle').show();
            } else {                
                $(domResourcesMenu).find('li').not('.toggle').fadeIn();
            }
            
            // Replace each "More..." button with a "Less..." button.
            $(domResourcesMenu).find('li.more').hide();
            $(domResourcesMenu).find('ul').each(function() {
                if($(this).data('truncated') === true) {
                    $(this).find('li.less').show();
                }   
            });
            
            $(domResourcesMenu).find('.resource-menu-root').height('100%');
            setResourceMenuHeights();
            $(domResourcesMenu).height('auto');
            $(domResourcesMenu).addClass('open');
        });
        
        // Return menu to its fully closed state after clicking 'Less...'
        $(domResourcesMenu).find('li.less').click(function(e) {
            e.preventDefault();
            
            $(domResourcesMenu).removeClass('open');
            $(domResourcesMenu).find('li.less').hide();
            displayMoreButtons();
            $(domResourcesMenu).find('.resource-menu-root').height('auto');
            setResourceMenuHeights();
        });
        
        // Calculate height of tallest resource menu, and set all resource menus
        // to the tallest height, so that their borders are all the same height.
        function setResourceMenuHeights() {
            var intTallestListHeight = Math.max.apply(this, $(domResourcesMenu).find('.resource-menu-root-wrap').map(function() { return $(this).height(); }).get());
            $(domResourcesMenu).find('.resource-menu-root').height(intTallestListHeight);
            return intTallestListHeight;
        }
        
        // On hover, expand menu to display links. Using the hoverIntent plugin to delay hover event.
        $(domResourcesMenu).hoverIntent({
            timeout: 300,
			interval: 400,
            over: function() {
                if(!$(domResourcesMenu).hasClass('open')) {
                    displayMoreButtons();
                    $(this).removeClass('closed');
                    $(domResourcesMenu).find('.resource-menu-root').height('auto');
                    var intTallestListHeight = setResourceMenuHeights();
                    
                    if($.browser.msie && $.browser.version === '6.0') {
                        $(domResourcesMenu).css({ height: intTallestListHeight });
                    } else {
                        $(domResourcesMenu).animate({ height: intTallestListHeight });
                    }
                }
            },
            out: function() {
                if(!$(domResourcesMenu).hasClass('open')) {
                    if($.browser.msie && $.browser.version === '6.0') {
                        $(domResourcesMenu).css({ height: '20px' });
                        $(domResourcesMenu).addClass('closed');
                    } else {
                        $(domResourcesMenu).animate({ height: '20px' }, function() {
                            $(domResourcesMenu).addClass('closed');
                        });
                    }
                }
            }
        });
    }
}


var objResourcesList = {
    init: function() {
        $('#resources-list li .expander').click(function(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).parent('li').toggleClass('open').toggleClass('closed');
        });
    }
}


var objGroups = {
    init: function() {
        $('.group .toggle-group-notifications input[type=checkbox]').change(function(e) {
            $.ajax({
                url: $(this).attr('href'),
                data: {
                    show_notifications: Number($(this).is(':checked')),
                    group_id: parseInt($(this).closest('.group').attr('group'), 10)
                },
                type: 'POST',
                dataType: 'json',
                success: function(objResponse) {
                    if(!objResponse || objResponse.blnSuccess === false) {
                        $(e.target).attr('checked', !$(e.target).is(':checked'));
                    } else if(objResponse && objResponse.blnSuccess === true) {
                        // On the 'view group' page, set all message notification toggles to same value.
                        $('#messageWrapper .toggle-message-notifications input[type=checkbox]').attr('checked', $(e.target).is(':checked'));
                    }
                }
            });
        });
        
        // Allow drag-and-drop ordering of group information pages.
        if('sortable' in $.fn) {
            $('#group-information-pages').find('.scrollable-content ul.sortable').sortable({
                placeholder: "ui-state-highlight",
				handle: '.handle',
                stop: function(e, ui) {
                    var objPageOrder = {};
                    $(this).find('li').each(function(i, domLi) {
                        objPageOrder[i] = {
                            intPageId: parseInt($(domLi).attr('page'), 10),
                            intPageOrder: i
                        }
                    });
                    
                    $.ajax({
                        url: strSetPageOrdersURL,
                        type: 'POST',
                        data: objPageOrder,
                        dataType: 'json',
                        success: function(objResponse) {
                            if(objResponse && objResponse.blnSuccess) {
                                
                            }
                        }
                    });
                }
            }).disableSelection();

			$('.handle').hide();

			$('.sortable li').mouseover(function() {
				$(this).find('.handle').show();
			});
			
			$('.sortable li').mouseout(function() {
				$(this).find('.handle').hide();
			});
        }
		
		// Remove the association between an upload and this group.
		$('#group-shared-files .unshare-file').click(function(e) {
			e.preventDefault();
			
			var intGroupId = parseInt($(this).closest('.group').attr('group'), 10);
			var intUploadId = parseInt($(this).parents('li').attr('upload'), 10);
			
			$.ajax({
				url: '/groups/ajaxUnshareFile',
				type: 'POST',
				data: {
					group_id: intGroupId,
					upload_id: intUploadId
				},
				dataType: 'json',
				success: function(objResponse) {
					if(('blnSuccess' in objResponse) && objResponse.blnSuccess) {
						$('#group-shared-file-'+intUploadId).fadeOut('slow', function() {
							$(this).remove();
						});
					}
				}
			})
		});
		
		// Remove the association between a message and this group.
		$('#group-messages .unshare-message').click(function(e) {
			e.preventDefault();
			
			var intGroupId = parseInt($(this).closest('.group').attr('group'), 10);
			var intMessageId = parseInt($(this).parents('.message').attr('message'), 10);
			
			$.ajax({
				url: '/groups/ajaxUnshareMessage',
				type: 'POST',
				data: {
					group_id: intGroupId,
					message_id: intMessageId
				},
				dataType: 'json',
				success: function(objResponse) {
					if(('blnSuccess' in objResponse) && objResponse.blnSuccess) {
						$('#group-message-'+intMessageId).fadeOut('slow', function() {
							$(this).remove();
						});
					}
				}
			})
		});
    }
}


var objMessages = {
    init: function() {
        $('.message .toggle-message-notifications input[type=checkbox]').change(function(e) {
            $.ajax({
                url: $(this).attr('href'),
                data: {
                    show_notifications: Number($(this).is(':checked')),
                    message_id: parseInt($(this).closest('.message').attr('message'), 10)
                },
                type: 'POST',
                dataType: 'json',
                success: function(objResponse) {
                    if(!objResponse || objResponse.blnSuccess === false) {
                        $(e.target).attr('checked', !$(e.target).is(':checked'));
                    }
                }
            });
        });
    }
}

var showMore = function(strDivId, objLink) {
	$('#' + strDivId).toggle('slow');
			
	if($(objLink).attr('class') == 'upArrow'){
		$(objLink).removeClass('upArrow');
		$(objLink).addClass('downArrow');
	}else{
		$(objLink).removeClass('downArrow');
		$(objLink).addClass('upArrow');
	}
}

function showFlashMessage() {
	intOffScreen = -1 * ($('#flash-message').height() + 10);
	$('#flash-message')
		.css('top', intOffScreen + 'px')
		.show()
		.animate({top: 0}, function() {
			 setTimeout(function() {
				$('#flash-message').animate({top: intOffScreen}, function() {
					$(this).remove();
				});
			}, 10000);
		});
}

