$(document).ready(function() {
    setupMenus();
    eventSetup();
    //$(document).pngFix();
    // Setup select boxes
    setupSelectElements();
    submitButtons();
    setupFormClasses('#content');
    setupFormClasses('#staticcontent');
    setupFormClasses('#simplewrap');
    stretchScreen();
});

function eventSetup()
{
    setupWindowCloser();

    $('#new_message_button').click(function() {
        newMessage();
        return false;
    });

    $('#my_account_button').click(function() {
        myAccount();
        return false;
    });

    $('#project_logon_button').click(function() {
        switchProject();
        return false;
    });

    $('.click_and_pop').click(function() {
        remoteWindow($(this).attr('href'), 440, 150);
        return false;
    });

    $('.monoimage').mouseover(function(){monoOver(this);});
    $('.monoimage').mouseout(function(){monoOut(this);});
    preloadIcons();
}

function setupWindowCloser()
{
    $('.windowCloser').click(function() {
      closeRemoteWindow();
      return false;
    });
}

function setupMenus()
{
    $('#sidebar ul li span').mouseenter(function() {
        menuOver(this);
    });

    $('.flyoutmenu').mouseleave(function() {
        menuClose();
    });
}

function menuOver(obj)
{
    menuClose();
    var stubID = $(obj).attr('id').replace('_trigger', '');
    var sideBarPos = $('#sidebar').offset();
    var triggerTop = $(obj).offset();
    var newTop = triggerTop.top - sideBarPos.top;
    $('#' + stubID + '_sub').css('top', newTop + 'px').css('display', 'block');
    $(obj).addClass('menu_open');
}

function menuClose()
{
    $('.flyoutmenu').css('display', 'none');
    $('#sidebar ul li span').removeClass('menu_open');
}

function remoteWindow(url,width,height,hideCloser)
{
    if (!width) {
        width = 450;
    }

    if (!height) {
        height = 250;
    }

    if (!hideCloser) {
        hideCloser = false;
    }

    var left = ($(window).width()) / 2 - (width / 2);
    if (left < 0) {
        left = 0;
    }

    var top = ($(window).height()) / 2 - (height / 2);
    if (top < 0) {
        top = 0;
    }

    var data = {};

    $('#remote_window_content').html('<div class="loading"></div>');
    $('#remote_window').width(width).height(height).css('left', left + 'px').css('top', top + 'px');
    $('#remote_window_content').width(width).height(height - 20);

    if (hideCloser == false) {
        $('.windowCloser').css('display', 'block');
    } else {
        $('.windowCloser').css('display', 'none');
    }

    $('#messageboxtop').width(width).height(70).css('left', left + 'px').css('top', (top - 70) + 'px');
    $('#messageboxfoot').width(width).height(34).css('left', left + 'px').css('top', (top + height) + 'px');

    $('#remote_window_content').load(url, data, function(responseText, textStatus, XMLHttpRequest) {
        if(textStatus == 'error') {
            if (XMLHttpRequest.status == 403) {
                $('#remote_window_content').html('<div class="error_remote_response">You don\'t have the required permission to access this page.</div>');
            } else {
                $('#remote_window_content').html('<div class="error_remote_response">An error has occured with this request. Please close this window and try again.</div>');
            }
        }

        setupSelectElements('#remote_window_content select[multiple!=true]');
        submitButtons('#remote_window_content :submit');
        setupFormClasses('#remote_window_content');
    });

    $('#overlay, #messageboxtop, #remote_window, #messageboxfoot').fadeIn();
}

function closeRemoteWindow(timer)
{
    if (!timer) {
        $('#overlay, #messageboxtop, #remote_window, #messageboxfoot').fadeOut();
    } else {
        // Close in a little while
        setTimeout('closeRemoteWindow();', timer);
    }
}

function refreshPage()
{
    document.location.href = document.location.href;
}

function loadPage(url, timer)
{
    if (!timer) {
        document.location.href = url;
    } else {
        setTimeout('loadPage("' + url + '");', timer);
    }
}

