// New async GA code

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-4305842-5']);
_gaq.push(['_setCookiePath', '/lib/']);
_gaq.push(['_trackPageview']);

(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

$(document).ready(function() {
    //Truncate the side menu if it is longer than the main page content
    //Only do this if L1 element is selected with a sub-mneu, or if an L2 is selected
    var navHeight = $('#navigation').height();
    var contHeight = $('#content').height();
    if (navHeight>contHeight && $('#sidemenu li>a.L1sel').parent().next('li:has(a.L2)').length + $('#sidemenu li a.L2sel').length){
        $('#sidemenu li a.L2sel').parent().prevAll('li:has(a.L1)').first().children().addClass('retain');
        $('#sidemenu li a.L1:not(.retain)').parent().remove();
    }

    //Remove quicklink if we are already on the page
    var hostRegEx = new RegExp("^https?://" + location.hostname);
    var pageUrl = location.href.replace(hostRegEx,'');
    $('#navigation2 li a[href="'+pageUrl+'"]').parent('li').remove();

    // Fix table widths
    // If we have the promoPanels, set to 100%, otherwise 80%
    // Most pages use promopanels for MyAccount, but we want full tables for forms
    // if ($('#promoPanels').length == 0) {
    //    $('table:not(.data)').addClass('narrowTable');
    //} else {
        $('table:not(.data)').addClass('fullTable')
    //}

    // Athens authentication check
    var athensCookie = $.cookie('athens');
    var visitorCookie = $.cookie('visitor');
	if (athensCookie === null && visitorCookie === null) {
            $("#lisSearchBox #catalogue").hide();
            $('.rightMessage > a').attr("href", "/lib/resources/logging_in.aspx")
            $("#loginMessage").append('<p><span class="authFail">Please <a href="http://www.wlv.ac.uk/athens">log in</a> to enable the search and use electronic resources</span><br /></p><p><span>Visitors: <a href="javascript:void(0)" onclick="javascript:setVisitor();">enable search for this session</a> but you will not be able to use any electronic resources</span></p>')
        } else if (athensCookie) {
            $("#loginStatus").append('<span class="authSuccess">Logged in</span>');
        } else if (visitorCookie) {
            $("#loginStatus").append('<span class="authFail">Visitor mode<br /><a href="http://www.wlv.ac.uk/athens">log in</a></span>');
        }

    // Mime type icons
    // Add pdf icons to pdf links
    $("a[href$='.pdf']:not(:has(img))").addClass("pdf");

    // Add txt icons to document links (doc, rtf, txt)
    $("a[href$='.doc']:not(:has(img)), a[href$='.docx']:not(:has(img)), a[href$='.txt']:not(:has(img)), a[href$='.rft']:not(:has(img))").addClass("doc");

    // Add zip icons to Zip file links (zip, rar)
    $("a[href$='.zip']:not(:has(img)), a[href$='.rar']:not(:has(img))").addClass("zip");

    // Add email icons to email links
    $("a[href^='mailto:']:not(:has(img))").addClass("email");

    //Add external link icon to external links -
    $('a').filter(function() {
            //Compare the anchor tag's host name with location's host name
        return this.hostname && this.hostname !== location.hostname;
      }).addClass("external");

   // Find any links to embedded Google calendars and embed them in an iFrame
   // Immediacy cannot do this with the embed site plugin as it does not like the src param
   $('a[href*="www.google.com/calendar/embed"]').each(function(){
        $(this).replaceWith('<iframe src="' + $(this).attr("href") + '" height="500" frameborder="0" style="border: 0" scrolling="no"></iframe>');
    });

   // Fix American date format on blog posts

    $('.BlogItem .CreatedDate').each(function() {
        var blogDate = $(this).text().split(" ");
        var MDY = blogDate[0].split("/");
        var GBDate = MDY[1] + "/" + MDY[0] + "/" + MDY[2] + " " + blogDate[1];
        if (blogDate.length == 3)
        {
            GBDate = GBDate + " " + blogDate[2];
        }
        $(this).text(GBDate);
    })

   // Google analytics including event tracking

   // Add virtual page view for search tracking
   if (location.href.match(/\/search\.aspx$/i)){
    var lisSearchTerms = escape($("input[id$='searchTerms']").val());
    if ( !(lisSearchTerms == "search%20keywords%20here") && !(lisSearchTerms == "Search%20the%20website") ){
        _gaq.push(['_trackPageview', '/search?q=' + lisSearchTerms]);
    }
   }
        // Set up regex to remove hostname from URLs
        var hostRegEx = new RegExp("^https?://" + location.hostname, "i");
        var wlvLibRegEx = new RegExp("^https?://www.wlv.ac.uk/lib", "i");
        var wlvRegEx = new RegExp("^https?://www.wlv.ac.uk", "i");

        // Quick Links event tracking
        $('#navigation2 a').each(function(){
            var href = $(this).attr('href');
            $(this).click(function() {
                var quicklink = href.replace(hostRegEx, '');
                _gaq.push(['_trackEvent', 'Quick Link', quicklink]);
            });
        });
        
       var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;

        $('a[href]').each(function(){
            var href = $(this).attr('href');
            var linkclass = $(this).attr('class');
            var linkText = $(this).text().replace(/[\n]+/g, ' ');
            if ((href.match(wlvLibRegEx)) && (!href.match(/\.aspx$/i))){
                $(this).click(function(){
                    var friendly = href.replace(wlvRegEx, '');
                    _gaq.push(['_trackPageview', friendly]);
                });
            }
            else if ((href.match(wlvRegEx)) && (!href.match(wlvLibRegEx))){
                $(this).click(function() {
                    var wlvLink = href.replace(wlvRegEx, '');
                    _gaq.push(['_trackEvent', 'WLV Link', wlvLink, linkText]);
                });
            }
            else if ((href.match(/^https?\:/i)) && (!href.match(document.domain))){
                $(this).click(function() {
                    var extLink = href.replace(/^https?\:\/\//i, '');
                    _gaq.push(['_trackEvent', 'External', extLink, linkText]);
                });
            }
            else if (href.match(/^mailto\:/i)){
                $(this).click(function() {
                    var mailLink = href.replace(/^mailto\:/i, '');
                    _gaq.push(['_trackEvent', 'Email', mailLink]);
                });
            }
            else if (href.match(filetypes)){
                $(this).click(function() {
                    var filePath = unescape(href.replace(/^.*\//i, ''));
                    _gaq.push(['_trackEvent', 'Download', filePath]);
                });
            }
        });

        // Conditional script loads
        // Only load some scripts on certain pages
        var currentPage = location.href.replace(/^.*\//, '');

        if (currentPage.match(/^book_a_session/i)) {
            $.getScript('/lib/templates/default/js/date.js', function() {
                $.getScript('/lib/templates/default/js/infobites_sessions.js');
            });
        }
        if (currentPage.match(/^site_map/i)) {
            $('H1:contains(Site Map)').appendTo($('#contentHead'));
        }
        if (currentPage.match(/^trials.aspx/i)) {
            noTrialDatabases();
        }
    });

