var _clientLogoImageIndex = null;

$(document).ready(function() {
    
    if (typeof document.loginBoxOpened == 'undefined') {
        document.loginBoxOpened = false;
    }
    
    $('#topmenu a, #sidemenu a').each(function() {
        var a = $(this);
        if (a.attr('href') == '.' || a.attr('href') == '/') {
            if (/^\/(.*\/)?$/.test(window.location.pathname) && window.location.pathname.indexOf('blog/') == -1) {
                a.addClass('selected');
            }
        } else if (window.location.pathname.indexOf(a.attr('href')) != -1) {
            a.addClass('selected');
        }
    });
        
    // Saving active state while new page loads
    $('#topmenu a').click(function() {
        var a = $(this);
        var hash = (a.attr('href').indexOf('#') !== -1) ? a.attr('href').substr(a.attr('href').indexOf('#')) : '';
        if (!a.hasClass('selected') && hash != '#' && (hash == '' || hash != '' && window.location.hash != hash)) {
            a.addClass('active');
        }
    });
    
    // Login form dropdown hover fix
    $('#topmenu a:last').click(function() {
        openLoginBox();
        if (!document.loginBoxOpened) {
            $(this).removeClass('active');
        }
        return false;
    });
    
    // IE button hover fix
    if ($.browser.msie) {
        $('.btn-login').mouseover(btnHover).mouseout(btnHover);
        $('.btn-sendpwd').mouseover(btnHover).mouseout(btnHover);
        $('.btn-try').mouseover(btnHover).mouseout(btnHover);
        $('.btn-learnmore').mouseover(btnHover).mouseout(btnHover);
    }
    
    $('#loginForm .btn-login').click(submitLoginForm);
    $('#pwdRecoveryForm .btn-sendpwd').click(submitRecoveryForm);
    
    // Home page actions
    if ($('body').attr('id') == 'home') {
        
        // Show login form on the home page after 2 seconds after load
        window.setTimeout(function() {
            openLoginBox(false);
        }, 2000);
        
        $('#clientLogo img').shuffle();
        clientLogoRoll();
    }
    
    $('div.fixed-height').each(function() {
        
        var i, col1bh, col2bh, col3bh, rh, div = $(this);
        
        var col1_Blocks = $('div.col-1 .cblock-content', div).toArray();
        var col2_Blocks = $('div.col-2 .cblock-content', div).toArray();
        var col3_Blocks = $('div.col-3 .cblock-content', div).toArray();
        var maxRows     = Math.max(col1_Blocks.length, col2_Blocks.length, col3_Blocks.length);
        
        for (i = 0; i < maxRows; ++i) {
            
            col1bh  = (typeof col1_Blocks[i] != 'undefined') ? $(col1_Blocks[i]).height() : 0;
            col2bh  = (typeof col2_Blocks[i] != 'undefined') ? $(col2_Blocks[i]).height() : 0;
            col3bh  = (typeof col3_Blocks[i] != 'undefined') ? $(col3_Blocks[i]).height() : 0;
            rh      = Math.max(col1bh, col2bh, col3bh);
            
            if (typeof col1_Blocks[i] != 'undefined') {
                $(col1_Blocks[i]).height(rh);
            }
            
            if (typeof col2_Blocks[i] != 'undefined') {
                $(col2_Blocks[i]).height(rh);
            }
            
            if (typeof col3_Blocks[i] != 'undefined') {
                $(col3_Blocks[i]).height(rh);
            }
            
        }
        
        $('.cblock-corner-bl, .cblock-corner-br').css({'bottom': 0});
        
    });
    
    createShadows();
    
});

function btnHover() {
    var b = $(this);
    if (!b.hasClass('hover')) {
        b.addClass('hover');
    } else {
        b.removeClass('hover');
    }
}

