// Last published: 10 Feb 2012 12:31


function togObj(theClass){
    var el = getElements(theClass);
    this.showIE = function(){ 
        if(document.all){    
            for ( i=0;i<el.length;i++ ) {
                el[i].style.visibility="visible";
                }
            }
        }
    this.hideIE = function(){ 
        if(document.all){
            for ( i=0;i<el.length;i++ ) {
                el[i].style.visibility="hidden";
                }
            }
        }
}


(function($){           
    $.fn.popupWindow = function(instanceSettings){
        
        return this.each(function(){
        
        $(this).click(function(){
        
        $.fn.popupWindow.defaultSettings = {
            centerBrowser:0, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
            centerScreen:0, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
            height:500, // sets the height in pixels of the window.
            left:0, // left position when the window appears.
            location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
            menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
            resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
            scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
            status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
            width:500, // sets the width in pixels of the window.
            windowName:null, // name of window set from the name attribute of the element that invokes the click
            windowURL:null, // url used for the popup
            top:0, // top position when the window appears.
            toolbar:0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
        };
        
        settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});
        
        var windowFeatures =    'height=' + settings.height +
                                ',width=' + settings.width +
                                ',toolbar=' + settings.toolbar +
                                ',scrollbars=' + settings.scrollbars +
                                ',status=' + settings.status + 
                                ',resizable=' + settings.resizable +
                                ',location=' + settings.location +
                                ',menuBar=' + settings.menubar;
                settings.windowName = this.name || settings.windowName;
                settings.windowURL = this.href || settings.windowURL;
                var centeredY,centeredX;
            
                if(settings.centerBrowser){
                        
                    if ($.browser.msie) {//hacked together for IE browsers
                        centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
                        centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
                    }else{
                        centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
                        centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
                    }
                    window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
                }else if(settings.centerScreen){
                    centeredY = (screen.height - settings.height)/2;
                    centeredX = (screen.width - settings.width)/2;
                    window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
                }else{
                    window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus();    
                }
                return false;
            });
            
        });    
    };
})(jQuery);
  
//  Expando plugin    
    (function($) {
         $.fn.gpExpando = function(options, callback) {
           
              // default options - these are used when no others are specified
              $.fn.gpExpando.defaults = {
                slideToggleSpeed: 400,
                closedAncClass: "expand",
                openAncClass: "contract",
                closedAncTitle: "Show contents",
                openAncTitle: "Hide contents"
              };
           
           // build main options before element iteration
              var o = $.extend({}, $.fn.gpExpando.defaults, options);
               this.each(function() {
                 var thisExpando = $(this);
                 $(thisExpando).wrapInner('<div></div>');
           
                 var $firstHeading = $($('div:first h2:first, div:first h3:first, div:first h4:first, div:first .showhide_toggle', thisExpando).get(0)); //Get the first heading from the selected and assign it to a variable
                 $firstHeading
                    .wrapInner('<a href="#" title="'+o.closedAncTitle+'" class="gpExpandoAnc '+o.closedAncClass+'"></a>')
                    .insertBefore($('div:first', thisExpando))
                    .addClass('gpExpandoHeading');
                 $('div:first', thisExpando).hide();
              
                 $('.gpExpandoAnc', thisExpando).click(function() {
                    var     $thisAnc = $(this),
                        $heading = $thisAnc.parent(),
                        $thisDiv = $heading.next('div'),
                        thisContent = $thisAnc.html(),
                        thisAltContent = ($heading.attr('data-altcontent')) ? $heading.attr('data-altcontent') : thisContent; //If altcontent exists define it, otherwise use thisContent
                    
                    if (!$thisDiv.is(":animated")){
                            try {
                                if  ($thisDiv.css('display')=='none') {
                                    slideView(o.openAncTitle, o.openAncClass, o.closedAncClass, thisContent, thisAltContent);
                                    $thisDiv.show('blind', o.slideToggleSpeed);
                                } else {
                                    slideView(o.closedAncTitle, o.closedAncClass, o.openAncClass, thisContent, thisAltContent)
                                    $thisDiv.hide('blind', o.slideToggleSpeed);
                                }
                            } catch(e) {
                                //$thisDiv.slideToggle(o.slideToggleSpeed);
                                $thisDiv.addClass('no-jqui iezoom');
                            }
                            if ($thisDiv.hasClass('no-jqui')) {
                                $thisDiv.toggle();
                            }
                    }
                    function slideView(title, classtoadd, classtoremove, content, altcontent){
                        $heading.attr('data-altcontent', content);
                        $thisAnc.attr('title', title)
                            .addClass(classtoadd)
                            .removeClass(classtoremove)
                            .html(altcontent);
                    };
                    return false;
                 });
              
              });
                  
              return this;
           };
        //  invoke the function we just created passing it the jQuery object
    })(jQuery);  

