//  Safe Firebug debug call
function debug(obj) {
    try{
        console.log(obj)
    }catch(e){}
}

//  Simple JS access to cookies
function createCookie(name,value,days) {
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

// Read a cookie
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
    {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
//  Delete a cookie
function eraseCookie(name) {
    createCookie(name,"",-1);
}

//  Setup Mechanism
//  Initialises all javascript

function setup(){
    if(sitemapJsonUrl && sitemapJsonUrl != ""){
      var newUl = jsonRenderNavigation(sitemapJsonUrl, path);
    }
    // Top level othersites drop down
    $('#otherSites').unbind().hoverIntent(
        {
            sensitivity: 1,
            interval: 150,
            over: function(){
                    $(this).children('ul').find('a').css('height','2.45em');
                    $(this).children('ul').slideDown({ duration: 300, easing: 'easeOutCirc',complete:function(){$(this).find('a').css('height','auto');}})
                },
            timeout: 150,
            out: function(){
                    $(this).children('ul').find('a').css('height','2.45em');
                    $(this).children('ul').slideUp({ duration: 300, easing: 'easeInCirc',complete:function(){$(this).find('a').css('height','auto');}});
                }
        }
    )

    // Disable other sites click
    $('#otherSites .hasMenu').click(function(){return false})

    // Main menu drop downs (overrides css)
    $('#popup div.body').hoverIntent(
        {
            sensitivity: 1,
            interval: 100,
            over: function(){},
            timeout: 100,
            out: function(){
                    toggleSites()
                    $('#popup div.body').slideUp({ duration: 300, easing: 'easeInOutCirc'});
                }
        }
    )

    normaliseHeights();

    // Size switcher
    $('#styleSize').click(function() {
        switchSize($(this).html());
        return false;
    });

    // Country clicker
    $('#siteWideNavigation').find('.change').click(toggleSites)

    // Left column
    // Change style size if cookie exists
    var c = readCookie('style');
    if (c) switchSize(c);

    // resizeIframes();
}

function setupMainNavigation(){
    //  Main menu drop downs (overrides css)
    $('#mainNavigation').children('li').unbind().hoverIntent(
        { sensitivity: 1,
           interval: 100,
           over: function(){
               $(this).children('ul').slideDown({ duration: 300, easing: 'easeOutCirc'});
            },//
           timeout: 100,
           out: function(){
                $(this).children('ul').slideUp({ duration: 100, easing: 'easeOutCirc'});
            }
        }
    )

    //  Disable section links
    //$('#mainNavigation').children('li').children('a').unbind().click(function(){return false});

    // Override Main menu CSS
    $('#mainNavigation').find('ul').css('display','none');
}

function lineHeight() {
    h1 = $('#HPWhoAreWe').height();
    h2 = $('#HPNews').height();
    editModeNewsContainer = $('#CQEditMode_NewsListHome');
    if (typeof(editModeNewsContainer) != 'undefined') {
        h2 = Math.max(h2, editModeNewsContainer.height());
    }
    if (h2 > h1) {
        $('#HPWhoAreWe').height(h2);
    }
}

function checkboxFix() {
    $('div.rememberMe label').css('line-height','100%').hide().show().css('display','inline');
    $('div.rememberMe input').hide().show().css('float','right');
    $('div.rememberMe span').hide();
    $('fieldset label').hide().show();
    $('fieldset label select').css('position','relative');
}

function normaliseHeights() {
    // find hidden panels and "unhide" them
    var hiddenPanels = new Array();
    var n = 0;
    $(".hpApplicationBox").each(function(){
        var div = $(this);
        var hidden = div.css("display") == "none";
        if (hidden) {
            hiddenPanels[n++] = div;
            div.show();
        }
    });

    normaliseHeight(".bodyTop");
    normaliseHeight(".hpApplicationBox h3");
    normaliseHeight(".App h3");
    normaliseHeight(".lowerFooter");
    normaliseHeight("#HPMyTNT .lowerTop");
    normaliseHeight(".bodyFooter");
    normaliseHeight(".App");
    normaliseHeight(".tabs");
    lineHeight();

    // IE6 bugfix - setting position to relative to force re-layout
    if (jQuery.browser.msie == true && jQuery.browser.version < 7) {
        $(".HelpTip").css("position", "absolute");
        $(".HelpTip").css("position", "relative");
    }

    // hide "hidden" panels back
    for (var i = 0; i < n; i++) {
        hiddenPanels[i].hide();
    }
}

/** 
 * Makes every element matching given selector have the same height.
 * @param cssSelector jQuery CSS selector to be used for finding components
 * @author Jan Ku&#378;niak
 */
function normaliseHeight(cssSelector) {
    var largestSize = 0;
    $(cssSelector).css("height", "");
    $(cssSelector).each(function() {
        height = $(this).height();
        if(height > largestSize) {
            largestSize = height;
        }
    });

    if($(cssSelector).size()) {
        $(cssSelector).height(largestSize + "px");
    }
}

function resizeIframes() {
    $("iframe").load(function() {
        this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
    });
}

function toggleSites(){
        //  Shows and loads site list in the popup box
        var link = $('#siteWideNavigation').find('.change');
        var open = link.attr('name').split('-')[0];
        var close = link.attr('name').split('-')[1];

        if(link.attr('isOpen') != 'true'){

            // changed 'isOpen' to 'isopen' to fix IE issue with no slideUp
            link.attr('isopen','true');
            link.html(close);

            if($('#popup').find('div.countries').size() > 0){
                $('#popup div.body').slideDown({ duration: 400, easing: 'easeInOutCirc'})

            }else{

                var loadedHtml = "";
                debug(countriesHtmlUrl());

                try{
                        //loadedHtml = $('#popup div.body').load( countriesHtmlUrl() );

                    jsonRenderCountries(countriesHtmlUrl());
                }catch(e){debug(e);}


                //$('#popup div.body').html(loadedHtml);
                $('#popup div.body').slideDown({ duration: 400, easing: 'easeInOutCirc'})

                // Load the countries.shtml using ajax.
                //$('#popup div.body').load(
                    // this function returns localised url which generates countries menu html
                    // function defined in secondaryNavigation/start.jsp
                //  countriesHtmlUrl(),
                //  function(){
                        $(this).slideDown({ duration: 400, easing: 'easeInOutCirc'})
                //  }
                //);
          }
            toggleIFrame();
        }else{
            $('#popup div.body').slideUp({ duration: 400, easing: 'easeInOutCirc'});
            // changed 'isOpen' to 'isopen' to fix IE issue with no slideUp
            link.attr('isopen','false');
            link.html(open)
            toggleIFrame();
        }

        return false;
}

//  Simple function to change font size
function switchSize(styleSize) {
    var large = $('#styleSize').attr('name').split('-')[0];
    var small = $('#styleSize').attr('name').split('-')[1];

    if(styleSize ==large){
        $('body').css('font-size','12pt').find('#styleSize').html(small)
        styleSize = large;
        $('#siteWideNavigation a.hasMenu').css('padding-bottom','9px');
    } else {
        $('body').css('font-size','10pt').find('#styleSize').html(large)
        styleSize = small;
        $('#siteWideNavigation a.hasMenu').css('padding-bottom','11px');
    }

    normaliseHeights();
    createCookie('style', styleSize, 365);
}

// Show an iFrame uner our country dropdown list.
function toggleIFrame()
{
  // If the user has IE 6 then we need to make sure that selects don't show through.
  if (jQuery.browser.msie == true && jQuery.browser.version < 7) 
  {
    // If the iFrame exists...
        if ($('#iFrameHolder').length > 0)
        {
          // remove it.
          $('#iFrameHolder').remove();
        } else {
          // create a new iframe.
      var popup = $('#popup');
      var popupOffset = popup.offset({ border: true, padding: true });
      // Create an iframe and place it in the siteWideNavigation div.
      $('#siteWideNavigation').append('<iframe id="iFrameHolder" src="#" tabindex="-1" '
                                      +'style="display:block; position:absolute;'
                                      +'z-index:98;filter:Alpha(Opacity=\'0\');"></iframe>');
      
      // Set the location and width of the item.
      $('#iFrameHolder').width(popup.width()).height($(document).height() - $('#siteWideNavigation').height()-20);
      $('#iFrameHolder').css('left', popupOffset.left).css('top', $('#siteWideNavigation').height());
    }
  }
}

function goURL(url) {
     location.href=url;
}

// Prep the setup routine
$(document).ready(setup);