﻿$(function() {
    //Need to sniff for external windows - we're looking for target attribute of _blank
    $('.leftRelContainer a').each(function() {
        if ($(this).attr("target") == "_blank") {
            $(this).addClass('externalLink');
        };
    });

    //Replace the Guidance and Industry links to those on HSE site.
    $('a.breadcrumbLink').each(function() {
        if ($(this).attr("href") == "/guidance") {
            $(this).attr("href", "http://www.hse.gov.uk/guidance");
        };
        if ($(this).attr("href") == "/guidance/industries") {
            $(this).attr("href", "http://www.hse.gov.uk/guidance/industries.htm");
        };
    });

    //Enable accordions
    $('ul.pageNavList li ul li.channelWithChildren > ul').hide();
    $('li.channelWithChildren').addClass('accordion');  //so we can style plus/minus icons
    //$('ul.pageNavList li ul li.channel_active > ul.subChannel').parent().show().addClass('accordionExpanded');  //show the ul if it has a current link in it (current page/section should be shown expanded)
    $('ul.pageNavList li.channel_active').addClass('accordionExpanded');
    $('ul.pageNavList li ul li.channel_active > ul.subChannel').show();

    //This is the plus or minus symbol being clicked...
    addAccordianFunctions($('li.accordion'));
});

function addAccordianFunctions(toAddTo) {
    
    $('li.accordion a').click(function() {
        window.location.href = $(this).attr('href');
        return false;
        //We run this first and return false so that the animation doesn't run...
    });

    toAddTo.click(function() {
        var thisLi = $(this);
        var nextUl = $(this).children('ul');
        if (nextUl[0] == null) {
            thisLi.addClass('loading');
            var urlExpanding = ($(this).children('a:first').attr('href'));
            $.ajax({
                url: "/onestopcms/core/ajax/GetNavigation.aspx?start=" + urlExpanding,
                context: document.body,
                cache: false,
                success: function(data, textStatus, jqXHR) {
                    thisLi.append(data);
                    thisLi.find('li.channelWithChildren').addClass('accordion');
                    addAccordianFunctions(thisLi.find('li.accordion'));
                    thisLi.toggleClass('accordionExpanded'); //for CSS bgimage, but only on first li (sub li>a's don't need the class)
                    nextUl = thisLi.children('ul');
                    nextUl.hide();
                    nextUl.slideToggle('fast');
                    thisLi.removeClass('loading');
                }
            });
        }
        else {
            $(this).toggleClass('accordionExpanded'); //for CSS bgimage, but only on first li (sub li>a's don't need the class)
            nextUl.slideToggle('fast');
        }
        return false;
    });
}