(function($) {
    $.fn.gpFormFieldHider = function(options, callback) {
        
            // default options - these are used when no others are specified
            $.fn.gpFormFieldHider.defaults = {
                inputParentClass: ".inputParent",
                hiddenId: "opt_fields_",
                actionType: 'slide'
            };
        
            // build main options before element iteration
            var o = $.extend({}, $.fn.gpFormFieldHider.defaults, options);
            this.each(function() {
                var thisHidden = $(this);
                var height = $(thisHidden).height();
                var optFieldRegEx = new RegExp('\\b'+o.hiddenId+'(\\S+)\\b'); 
                var thisInput = $(this).attr('id').match(optFieldRegEx)[1].replace(/\./g, '\\.'); 
                var inputName = $('#'+thisInput).attr('name'); 
                
                function performAction(first) {
                    if ($('#'+thisInput).is(':checked') ) {
                        if (o.actionType == 'fade') {
                            $(thisHidden).fadeIn();
                        } else if (o.actionType == 'disable'){
                            $(thisHidden).find('input, textarea, select').each(function() {
                                $(this).removeAttr("disabled");                            
                            });
                        } else if (o.actionType == 'slide'){
                            $(thisHidden).show().animate({ height : height }, { duration: 200 });
                        }    
                    } else {                    
                        if (o.actionType == 'fade') {
                            if (first == 'yes') {
                                $(thisHidden).hide();
                            } else {
                                $(thisHidden).fadeOut();
                            }
                        } else if (o.actionType == 'disable'){
                            $(thisHidden).find('input, textarea, select').each(function() {
                                $(this).attr("disabled", "disabled");
                            });
                        } else if (o.actionType == 'slide'){
                            if (first == 'yes') {
                                $(thisHidden).animate({ height: 0 }, { duration: 1, complete: function () { 
                                    $(thisHidden).hide();
                                } 
                                });
                            } else {
                                $(thisHidden).animate({ height: 0 }, { duration: 200, complete: function () {
                                    $(thisHidden).hide();
                                } 
                                });
                            }
                        }
                    }
                };
                
                performAction('yes'); 
                $('input[type=radio][name='+inputName+'], #'+thisInput).click(function(){ 
                    performAction();
                });
            });
            return this;
        };
        
    })(jQuery);
  
(function($) {
    $.fn.gpMoreExpander = function(options, callback) {
    
        // default options - these are used when no others are specified
        $.fn.gpMoreExpander.defaults = {
            clickableEl: '<img alt="More actions" src="/assets/images/icons/cogs.gif">',
            ancTitle: 'Show more actions'
        };
    
        // build main options before element iteration
        var o = $.extend({}, $.fn.gpMoreExpander.defaults, options);
        this.each(function() {
            
            // Build the html structure and create the variables
            var thisClass = ($(this).attr('class').split(' ')[0]); // Grab the first class from ul (so that other classes can also be added if wanted)
            $(this).addClass(thisClass + 'js').removeClass(thisClass).wrap('<div class="' + thisClass + 'div"></div>');
            var moreitemsdiv = $(this).parent('.' + thisClass + 'div');
            var moreitemsanc = $('<a title="'+ o.ancTitle +'" href="#" class="' + thisClass + 'anchor">'+ o.clickableEl +'</a>');
            $(moreitemsdiv).prepend(moreitemsanc);
            var activeClass = thisClass + 'active';
            var moreitemsdiv = '.' + thisClass + 'div' // Re-use this variable to mean all divs
            var moreitemsul = '.' + thisClass + 'js'
            
            // Hide if clicking anywhere other than the link
            $('body').click(function() {
                hideList();
            });
            // Bind the show to the focus and the click
            $(moreitemsanc).bind("focus click", function(event){
                showList(this);
                return false; // Stop the body click from affecting the anchor click and prevent default action on the link.
            });
            // Hide the list when leaving the last li in the list
            $(moreitemsul).find('li:last-child a').blur(function(){
                hideList();
            });
            //functions
            function showList(this_anchor){
                var thismoreitemsdiv = $(this_anchor).parent(moreitemsdiv);
                
                
                $(moreitemsdiv).removeClass(activeClass);
                $(thismoreitemsdiv).addClass(activeClass);
                return false
            };
            function hideList(){
                $(moreitemsdiv).removeClass(activeClass);
            }
        });
        return this;
    };
    
})(jQuery);