function openLoginBox(bFocusField) {
    if (typeof bFocusField == 'undefined') {
        bFocusField = true;
    }
    
    if (!document.loginBoxOpened) {
        document.loginBoxOpened = true;
        var cBlock = $('#loginDropdown .cblock');
        $('#loginDropdown').css('z-index', 100);
        
        if (cBlock.offset()) {
            $('#loginDropdown .cblock-shadow').css({left: cBlock.offset().left + 'px', top: cBlock.offset().top + 'px'});
        }
        
        $('#loginDropdown').css('visibility', 'visible');
        $('#loginBox').slideDown('fast', function() {
            if (bFocusField) {
                $('#loginForm #login').focus();
            }
        });
    } else {
        document.loginBoxOpened = false;
        $('#loginDropdown').css('visibility', 'hidden');
        $('#loginDropdown').css('z-index', -1);
        $('#loginBox').slideUp('fast');
    }
}

function submitLoginForm() {
    
    var f = $(this.form);
    
    if ($('#login', f).val() == '') {
        alert('Please enter a username.');
        $('#login', f).focus();
        return false;
    } else if ($('#password', f).val() == '') {
        alert('Please enter a password.');
        $('#password', f).focus();
        return false;
    }
    
    var query = f.serialize();
    $('input', f).attr('disabled', true);
    $('.progress-indicator', f).show();
    
    $.post(f.attr('action'), query, function(response) {
                
        $('input', f).attr('disabled', false);
        $('.progress-indicator', f).hide();
        
        if (!response) return false;
        
        if (response.success) {
            f.attr('action', response.afm_site_url + f.attr('action'));
            f.submit();
        } else {
            $('#password', f).val('');
            alert(response.errors);
            return false;
        }
        
    });
}

function submitRecoveryForm() {
    
    var f = $(this.form);
    
    if (!/^[a-z0-9\+\.\-]+\@[a-z0-9\+\.\-]+$/i.test($('#email', f).val())) {
        alert('Please enter a valid email.');
        $('#email', f).focus();
        return false;
    }
    
    var query = f.serialize();
    $('input', f).attr('disabled', true);
    $('.progress-indicator', f).show();
    
    $.post(f.attr('action'), query, function(response) {
                
        $('input', f).attr('disabled', false);
        $('.progress-indicator', f).hide();
        
        if (!response) return false;
        
        if (response.success) {
            alert('A new password has been sent to your email address.\r\n'
                + 'If it does not arrive within 30 minutes please contact '
                + response.pal_support_email
                + ' and we will make sure that you receive it.'
            );
            $('#email', f).val('');
            return false;
        } else {
            alert(response.errors);
            return false;
        }
        
    });
}

function clientLogoRoll() {
    
    var IMG_APPEAR_TIME     = 2000;
    var IMG_DISAPPEAR_TIME  = 2000;
    var IMG_SHOW_TIMEOUT    = 3000;
    
    if (_clientLogoImageIndex == null) _clientLogoImageIndex = 0;
    
    var images = $('#clientLogo img').toArray();
    
    if (!images.length) return;
    
    var cImg = images[_clientLogoImageIndex];
    
    if (images.length == 1) {
        $(cImg).fadeIn(IMG_APPEAR_TIME);
        return;
    }
    
    if (typeof images[_clientLogoImageIndex + 1] == 'undefined') {
        _clientLogoImageIndex = 0;
    } else {
        _clientLogoImageIndex += 1;
    }
    
    $(cImg).fadeIn(IMG_APPEAR_TIME, function() {
        setTimeout(function() {
            $(cImg).fadeOut(IMG_DISAPPEAR_TIME, function() {
                clientLogoRoll();
            });
        }, IMG_SHOW_TIMEOUT);
    });
    
}

function createShadows() {
    
    if (!_shadowOffsetLeft) _shadowOffsetLeft = 0;
    
    $('.cblock:not(.no-shadow)').each(function(i) {
        
        var cBlock = $(this);
        var cBlockShadow = $('#proto_cBlockShadow').clone();
        $(cBlockShadow).attr('id', $(cBlockShadow).attr('id' + i));
        
        cBlock.parent().append(cBlockShadow);
        $('.cblock-shadow-holder', cBlockShadow).height(cBlock.height() - 17);
        cBlockShadow.width(cBlock.width() + 13);
        cBlockShadow.css({left: cBlock.position().left - _shadowOffsetLeft + 'px', top: cBlock.position().top + 'px'});
        cBlockShadow.show();
        
        
        
    });
    
}