/*-***********************************-*
 * Learnosity Common JavaScript
 *-***********************************-*/
$(function () {
    // Global focus on user name input if found
	$('.username:first').focus();
    
    $('#langselect').change(function() {
        window.location.href = $(this).attr('data-langselect') + this.value;
    });
    
    /* Generic include of jQueryUI Calendar (override with custom global class) */    
    $(".datepicker").datepicker({
    	dateFormat: 'yy-mm-dd',
    	constrainInput: true
    }); 

	// Slide() bug workaround: http://jqueryfordesigners.com/slidedown-animation-jump-revisited/
    // To be moved into a Learnosity wrapper
    var $div = $('.searchform').css('visibility','hidden').show();
    var height = $div.height();
    $div.hide().css({ height : 0 }).css('visibility','visible');

    $('.searchform_show').click(function () {
        if ($div.is(':visible')) {
            $(this).html('Refine Search<span class="arrowdown"></span>');
            $div.animate({ height: 0 }, { duration: 500, complete: function () {
                $div.hide();
            } });
        } else {
            $(this).html('Close Search<span class="arrowup"></span>');
            $div.show().animate({ height : height }, { duration: 500 });
        }	        
        return false;
    });

    /* Hack creating links on Datagrids till we can refactor it's output HTML */
	$('.datagrid tbody tr').click(function(event) {
        var firstCell = $($(this).children('td')[0]);
        var link = firstCell.children('a')[0];
        var checkbox = firstCell.children('input[type="checkbox"]')[0];

        if(link && !$(event.target).is(':checkbox')) {
            window.location.href = link.href;            
        } else if(checkbox && !$(event.target).is(':checkbox')) {
            if ($(checkbox).is(':checked')) {
                $(checkbox).attr('checked', '');
            } else {
                $(checkbox).attr('checked', 'checked');
            }
        }
	});
    
    /* Hack to fire search button even if it's not the first submit in the form */    
    $('.searchform').keypress(function(e) {
        if (e.which == 13) {
            e.preventDefault();
            $('button:last').click();
        }
    });
});