(function($){

    $.fn.gpChangeTag = function(options, callback) {
        var settings = {
            'tag' : 'span',
            'copyAttributes' : []
        };        
        if (options) {
            $.extend(settings, options);
        }
        $(this).after(function() {
            var $attr = '';
            var $element = $(this);
            $.each(settings['copyAttributes'], function(key, val) {
                $attr = $attr + ' ' + val + '="' + $element.attr(val) + '"';
            });
            return '<' + settings['tag'] + $attr + ' />';
        });
        $(this).next(settings['tag']).html($(this).html());
        $newtag = $(this).next(settings['tag']);
        $(this).remove();
        return $newtag;
    };

    $.fn.gpOverlay = function(action, color) {
        if (typeof color == "undefined")
            {
            color = 'transparent';
            }
        if (action == "add")
        {
            $(this).before('<div class="gp_overlay" style="width: '+$(this).outerWidth()+'px; height: '+$(this).outerHeight()+'px; z-index: 1; position: absolute; background: url(\'/assets/images/icons/indicator_big.gif\') no-repeat 50% 50% '+color+';"></div>');
            $(this).prev('div.gp_overlay').fadeTo(0,0.5);
            return $(this);
        }
        
        if (action == "remove")
        {
            $(this).prevAll('div.gp_overlay').remove();
            return $(this);
        }
    };

    $.fn.gpPromoItem = function() {
        $(this).each(function() {    
            $(this).find('.trail').hide();
            if ($(this).hasClass('horizontal'))
            {
                $(this).hover(function() {
                    $(this).find('.trail').stop(true, true).fadeTo(600,0.8);
                }, function() {
                    $(this).find('.trail').stop(true, true).fadeOut(800);
                });
            } else {
                var $hidden = true;
                $(this).bind('mouseenter', function() {
                    $(this).children('*').stop(true, true);
                    if ($hidden)
                    {
                        $hidden = false;
                        $(this).find('.trail').fadeTo(0,0.8).show('blind', {}, 800);
                    }
                });
                $(this).bind('mouseleave', function() {
                    $(this).children('*').stop(true, true);
                    if (!$hidden)
                    {
                        $hidden = true;
                        $(this).find('.trail').hide('blind', {}, 1200);
                    }
                });
            }
        });
    }; 

    $.fn.gpMessageBox = function() {
        $(this).css('position', 'relative');
        if ($(this).hasClass('info_message_box') || $(this).hasClass('success_message_box')) {
            $(this).prepend('<span class="close_message_box" style="position: absolute; top: 2px; right: 6px; font-size: 0.85em;"><a href="#">[ x ]</a></span>');
            $(this).find('.close_message_box a').bind('click', function() {
                $(this).closest('div[class*=_message_box]').fadeTo(300,0.01,function() {
                    $(this).hide('blind');
                });
                return false;
            });
        }
    };

    $.fn.gpScrollLast = function(element) {
        $(this).scrollTop('0');
        $(this).scrollTop($(element,$(this)).last().position().top);
        return $(this);
    };
})(jQuery);
 
$.fn.reorder = function() {
 
  function randOrd() { return(Math.round(Math.random())-0.5); }
 
  return($(this).each(function() {
    var $this = $(this);
    var $children = $this.children();
    var childCount = $children.length; 
    if (childCount > 1) {
      $children.remove(); 
      var indices = new Array();
      for (i=0;i<childCount;i++) { indices[indices.length] = i; }
      indices = indices.sort(randOrd);
      $.each(indices,function(j,k) { $this.append($children.eq(k)); }); 
    }
  }));
}
    
    function checkSelection(arrayid, thisAnc) {
        var $inputs = thisAnc.parents('.checkselect').find('input');
        $inputs.each(function(){
            var $this = $(this);
            if ($.inArray($this.attr('value'), arrayid) != -1) { //inArray returns index so -1 means it doesn't exist.
                $this.attr('checked', true);
            }
        });    
    }
        