function submitForm(obj)
{
    var values = $(obj).serialize();
    var submitURL = $(obj).attr('action');
    var firstSubmit = true;
    $('.windowCloser').css('display', 'none');
    $('#remote_window .subwrapleft').each(function() {
        if (firstSubmit == true) {
            firstSubmit = false;
            $(this).replaceWith('<img src="/images/loading.gif" alt="Loading" />');
        } else {
            $(this).replaceWith('');
        }
    });
    $.post(submitURL, values, function(data) {
        $('#remote_window_content').html(data);
        setupSelectElements('#remote_window_content select[multiple!=true]');
        submitButtons('#remote_window_content :submit');
        setupFormClasses('#remote_window_content');
    });

    return false;
}

function refreshMainContent(url)
{
    $('#content').load(url, function() {
        sectionEventSetup();
        setupSelectElements();
        submitButtons();
        setupFormClasses('#content');
        setupFormClasses('#staticcontent');
    });

}

function newMessage(obj)
{
    var url = '/messages/newmessage';
    remoteWindow(url, 550, 500);
}

function switchProject()
{
    var url = '/project/switchstart';
    remoteWindow(url, 440, 240);
}

function myAccount(obj)
{
    var url = '/account';
    remoteWindow(url, 400, 250);
}

function setupSelectElements(selector)
{
    if (!selector) {
        selector = 'select[multiple!=true]';
    }

    $(selector).selectbox();
}

function submitButtons(selector)
{
    if (!selector) {
        selector = ':submit';
    }

    $(selector).each(function() {
        $(this).addClass('submitCustom');
        $(this).css({
                'width'  : $(this).width() + 25
        });

        if ($.browser.msie != true) {
            // Non-IE
            $(this).wrap('<span class="subwrapleft"></span>');
        } else if (parseInt($.browser.version) > 7) {
            // IE 8+
            $(this).wrap('<span class="subwrapleftieeight"></span>');
        } else {
            $(this).wrap('<span class="subwrapleftie"></span>');
        }

        var parentHeight = $(this).parent().height() + parseInt($(this).parent().css('padding-top')) + parseInt($(this).parent().css('padding-bottom'));
        var heightDiff   = $(this).height() - parentHeight;
        if (heightDiff == 0 && $(this).parent().parent().hasClass('correctSubmitPaddingOpposite') == true) {
            $(this).parent().css('padding-top', 7 + 'px');
        } else if (heightDiff == 0) {
            if ($.browser.msie == true && parseInt($.browser.version) > 7) {
                $(this).parent().css('padding-top', 7 + 'px');
            } else {
                $(this).parent().css('padding-top', 8 + 'px');
            }
        } else if (heightDiff == 2) {
            $(this).parent().css('padding-top', 7 + 'px');
        }

        //if ( >= ($(this).parent().height() + parseInt($(this).parent().css('padding-top')) + parseInt($(this).parent().css('padding-bottom')))) {
        //    $(this).parent().css('padding-top', 8 + 'px');
        //}
        //

    });
}

function setupFormClasses(parentSelector) {
    $(parentSelector + ' :text').addClass('textinput');
    $(parentSelector + ' :submit').addClass('submitinput');
    $(parentSelector + ' :checkbox').addClass('checkboxinput');
}

function stretchScreen()
{
    if ($(window).height() > $('#wrapper').height()) {
        var diff = $(window).height() - $('#wrapper').height();
        $('#tabcontent, #connectbackground').css('height', parseInt((parseInt($('#content').height()) + diff)) - 30 + 'px');
        $('#tabcontent, #connectbackground').css('overflow-y', 'auto');
    }

    if ($('#main').height() > $('#content').height()) {
        $('#connectbackground').css('height', $('#main').css('height'));
    }

    if ($('#main').height() < 400) {
        $('#main').css('height', '400px');
    }
}

function monoOver(obj)
{
    $(obj).attr('src', $(obj).attr('src').replace('_off', '_on'));
    if ($(obj).hasClass('toolbaricon')) {
        iconTooltip(obj);
    }
}

function monoOut(obj) {
    $(obj).attr('src', $(obj).attr('src').replace('_on', '_off'));
    if ($(obj).hasClass('toolbaricon')) {
        tooltipHide();
    }
}

function preloadIcons()
{
    $('.monoimage').each(function() {
        $.preLoadImages($(this).attr('src').replace('_off', '_on'));
    });
}

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)
