﻿$(document).ready(function() {
    var navlead = $("#logo a").attr("href");

    $("table:not(.calendar):not(.noArrow) tr td:nth-child(2) a").prepend("<span class='sideContentArrow'>&#9658</span>");
    $("tbody tr:first-child").attr("class", "headerTR");
    $("tbody tr:nth-child(2)").attr("class", "detailsTR");
    $("table tr td:first-child").css("padding-left", "5px");

    //only show third level ul's in the primary nav on the Products and Services menu item.
    var classNames = ["rms", "crs"],
		$productsmenu = $('#primary-nav > ul > li:eq(1)').addClass('products');
    $("#primary-nav > ul > li:not(:eq(1)) > ul > li > ul").remove();
    $productsmenu.find("> ul > li").addClass("first")
    .each(function(i) {
        //$(this).after(
              $(this).addClass(classNames[i])
                .find("ul > li")
                .addClass(classNames[i])
        //      );
        //$(this).find("ul").remove();
    });

    $(".relatedStoriesLink").before("<span class='sideContentArrow'>&#9658</span>");
    $(".newswrapper li, .eventlist li").prepend("<span class='sideContentArrow'>&#9658</span>");
    if ($.browser.msie && $.browser.version <= 7) {
        $(".relatedlinks ul li a").before("<span class='arrow'>&#9658</span>");
        $("#content-container ul.links li a").before("<span class='arrow'>&#9658</span>");
    }
    //$(".Subhead, .Subsubhead").each(function(i) { $(this).parent("p").css("margin-bottom", "0px"); });
    //    $(".Subsubhead").each(function(i) {
    //        $(this).html($(this).children("strong").html());
    //        $(this).addClass("Subhead").removeClass("Subsubhead");
    //    });
    $(".freeform-content p:first").css("margin-top", "0px");
    $("#footerlinks li:not(:last-child)").append(" | ");
    $('span.pdf').append('<img src="' + navlead + 'images/pdficon_small.gif" alt="pdf" width="12" height="12"/>');

    $(".txtSearch").focus(function() {
        $(this).val("");
    }).blur(function() {
        if ($(this).val() == "")
            $(this).val("Search Harlan.com for...");
    }).keyup(function(e) {
        if (e.which == 13) // enter key
        {
            window.location.href = navlead + 'search/-/?q=' + encodeURIComponent($(this).val());
            return false;
        }
    });

    $(".txtEmailNews").focus(function() {
        $(this).val("");
    }).blur(function() {
        if ($(this).val() == "")
            $(this).val("Email address");
    }).keyup(function(e) {
        if (e.which == 13) // enter key
        {
            $("#news-update input:last").click();
            return false;
        }
    });

    $("ul.storieslist li > a > img:eq(0)").css("width", "72px").css("height", "91px").css("margin-top", "5px");
    $("#BottomContent ul.storieslist li > a > img").css("width", "71px").css("height", "95px").css("margin-top", "-4px");
    $("ul.storieslist li > a > img:eq(1)").css("width", "72px").css("height", "95px").css("margin-top", "5px");
    $("ul.storieslist li > a > img:eq(2)").css("width", "72px").css("height", "96px").css("margin-top", "6px");
    jQuery.each(jQuery.browser, function(i) {
        if ($.browser.msie && jQuery.browser.version.substr(0, 1) == "6") {
            $("ul.storieslist li:eq(0)").css("margin-top", "-3px");
            $("ul.storieslist li:eq(1)").css("margin-top", "-1px");
            $("ul.storieslist li:eq(2)").css("margin-top", "-3px");
        }
    });

    $(".SearchButton").hover(function() {
        this.src = this.src.replace("ButtonSearch.png", "ButtonSearchHover.png");
    }, function() {
        this.src = this.src.replace("ButtonSearchHover.png", "ButtonSearch.png");
    });

    $("#primary-nav ul li:has(ul)").hover(function() {
        $("ul", this).addClass("hover"); //.css("top", this.offsetHeight + "px");
    }, function() {
        $("ul", this).removeClass("hover");
    });

    $("#primary-nav li:has(li)").hover(function() {
        $("ul", this).addClass("over"); //.css("top", this.offsetHeight + "px");
    }, function() {
        $("ul", this).removeClass("over");
    });
    $("#primary-nav li").hover(function() {
        $(this).addClass("hover");
    }, function() {
        $(this).removeClass("hover");
    });

    $(".subnavigation ul li ul li:has(ul)").find("span").css("cursor", "pointer").click(function() {
        var $this = $(this);
        $this.next().next().slideToggle("slow");
        var html = $this.html();
        if (html.indexOf("\u25BA") >= 0) {
            $this.html(html.replace(/\u25BA/, "\u25BC"));
        } else {
            $this.html(html.replace(/\u25BC/, "\u25BA"));
        }
    });

    // table rollup
    // option #1 - roll up rest of table if first row is clicked
    /*$("#content table:not(.calendar) tr:first-child>td").click(function() {
    $("tr:gt(0)", $(this).parent().parent()).toggle();
    $(this).parent().toggleClass("headerTR-collapse");
    setEqualHeight();	// reset page height?
    return false;
    }).each(function (i) {
    var bgImgWidth = 9;
    var bgPaddingRight = 5;
    $(this).parent().css("background-position", (this.offsetWidth - (bgImgWidth + bgPaddingRight)) + "px 50%");
    if ($.browser.msie && parseFloat($.browser.version) < 7)	// IE6 craziness
    {
    $(this).append("<span class=\"ie6-arrow\">&nbsp;</span>");
    }
    });*/
    // option #2 - roll up entire table following anything with a .rollup class (this class will have to be added to the FCK styles and xml)
    /*$("#content .rollup").click(function() {
    $(this).next("table").toggle();
    });*/

    $("a.video").objectOverlay({});


    // image map template
    if ($('div.imagemap').length) {
        $('div.imagemap div.subtitle').appendTo('#content-title');
        $('div.freeform strong:first').addClass('noborder');
    }

    // global map template
    if ($('#globalmap').length) {
        var preload = new Array();
        var hovermaps = new Array();
        preload[0] = 'image.axd/0f32fe50148249ab9540cebbdbda7ba7.png'; // north america
        preload[1] = 'image.axd/c510c36d1c2b4622848f6bd78d952bee.png'; // asia
        preload[2] = 'image.axd/ec4b69e7cbf04b969c0d9f1111c6859d.png'; // europe
        preload[3] = 'image.axd/97089a4b9141458f957e8e14aa244786.png'; // middle east
        $(document.createElement("img")).load(function() {
            if (preload[0]) {
                this.src = preload.shift();
                hovermaps.push(this.src);
            }
        }).trigger("load");

        $('#globalmap div.subtitle').appendTo('#content-title');
        var globalmapsrc = $('#globalmap img').attr('src');
        $('#globalmap area').mouseover(function() {
            var index = $('#globalmap area').index(this);
            $('#globalmap img').attr('src', hovermaps[index]);
        }).mouseout(function() {
            $('#globalmap img').attr('src', globalmapsrc);
        });
    }

    // contact us widget
    $('#contactUs select.country').change(function() {
        var $stateContainer = $('.state-container');
        if ($(this).val() == 'USA' || $(this).val() == 'Canada') {
            $stateContainer.fadeIn();
            $stateContainer.find('select').val($stateContainer.find('select option:first').val());
        }
        else {
            $stateContainer.hide();
            // select another value other than the first one to bypass the required filter
            //if ($stateContainer.find('select').val() == '0')
            $stateContainer.find('select').val($stateContainer.find('select option:eq(1)').val());
        }
    });

    $('#content-middle-right:has(#contactUs fieldset)').addClass('hasForm');

    if ($('#contactUs fieldset').length) {
        var msie6 = $.browser == 'msie' && $.browser.version < 7;
        if (!msie6) {
            var top = $('#contactUs').offset().top - parseFloat($('#contactUs').css('margin-top').replace(/auto/, 0));
            $(window).bind('scroll load', function() {
                var y = $(this).scrollTop();

                if (y >= top)
                    $('#contactUs').addClass('fixed');
                else
                    $('#contactUs').removeClass('fixed');
            });
        }
    }

    // table view options used in Online Lit and Cell Line References
    $('.table-viewoptions').each(function() {
        var $table = $(this).next(),
			$rowGroups = $table.find('td[scope="rowgroup"]'),
			$select = $(this).find('select'),
			$search = $(this).find('input.search');
			
		$rowGroups.parent().prev().addClass('last').end().andSelf().addClass('scope-rowgroup');
        $table.find('td[scope="row"]').parent().andSelf().addClass('scope-row');

        $rowGroups.each(function(i) {
            $('<option></option>').val(i).html($(this).text()).appendTo($select);
        });
        
        if ($select.find('option[value=-1][selected]').length == 0)
			$table.hide();
        
        $select.change(function() {
			var isInteger = /^-?\d+$/,
				val = $(this).val(),
				$rows = $table.find('tbody tr'),
				$rowsToShow;
            if (isInteger.test(val)) {
                $table.hide();
                if (val == -1) {
                    $rowsToShow = $rows.show();
                }
                else {
                    $rows.hide();
                    var $parentTR = $rowGroups.filter(':eq(' + val + ')').parent(),
						$nextTR = $rowGroups.filter(':eq(' + (parseInt(val) + 1) + ')').parent(),
						parentIndex = $rows.index($parentTR),
						nextIndex = $rows.index($nextTR);

                    if (nextIndex == -1)
                        $rowsToShow = $rows.slice(parentIndex).show();
                    else
                        $rowsToShow = $rows.slice(parentIndex, nextIndex).show();
                }
                $table.trigger('showing', [$rowsToShow]);
                $table.fadeIn('fast');
            }
        });
        
        $search.quicksearch($table.find('tbody tr'), {
            loader: 'span.loading',
            onBefore: function() {
                if (!$table.is(':visible'))
                    $table.show();
                $select.val($select.find('option:first-child').val());
                if ($table.find('td.templabel').length == 0) {
                    $table.addClass('templabel');
                    for (var x = 0; x < $rowGroups.length; x++) {
                        var $row = $rowGroups.filter(':eq(' + x + ')'),
							rowtext = $row.text(),
							$parentTR = $row.parent(),
							$nextTR = $rowGroups.filter(':eq(' + (x + 1) + ')').parent(),
							parentIndex = $table.find('tbody tr').index($parentTR) + 1,
							nextIndex = $table.find('tbody tr').index($nextTR);

                        if (nextIndex == -1)
                            $table.find('tbody tr').slice(parentIndex).prepend('<td class="templabel">' + rowtext + '</td>');
                        else
                            $table.find('tbody tr').slice(parentIndex, nextIndex).not(':has(.header)').prepend('<td class="templabel">' + rowtext + '</td>');
                    }
                    $table.find('td[rowspan]').each(function() {
                        $(this).data('rowspan', $(this).attr('rowspan')).removeAttr('rowspan');
                    });
                }
            },
            onAfter: function() {
				//alert('after');
                if ($search.val() == '') {
                    $table.removeClass('templabel').find('td.templabel').remove();
                    if ($select.find('option[value=-1][selected]').length == 0)
						$table.hide();
                    $table.find('td.scope-rowgroup').each(function() {
                        $(this).attr('rowspan', $(this).data('rowspan'));
                    });
                }
            }
        });

        $search.keyup(function(e) {
            if (e.keyCode == 27) // escape
            {
                $search.val('').trigger('keyup');
            }
        });
    });

    /* Cell Line References */
    $('table.cell-line').bind('showing', function(e, $rowsToShow) {
        var $modelList = $('#model-list');
        var $nudeMice = $rowsToShow.slice(1).find('td:nth-child(2)');
        $nudeMice = $nudeMice.add($rowsToShow.eq(0).find('td:nth-child(3)'));
        var nudeMiceCount = $nudeMice.filter(':has(img)').length;

        var $scidMice = $rowsToShow.slice(1).find('td:nth-child(3)');
        $scidMice = $scidMice.add($rowsToShow.eq(0).find('td:nth-child(4)'));
        var scidMiceCount = $scidMice.filter(':has(img)').length;

        var $nudeRats = $rowsToShow.slice(1).find('td:nth-child(4)');
        $nudeRats = $nudeRats.add($rowsToShow.eq(0).find('td:nth-child(5)'));
        var nudeRatCount = $nudeRats.filter(':has(img)').length;


        $modelList.find('div').hide();
        if (nudeMiceCount > 0) $modelList.find('div:eq(0)').show();
        if (scidMiceCount > 0) $modelList.find('div:eq(1)').show();
        if (nudeRatCount > 0) $modelList.find('div:eq(2)').show();

        $('#content-container .references').show();
		$('#content ol.references li a').unbind().attr('target', '_blank');
    });
    
    // show model list on Cell Line References page if hash passed in
    if ($('table.cell-line').length && window.location.hash.indexOf('#model-') == 0) {
        $('#content-container #model-list div').show();
    }

    // if there are references, link up any footnotes defined (used in Cell Line References)
    if ($('#content ol.references').length) {
        $('#content ol.references li').each(function(i) {
            $(this).attr('id', 'fn:' + (i + 1))
        });

        $('#content sup a').each(function() {
            var $this = $(this),
				id = $this.attr('href').replace('#', ''),
				refid = $this.parent().attr('id'),
				$footnote = $('#content ol.references li[id="' + id + '"]');

            $this.mouseover(function() {
                $('#footnote-hover').remove();
                $('<div id="footnote-hover"></div>')
					.append($footnote.html())
					.append('<img src="' + navlead + 'images/exitdisclaimer.gif" width="12" height="12" alt="View the reference"/>')
					.find('a').attr('title', 'View the reference').end()
					.appendTo('body')
					.css({ left: $this.offset().left, top: $this.offset().top })
					.mouseover(function() {
						$(this).stop().css('opacity', '1');
					}).mouseout(footnoteFade);
            })
			.mouseout(footnoteFade)
			.click(function() {
			    $footnote.addClass('selected');
			    $('<a href="#' + refid + '" class="back" title="Go back"><img src="' + navlead + 'images/back.png" width="13" height="10" alt="Back"/></a>').appendTo($footnote).click(function() {
			        $(this).remove();
			        $footnote.removeClass('selected');
			    });
			});
        });
    }
    function footnoteFade() {
        $('#footnote-hover').fadeOut('slow', function() {
            $(this).remove();
        });
    }

    /* toggle used in Online Lit CRS */
    var $toggle = $('ul.toggle');
    if ($toggle.length) {
        if ($.browser.msie && $.browser.version < 9) {
            $toggle.find('li:first-child').addClass('first');
            $toggle.find('li:last-child').addClass('last');
            $toggle.before('<span id="toggle-before">View by:</span>');
        }

        $toggle.find('li').click(function() {
            var index = $toggle.find('li').index(this),
				$divs = $toggle.siblings('div');
            $(this).siblings().removeClass('selected').end().addClass('selected');
            $divs.hide().eq(index).fadeIn('fast');
        }).eq(0).trigger('click');
    }

    // news item page
    $(".news-location").prependTo(".news p:first");

    //Google event to track individual download links
    var link = {
        href: "",
        _url: function() {
            var key = "/download.axd/";
            return this.href.substr(key.length);
        },
        extension: function() {
            return this._url().substr(33, 3);
        },
        filename: function() {
            return this._url().substr(this._url().search("/?d=") + 3);
        },
        path: function() {
            return this.filename() + "." + this.extension();
        }
    };

    $('a[href*="/download.axd/"]').bind("click", function(e) {
        link.href = $(this).attr("href");
        _gaq.push(['_trackPageview', '/downloads/' + link.path()]);
    });
    $('a[href*="http:/"]').each(function() {
        $(this).click(function() {
			var popup = $(this).attr('target') == "_blank";
            recordOutboundLink($(this).attr("href"), "Outbound Links", $(this).attr("href"), popup);
            if (!popup)
				return false;
        });
    });
});

function recordOutboundLink(link, category, action, popup) {
    try {
        var myTracker = _gat._getTrackerByName();
        _gaq.push(['_trackEvent', category, action]);
        if (!popup)
			setTimeout('document.location = "' + link + '"', 100);
    } catch (err) { }
}