$(document).ready(function() {
    
    $.extend({
        gpImageRollover: function(pairings) {
            $.each(pairings, function(k,v) {
                $(k).live('mouseenter', function() {
                    $(this).data('start', $(this).attr('src'));
                    explode = $(this).attr('src').split('/').reverse();    
                    image = explode[0].slice(explode[0].indexOf('.'));
                    new_url = v+image;
                    for (var i = 1; i < explode.length; i++)
                        {
                        new_url = explode[i] + '/' + new_url;
                        }
                    $(this).data('new_url', new_url);
                    $(this).attr('src', $(this).data('new_url'));
                }).live('mouseleave', function() {
                    $(this).attr('src', $(this).data('start'));
                });
            })
        }
    });
    
    $.gpImageRollover({
        'img.close_rollover' : 'cross_2',
        'img.tick_rollover' : 'tick_2',
        'img.flag_rollover' : 'flag',
        'img.question_rollover' : 'question_2',
        'img.edit_rollover' : 'cogs_2'
    });
    
    $('div.randomWithin').reorder();
    
    $('table:not(.nozebra).simpledatatable tr:odd td').addClass('odd');
    $('table:not(.nozebra).simpledatatable tr:even td').addClass('even');
    
    $('table:not(.nozebra).simpledatatable tr td.even.nozebra').removeClass('even');
    $('table:not(.nozebra).simpledatatable tr td.odd.nozebra').removeClass('odd');
    
    $(".browser_back").before('<div><a href="#" onclick="history.back(); return false;">Previous page</a></div>').remove();
    
    $( '.splitlist2col ol, .splitlist2col ul').each(function() {
          var classes = $(this).attr('class');
          if($(this).is("ol")) { var ordered = true; }
          var colsize = Math.round($(this).find("li").size()/2);
          $(this).find("li").each(function(i) {
               if (i>=colsize) {
                    $(this).addClass('right_col');                    
               }
            });
          if(ordered) {
               $(this).find('.right_col').insertAfter(this).wrapAll('<ol start="' + (colsize+1) + '" class="' + classes + '"></ol>');                
          } else {
                $(this).find('.right_col').insertAfter(this).wrapAll('<ul class="' + classes + '"></ul>');            
            }                
     });
    $('.splitlist2col ul .right_col, .splitlist2col ol .right_col').parent().after('<div class="clear"> </div>');
    $('.splitlist2col ul, .splitlist2col ol').wrap('<div style="float: left; width: 49.9%;"></div>'); 
    $('.splitlist2col ol li').css('margin-left', '0.5em');
    
    
    $('input.fck_js').removeAttr("disabled");
    
    $('.fck_disabled_message').remove();
    
    $('*[class*=colminheight]').each(function(index) { 
        var cmheight = $(this).attr('class').match(/\bcolminheight(\d+)\b/)[1];             
    
        $(this).css({
                'min-height' : cmheight+'px'
                })
                .height (cmheight+'px'); 
    });
    
        
    $('*[class*=colmaxheight]').each(function() {
        var cmheight = $(this).attr('class').match(/\bcolmaxheight(\d+)\b/)[1];
        $(this).css({'max-height':cmheight+'px', 'overflow':'auto', 'position':'relative'});
    });
    
    $('*[class*=vertalign]').each(function(index) { 
        var wrapHeight = $(this).attr('class').match(/\bvertalign(\d+)\b/)[1];             
        if ($.browser.msie) {
            $(this).css('margin-top', ((wrapHeight - $(this).attr('height'))/2)+'px');
        } else {
            margTop = (wrapHeight - this.height)/2;
            $(this).css('margin-top', margTop+'px');
            $(this).load(function() {
                margTop = (wrapHeight - this.height)/2;
                $(this).css('margin-top', margTop+'px');
            });
        }
    });
    
    $('.checkselect p:first').append('<span class="smalltext margleft"><a class="margright selectall" href="#">Select all</a> | <a class="margleft margright deselectall" href="#">Deselect all</a></span>');
    $('.selectall, .deselectall').click(function(){
        var $thisAnc = $(this);
        var $inputs = $thisAnc.parents('.checkselect').find('input');
        ($thisAnc.hasClass('selectall')) ?  $inputs.attr('checked', true) : $inputs.attr('checked', false);
        return false
    });
    $('body').addClass('js'); 
    $('.showhide_small').gpExpando();
    $('.showhide_large').gpExpando( {  
       closedAncClass: "expand_large",
       openAncClass: "contract_large"
    });
        
    $('.moreitems').gpMoreExpander();   
    $('div[id^=opt_fields_]').gpFormFieldHider(); //Grab divs that start with opt_fields_
    $('div[id^=disabled_opt_fields_]').gpFormFieldHider({actionType: 'disable', hiddenId:'disabled_opt_fields_'});
    $('div[id^=fade_opt_fields_]').gpFormFieldHider({actionType: 'fade', hiddenId:'fade_opt_fields_'});
});

