/* 
    Created on : Oct 6, 2011, 1:08:14 PM
    Author     : chris.wright
 */
$.Menu = function() {};
$.Menu.prototype.loaded = true; // Make visible
$.Menu.root_submenu = null;
$.Menu.current = null;
$.Menu.spinner = null;
$.fn.reverse = [].reverse;

$.Menu.getLink = function (document_name) {
    return $("#menu a[href='" + document_name + "']:not(#menu div.text a):first");
}
$.Menu.load = function() {
    $('a.button').button();

    // Highlight the correct menu
    var document_name = $.Menu.getDocumentName();
    var link = $.Menu.getLink(document_name);
    if (link.length < 1) {
        link = $.Menu.getLink('index.php');
    }

    if (link.parent().is('li')) {
        link.parent().addClass('selected');
    } else {
        link.addClass('selected');
    }
    $.Menu.current = link;
    if (link.parents('div.submenu:last').length > 0) {
        $.Menu.root_submenu = link.parents('div.submenu:last').prev('a')[0];
    } else {
        $.Menu.root_submenu = link[0];
    }
    $($.Menu.root_submenu).addClass('selected');
    if (link.parent().is('li')) {
        $.Menu.activateSubmenu(link.parent());
    }

    // If this is the home page then show the menu
    if ($.Menu.isHome()) {
        $('#menu_details').show();
        $.Menu.loadSubmenu(link);
    }

    // Fade in the container
    $('#container .content').css('visibility','visible').hide().fadeIn();

    // Setup the root menu
    $('#menu div.container:first > a').click(function(e) {
        e.preventDefault();
        $.Menu.clickedRoot($(this));
        return false;
    });

    $('#container a').each(function() {
        var link = $(this);
        var document_name = link.attr('href');
        var menu_link = $.Menu.getLink(document_name);

        // If this is an internal url
        if (menu_link.length > 0) {
            link.click($.Menu.clickedLink);
        }
    });

    startSpinning();
};

$.Menu.clickedLink = function(e) {
    if (e) e.preventDefault();

    var clicked = $(this);
    var document_name = clicked.attr('href');
    var link = $.Menu.getLink(document_name);

    var root_submenu = link;
    if (link.parents('div.submenu:last').length > 0) {
        root_submenu = link.parents('div.submenu:last').prev('a');
    }

    // We clicked a root link and we are not currently on a submenu
    if ($('#menu_details:hidden').length > 0) {
        $.Menu.animateRootTo(root_submenu, function() {
            // Go straight to the URL after a transfer
            $.Menu.loadUrl(document_name);
        });
    } else {
        $.Menu.animateRootTo(root_submenu, function() {
            $.Menu.unloadSubmenu(function() {
                // Hide the detail first
                $('#menu_details').slideUp(500, function() {
                    // Go straight to the URL after a transfer
                    $.Menu.loadUrl(document_name);        
                })
            });
        });
    }
    return false;
};

