var nav = {
    init: function () {
        var items = $('#products .flyout li').length;
        var itemWidth = 122;
        var menuWidth = itemWidth * items;

        $('.menu li:last-child').addClass('nav-last');
        $('.flyout li:last-child').removeClass('nav-last');
        $(".category-right ul li:last-child, .category-rightdark ul li:last-child").addClass("category-last");
        $('#products .flyout-wrap').css({ 'height': '0' }).hide();
        $('#products .flyout').css({ 'width': menuWidth, 'margin': '0px auto' });

        $("#products").hover(
            function () {
                $('#products  a:first-child').addClass("on");
                $('#products .flyout-wrap, #products .flyout').show();
                $(this).addClass("products");
                $(this).find('.flyout-wrap').stop();
                $('.dropdown .flyout-dropdown, .dropdown .flyout').hide();
            },
            function () {
                $('#products a:first-child').removeClass("on");
                $(this).removeClass("products");
                $('.flyout-wrap, .flyout').hide();

            }
        );

        $('.dropdown .flyout-wrap, .dropdown .flyout').hide();
        $(".dropdown").hover(
            function () {
                $(this).find('a:first-child').addClass("on");
                $('.menu').find('li:nth-child(n+4)').addClass("dropdown-right");
                $(this).addClass('dd-on').show();
                $(this).addClass("flyout-navbg");
                $(this).find('.flyout-wrap, .flyout').show();
            },
            function () {
                $(this).removeClass('dd-on').show();
                $(this).find('a:first-child').removeClass("on");
                $('.menu').find('li:nth-child(n+4)').removeClass("dropdown-right");
                $(this).removeClass("flyout-navbg");
                $(this).find('.flyout-wrap, .flyout').hide();
            }
        );

    }
};

// Generic modal edit
$("a.defaultModal").click(function () {
    var href = $(this).attr("href");
    var tab = ($(this).attr("rel")) ? $(this).attr("rel") : null;
    $.ajax({
        url: href,
        type: "GET",
        dataType: "html",
        success: function (data) {
            modal.make(data, null, tab);
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        }
    })
    return false;
});

var formSubmitWithFormStatus = {
    init: function () {
        $('.genericForm').submit(function () {
            $.post($(this).attr("action"), $(this).serialize(),
                  function (response) {
                      $("#formStatus").html(response._formStatus);
                  });
            return false;
        });
    }
};

var searchBoxAutoComplete = {
    init: function () {
        $('#searchTxt').keyup(function () {
            if ($(this).val().length >= 3) {
                var href = "/home/quicksearchresults?query=" + $(this).val();
                var tab = "/home/quicksearchresults?query=" + $(this).val();
                $.ajax({
                    url: href,
                    type: "GET",
                    dataType: "html",
                    success: function (data) {
                        modal.make(data, "search", "");
                    },
                    error: function (xmlHttpRequest, textStatus, errorThrown) {
                        alert(errorThrown);
                    }
                })
            }
        });
    }
};

var delayImageLoad = {
    init: function () {
        $('.delayLoad').each(function () {
            var intendedSrc = $(this).attr('data-lighburn-intended-url');
            $(this).delay(600).fadeOut(function () { $(this).attr('src', intendedSrc).fadeIn(300); });
        });
    }
};

var modal = {
    make: function (data, status, selectedTab) {

        var currentTab = (selectedTab) ? selectedTab : 0;

        // Make Modal & Overlay
        if (status == 'search') {
            $('body').prepend('<div id="searchModal-container"><div id="searchModal"></div></div>');
        } else {
            $('body').prepend('<div id="modal"></div><div id="overlay">&nbsp;</div>');
        }
        $('#overlay').height($(window).height()).fadeTo('fast', 0.8);

        // Populate Modal
        if (status == 'Accept') {
            $('#modal').prepend('<h4>You\'re about to accept ' + $('h1').text() + ':</h4><div id="modalHolder"></div>')
            $('#modalHolder').html('<p>' + data + '</p>' + $('#acceptNote').html());
            $('#modal').append('<p id="modalControls"><a href="#" id="modalClose">Cancel</a> or <a href="#" id="modalSubmit" class="jsButton"><span>Send</span></a></p>')
        } else if (status == 'Reject') {
            $('#modal').prepend('<h4>You\'re about to reject ' + $('h1').text() + ':</h4><div id="modalHolder"></div>')
            $('#modalHolder').html('<p>' + data + '</p>' + $('#rejectNote').html());
            $('#modal').append('<p id="modalControls"><a href="#" id="modalClose">Cancel</a> or <a href="#" id="modalSubmit" class="jsButton"><span>Send</span></a></p>')
        } else {
            $('#modal, #searchModal').html(data);
            $('#modal').prepend('<a href="#" id="modalClose" class="closeBtn">Close</a>')
        }

        // Initialize Form Elements
        forms.format($('#modal, #searchModal'));
        $('.daysList, .employeeList').buttonset();

        // Final build & show
        $('#modal #tabs, #searchModal #tabs').tabs({
            selected: currentTab
        });
        $('html, body').animate({ scrollTop: 0 }, 'slow');
        $('#modal').fadeIn('fast');
        $('#searchModal').fadeIn('500');

        // Listen for clicks
        $('#modalSubmit').live('click', function (e) {
            $('#modalApprovalForm').submit();
            e.preventDefault();
        });
        $('#overlay, #modal a#modalClose').live('click', function (e) {
            modal.destroy();
            e.preventDefault();
        })

        $('#searchModal-container').bind('mouseleave', function () {
            $(this).remove();
        })

        $('#modal .jsButton').live('click', function () {
            $(this).addClass('saving');
        });

        $(window).resize(function () {
            $('#overlay').height($(window).height());
        });

    },
    destroy: function () {
        $('#overlay, #modal, #searchModal').fadeOut('fast', function () {
            $(this).remove();
        });
    }
};

var forms = {
    init: function () {
        $('#content').ready(function () {
            forms.format($(this));
        });
    },
    format: function (container) {
        var inputs = container.find('input[type=text], input[type=password]'),
            mce = container.find('textarea.editor');

        // Input type=text
        inputs.each(function () {
            if ($(this).val() != '') {
                $(this).addClass('on');
            }
        });
        inputs.focus(function () {
            $(this).addClass('on');
        });
        inputs.blur(function () {
            if ($(this).val() == '') {
                $(this).removeClass('on');
            }
        });
    }
};

function initialize() {
    formSubmitWithFormStatus.init();
    searchBoxAutoComplete.init();
    nav.init();
    forms.init();
    delayImageLoad.init();
}

$(function () {
    initialize();
    document.documentElement.className = document.documentElement.className.replace('no-js', 'js');


    $("#breadCrumb ul li:last-child").addClass("on");
    $('.stock-container ul:odd, .detail-content ul:even, #request_illustration_modal ul:even, #request_a_quote ul:even').addClass('odd')
    $('.position:even').addClass('position-margin')
    $(window).load(function () {
        $('#loading').hide().remove();
    });
    $(".category-container:last-child").addClass('category-container-last');
    $(".category-right ul li:nth-child(5n)").addClass('results-last');
    $('.results-left input.close').click(function () {
        $(this).parents('.category-container').hide('drop', '1000');
        return false;
    });
    $("#contentint p:first").addClass('intro');
    $(".position p:first").removeClass('intro');
    $(".content-banner p:first").addClass('address-sidebar');
});