$(document).ready(function(){
  $('#nav_menu_1').before('<a id="open_all" class="offscreen" href="#">Screen reader users can click here to open all menus</a>');
  $("#menu_column ul li").not("#menu_column ul li ul li").each(function(){
        checkCookie(this);    
    });
    
    function checkCookie(li) {
        var menu_index = $(li).index();
        var menu_id = $(li).parent().parent().attr('id');
        var cookie_state = $.cookie(menu_id + '_' + menu_index);
        
        if(cookie_state === null || cookie_state === '0') {
            $('ul', li).hide();
            $("a", li).not("#menu_column ul li ul li a").addClass('closed'); // Add class of closed to top level headings to add rounded corners
            $("span", li).addClass('closed'); // Add class of closed to top level headings to add rounded corners
            if ($(li).children('ul').length) {
                $(li).children('a, span').before('<div class="toggle nav_arrow_light_down"></div>');
             } 
            else {
                $(li).not("#menu_column ul li ul li").addClass('no_toggle'); // If no children add no_toggle class
            }
        };
        
        if(cookie_state === '1') {
            $(li).children('a, span').before('<div class="toggle nav_arrow_light_up"></div>');
        };
    }
//ARIA Support
    navi = 1;
    $('#nav_menu_1').find('ul').first().attr('role','navigation').end().end().find('ul li ul').each(function() {
        $(this).attr('id', 'navMenu' + navi).attr('role','group').siblings('.toggle').attr('aria-controls', 'navMenu' + navi).attr('tabindex', '0').attr('role','button').each(function() {
            if ($(this).siblings('ul:visible').size()) {
                $(this).attr('aria-expanded', 'true');
            } else {
                $(this).attr('aria-expanded', 'false');
            }
        });
        navi++;
    });
        
     $('#menu_column #open_all').click(function(){ // For screen reader users - Opens all menus
        $('#menu_column .toggle').each(function(){
            $(this).attr('aria-expanded','true');
            if($(this).hasClass('nav_arrow_light_down')){
                $(this).siblings('ul').slideDown('fast');
                $(this).removeClass('nav_arrow_light_down');
                $(this).addClass('nav_arrow_light_up');
                $(this).next().removeClass("closed");
                changeCookie(this)
            }
        });
    });
    
    function changeCookie(toggle) {
        if($(toggle).hasClass('nav_arrow_light_down')){
                var menu_index = $(toggle).parent().index();
                var menu_id = $(toggle).parent().parent().parent().attr('id');
                $.cookie(menu_id + '_' + menu_index, '0', { path: '/' })
            }else{
                var menu_index = $(toggle).parent().index();
                var menu_id = $(toggle).parent().parent().parent().attr('id');
                $.cookie(menu_id + '_' + menu_index, '1', { path: '/' });
            }
    }
    
     $('.toggle').click(function(){
      var thistoggle = $(this);
      if($(thistoggle).hasClass('nav_arrow_light_down')){
                $(this).siblings('ul').slideDown('fast');
                $(this).removeClass('nav_arrow_light_down');
                $(this).addClass('nav_arrow_light_up');
                $(this).next().removeClass("closed");
                $(thistoggle).attr('aria-expanded','true');
                changeCookie(this)
            } else {
                $(this).siblings('ul').slideUp('fast', function(){
                    $(thistoggle).next().addClass("closed");
                });
                $(this).addClass('nav_arrow_light_down');
                $(this).removeClass('nav_arrow_light_up');
                $(thistoggle).attr('aria-expanded','false');
                changeCookie(this)
            }    
        return false
     });
    $('.toggle').keypress(function(e) {
        if (e.which == 13) {
            $(this).click();
            return false;
        }
    });
    // Below funtion is for use with the checkSelection function and the taxonomic array in jsp
    $('.checkselect.nationality p:first-child span').append(' | <a class="margleft margright eea" href="#">All EEA</a> | <a class="margleft margright noneea" href="#">All Non-EEA</a> | <a class="margleft margright africa" href="#">All Africa</a> | <a class="margleft margright southamerica" href="#">All South America</a> | <a class="margleft margright asia" href="#">All Asia</a>');
                
    $('.checkselect.nationality p span a').click(function(e){
        var $thisAnc = $(this);
        if ($thisAnc.hasClass('eea')) {
           checkSelection(eeaarray, $thisAnc);
        } else if ($thisAnc.hasClass('noneea')) {
            checkSelection(noneeaarray, $thisAnc);
        } else if ($thisAnc.hasClass('africa')) {
            checkSelection(africaarray, $thisAnc);
        } else if ($thisAnc.hasClass('southamerica')) {
           checkSelection(southamericaarray, $thisAnc);
        } else if ($thisAnc.hasClass('asia')) {
            checkSelection(asiaarray, $thisAnc);
        }
        e.preventDefault();
    });
});