$.Menu.getDocumentName = function() {
    var document_name = window.location.href;
    document_name = document_name.replace(window.location.protocol + "//" + window.location.hostname + "/", "");
    if (document_name == '') {
        document_name = 'index.php';
    }
    document_name = document_name.replace(/#.*/,'');
    document_name = document_name.replace(/^.+?\//,'');
    return document_name;
};

$.Menu.isHome = function() {
    // If this is the home page then show the menu
    var document_name = $.Menu.getDocumentName();
    return ('index.php' === document_name || '' === document_name);
};

$.Menu.clickedRoot = function(root) {
    $('*').stop(true, true);

    // Determine if there is a submenu or not
    var possible_submenu = root.next('.submenu');
    if (possible_submenu.length < 1 || 'index.php' == root.attr('href')) {
        // We clicked a root link and we are not currently on a submenu
        if ($('#menu_details:hidden').length > 0) {
            $.Menu.animateRootTo(root, function() {
                // Go straight to the URL after a transfer
                $.Menu.loadUrl(root.attr('href'));
            });
        } else {
            $.Menu.animateRootTo(root, function() {
                $.Menu.unloadSubmenu(function() {
                    // Hide the detail first
                    $('#menu_details').slideUp(500, function() {
                        // Go straight to the URL after a transfer
                        $.Menu.loadUrl(root.attr('href'));        
                    })
                });
            });
        }
    } else {
        // If we clicked on the same submenu as currently open one and are not on the home page, collapse menu details
        if (root[0] == $('#menu div.container:first > a.selected')[0] && $('#menu_details:visible').length > 0) {
            if ($.Menu.isHome()) return;
            $.Menu.revert();
            return;
        }

        $.Menu.animateRootTo(root, function() {
            // We clicked a root submenu and we are not currently on a submenu
            if ($('#menu_details:hidden').length > 0) {
                if (!$.Menu.isHome()) {
                    $('#minimise').show().click($.Menu.revert);
                }
                $('#menu_details').slideDown(500, function() {
                    $.Menu.loadSubmenu(root);
                });
            } else {
                $.Menu.loadSubmenu(root);
            }
        });
    }
};

$.Menu.revert = function() {
    $.Menu.unloadSubmenu(function() {
        // Hide the detail first
        $('#menu_details').slideUp(500, function() {
            $.Menu.animateRootTo($($.Menu.root_submenu));
        })
    });
};

$.Menu.animateRootTo = function(to, after_animation) {
    $('#menu div.container:first > a.selected').removeClass('selected').effect("transfer", {
        to: to,
        className: 'selected'
    }, 300, function() {
        to.addClass('selected');
        if (after_animation) {
            after_animation.apply(this, arguments);
        }
    });
};

$.Menu.unloadSubmenu = function(after_unload) {
    $('#selected_submenu').find('div:first').effect('drop', {
        direction: 'left'
    }, 500, function() {
        $(this).empty();
        after_unload.apply(this, arguments);
    });
};

$.Menu.loadSubmenu = function(root) {
    var submenu = root.next('.submenu').clone();
    submenu.find('a.button').button();

    function setupSubmenu() {
        var text = submenu.children('div.text');
        text.find('a').each(function() {
            var link = $(this);
            var document_name = link.attr('href');
            var menu_link = $.Menu.getLink(document_name);

            // If this is an internal url
            if (menu_link.length > 0) {
                link.click($.Menu.clickedLink);
            }
        });

        startSpinning();

        var menu = submenu.children('div.menu');
        menu.find('a').click(function(e) {
            var link = $(this);
            e.preventDefault();

            $.Menu.unloadSubmenu(function() {
                // Hide the detail first
                $('#menu_details').slideUp(500, function() {
                    // Go straight to the URL after a transfer
                    $.Menu.loadUrl(link.attr('href'));      
                })
            });
            return false;
        });
        menu.find('li.submenu').each(function() {
            var inner_submenu = $(this);
            var depth = inner_submenu.parents('li.submenu').length;
            if (depth != 1) {
                inner_submenu.prev().addClass('ui-widget-header');
                return;
            }
            inner_submenu.prev('li').hover(function() {
                $(this).css('cursor', 'pointer');
            }, function() {
                $(this).css('cursor', 'default');
            });
        });
        menu.find('li:not(li.submenu)').mouseover(function() {
            $.Menu.activateSubmenu($(this));
        }).click(function() {
            $.Menu.activateSubmenu($(this));
        });
        menu.find('ul:first > li.submenu > ul > li.submenu').hide();
    }

    function fadeInSubmenu() {
        $('#selected_submenu').empty().append(submenu);
        submenu.show();
        setupSubmenu();

        // Animate the menus dropping in
        submenu.children('div.menu').effect('drop', {
            direction: 'left',
            mode: 'show'
        }, 500);
        submenu.children('div.text').effect('drop', {
            direction: 'right',
            mode: 'show'
        }, 500);
    }

    if ($('#selected_submenu').find('div:first').children('*').length > 0) {
        $.Menu.unloadSubmenu(fadeInSubmenu);
    } else {
        fadeInSubmenu();
    }
};

$.Menu.activateSubmenu = function(submenu) {
    $('.selected_path').removeClass('selected_path');
    submenu.addClass('selected_path').parents('.submenu').each(function() {
        $(this).prev('li').addClass('selected_path');
    });

    var nested = submenu.next('li.submenu');
    if (nested.length > 0) {
        // Hide all previously shown submenus
        if (nested.parents('li.submenu').length < 2) {
            submenu.parents('div.menu:first').find('ul:first > li.submenu > ul > li.submenu').hide();
        }
        if (nested.parents('li.submenu').length == 1) {
            nested.addClass('expanded_menu').css('padding', '0').show();
        }
    }
};

$.Menu.loadUrl = function(url) {
    $('#container div.content:first').fadeOut(function() {
        $('#loader').remove();
        $('#container').prepend('<img id="loader" src="images/ajax-loader.gif" alt="loading" style="display:block;margin:5em auto 0 auto" />');
        window.location = url;

        // If this is a internal link then reload the page
        if (/^#.*$/.test(url)) {
            window.location.reload();
        }
    });
};

function startSpinning() {
    if ($.Menu.spinner) clearInterval($.Menu.spinner);
    var spinners = $('.spin');
    if (spinners.length < 1) {
        return;
    }
    spinners.hide().filter('.spin').each(function() {
        $(this).parent().children('.spin:first:hidden').show();
    });

    $.Menu.spinner = setInterval(showNext, 8000);
}

function showNext() {
    var current = $('.spin:visible');
    if (current.length < 1) {
        if ($.Menu.spinner) clearInterval($.Menu.spinner);
        return;
    }
    current.fadeOut('slow', function() {
        current.each(function() {
            var self = $(this);
            var next = self.next('.spin');
            if (next.length < 1) {
                next = self.parent().children('.spin:first');
            }
            next.fadeIn();
        });        
    });
}

$.Faq = {
    setup : function() {
        $('li.question').click(function() {
            var answer = $(this).next('.answer');
            if (answer.is(':hidden')) {
                answer.slideDown();
            } else {
                answer.slideUp();
            }
        });
    }  
};

$.Maps = {
    setup : function () {
        $('.map').click(function() {
            var link = $.Menu.getLink('contact.php');
            $.Menu.clickedRoot(link);
        });
    }
}

$(document).ready(function() {
    $.Menu.load();
    $.Faq.setup();
    $.Maps.setup();
    $('div.search img.icon').click(function() {
        $("form#search").submit();
    });
    $('#search input:visible').mousedown(function() {
        $(this).val('');
    });
    $('#search input:visible').keypress(function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if(code == 13) { //Enter keycode
            $("form#search").submit();
        }
    });
});
