﻿  
/* Toggle element display */
function showHide() {

    var text = document.getElementById("full-text");
    var link = document.getElementById("expand-text-link");
    
    if(text.style.display == "block" || text.style.display == ""){
        text.style.display = "none";
    } else {
        text.style.display = "block";
        link.style.display = "none";
    }
}


/* Document switching */
function showdoc(){

    var dprev = document.getElementById("preview");
    var dfull = document.getElementById("full");

    dprev.className = "hide";
    dfull.className = "show";
}

function hidedoc() {

    var dprev = document.getElementById("preview");
    var dfull = document.getElementById("full");

    dprev.className = "show";
    dfull.className = "hide";
}

function expandBreadcrumbs() {
    $("#icon-expand").hide();
    $("#bccollapsable").show();
}


/* Makes the bullets within links clickable */           
function clickableBullets() {

    /* 
        To-do:
        Replace this clunky function with some semantic HTML and decent CSS.
        -Vince
    */
    
    function followTo(loc) {
        window.location = loc;
    }

      $('span.hand').each(function() { 
        var $hand = $(this);
        
        $(this).next('a').each(function() { 
            var loc = $(this).attr('href');                      
            $hand.click(function(){ window.location.href = loc; });
        });
        
    });
};



/* Opens links with rel=external in a new window */
function externalLinksInNewWindow() {
    $('a[rel~="external"]').attr('target', '_blank');
}



/* Function to assign events to links that open pop-up windows */
function initPopupLinks() {
    $(".popup-link").click(function(e) {
        e.preventDefault();
        var href = $(this).attr("href");        
        var newWindow = window.open(href, "_blank", 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=750,height=500,left=50,top=25');
        if (window.focus) { newWindow.focus() }        
    });
};



/* Hide empty elements on Company profile Dashboard */
$(function() {
    $("#company-info div:empty").hide();
});



/* Set focus on first element of forms */
$(function() {
    var usernameInput = document.getElementById("username");
    if (usernameInput != null) {
        usernameInput.focus();
    }
    else {
        $("input:text:visible:first").focus();
    }
});



/* Expands short pages to fill browser viewport */
function expandToFillViewport() {
    var viewportHeight = $(window).height();
    var body = $('.main-wrapper');
    var bodyHeight = body.height();

    if (bodyHeight < viewportHeight) {
        body.css('min-height', viewportHeight + 'px');
    }
     
}



/* Create tooltips */
var toolTipShowDuration = 50;
var toolTipHideDuration = 300;
function toolTips() {
    $('span.toolTipTrigger').click(function() { toolTipTrigger(this); });
    $('.close-button').click(function() {
        $(this).parent().fadeOut(toolTipHideDuration);
    });
    
}

function toolTipTrigger(el) {
     if (!el)
         el = this;
   
    var targetName = $(el).attr("toolTipFor");
        
    var targetToolTip = $('div#' + targetName);

    if (targetToolTip.css('display') == "none") {
        $(".filterToolTip").not("#" + targetName).fadeOut(toolTipHideDuration);

        var ttTop = $(el).position().top - targetToolTip.height() - 5,
        ttLeft = $(el).position().left + $(el).width() + 5;

        if (targetToolTip.attr("id") == "filterToolTip-city" && $.browser.msie && $.browser.version < 8) {
            ttTop = ttTop + 50;
        }                
        
        targetToolTip.css({
            "top": ttTop + "px",
            "left" : ttLeft + "px" 
        });

        targetToolTip.show('drop', toolTipShowDuration);
                
    } else {
        targetToolTip.fadeOut(toolTipHideDuration);        
    }

    targetToolTip.find('.close-button').unbind().click(function(e) {
        e.preventDefault();
        targetToolTip.fadeOut(toolTipHideDuration);
    });    
    
    return false;
}



/* Omniture */
function OmnitureClick(clickname, ltv, pagename) {
    if (typeof (window['s']) != 'undefined' && typeof (window['s']) != 'string') {
        // Put the click name in an sprop if defined
        var addClickNameProp = typeof (window['CustomClickPropNumber']) != 'undefined';
        if (addClickNameProp) {
            eval('s.prop' + CustomClickPropNumber + ' = clickname;s.eVar' + CustomClickPropNumber + ' = clickname;');
            var ltvToAdd = 'prop' + CustomClickPropNumber + ',eVar' + CustomClickPropNumber;
            if (ltv && ltv.length > 0)
                ltv = ltv + ',' + ltvToAdd;
            else
                ltv = ltvToAdd;
        }
    
        // linkTrackVars
        if (ltv)
            s.linkTrackVars = ltv;
        else
            s.linkTrackVars = '';
        
        // click name / page name
        var c;
        if (pagename)
            c = pagename + '.' + clickname;
        else
            c = clickname;

        // call the click
        s.tl(this, 'o', c);
        if (addClickNameProp) { // clear the custom click prop so it is not sent on the automatic exit link tracking
            eval('s.prop' + CustomClickPropNumber + ' = null;s.eVar' + CustomClickPropNumber + ' = null;');
        }
    }
    return true;
}

function OmniturePageView(pagename) {
    s.pageName = pagename;
    s.t();
}


// Reg 3 images for focus on checking input
function checkingAccountBullet() {
    //Checking account info popup
    $('#routing').focus(function() {
        $(this).siblings('.focus-bullet').fadeIn();
        $('#routing-img').fadeIn();
    });

    $('#routing').blur(function() {
        $(this).siblings('.focus-bullet').fadeOut();
        $('#routing-img').fadeOut();
    });

    $('#account').focus(function() {
        $(this).siblings('.focus-bullet').fadeIn();
        $('#account-img').fadeIn();
    });
    $('#account').blur(function() {
        $(this).siblings('.focus-bullet').fadeOut();
        $('#account-img').fadeOut();
    });
}



//Adjust Research center column heights
function researchCenterColumns() {
    var leftColumnHeight = $('#tools_sidebar').height();
    var mainColumnHeight = $('#mrc_content').height() - 100;

    if (leftColumnHeight > mainColumnHeight) {
        $('#contentlist').css('min-height', leftColumnHeight - 58 + 'px');
    };

};



/* What's this? */
function initReadMoreLessLinks() {
    $("#readwholedoclink").mouseover(function() {
        $(this).css('cursor', 'pointer');
    });

    //**SHOW FULL TEXT
    $("#readwholedoclink").click(function() {
        $("#spnReadMore").hide();
        $("#full").show();
    });

    //**SHOW less
    $("#readlessdoclink").click(function() {
        $("#spnReadMore").show();
        $("#full").hide();
    });
}

var o_rtime = new Date(1, 1, 2000, 12, 00, 00);
var o_timeout = false;
var o_delta = 200;

(function ($) {
    $.fn.outerHTML = function () {
        return $(this).clone().wrap('<div></div>').parent().html();
    }
})(jQuery);


/* Overlay */
function showOverlay(contentId) {
    document.getElementById("search_field_inp").blur();

    var $overlay = $('<div id="overlay-background">'),
    $content = $('<div id="overlay-content">');

    $("body").append($overlay).append($content);

    $content.html($("#" + contentId).outerHTML());
    var $scrollContent = $content.find(".scrollable");
    fitContentToViewport($content, $scrollContent);
    
    if (navigator.userAgent.indexOf("MSIE 6") > -1) {        
        $overlay.css({ 'position' : 'absolute', 'height': $(window).height() + 'px' }).show();
        $content.center().show();
        $('select').css('visibility', 'hidden');
    } else {
        $overlay.css({ "visibility": "visible"  }).fadeTo(100, .5);
        $content.center().css('visibility', 'visible').fadeTo(100, 1);
    }

    //fix z-index issues with IE7
    if ($.browser.msie && $.browser.version < 8) {
        $(".midcontent .fixwidthinner").css("z-index", "1001");
        $content.parent().css("z-index", "1000");
    }

    $(window).unbind("resize").resize(function() {
        // set a delay for IE7, so things resize correctly
        if ($.browser.msie && $.browser.version < 8) {
            o_rtime = new Date();
            if (o_timeout === false) {
                o_timeout = true;
                setTimeout(function() {
                    overlayResizeEnd($content, $scrollContent);
                }, o_delta);
            }
        }
        else {
            fitContentToViewport($content, $scrollContent);
            $content.center();
        }
    });

}

function overlayResizeEnd($content, $scrollContent) {
    if (new Date() - o_rtime < o_delta) {
        setTimeout(function() {
            overlayResizeEnd($content, $scrollContent);
        }, o_delta);
    } else {
        o_timeout = false;
        fitContentToViewport($content, $scrollContent);
        $content.center();
    }
}

function hideOverlay() {
    var $overlay = $('#overlay-background'),
    $content = $('#overlay-content');
    
    $content.fadeTo(100, 0, function() {
        $content.css({ "visibility": "hidden" });          
    });
    $overlay.fadeTo(100, 0, function() {
        $overlay.css("visibility", "hidden");
    });

    if ($.browser.msie && $.browser.version < 8) {
        $(".midcontent .fixwidthinner").css("z-index", "");
        $content.parent().css("z-index", "");
    }

    $overlay.remove();
    $content.remove();

    $(window).unbind("resize");
}

function fitContentToViewport($content, $scrollContent) {
    var contentHeight = $content.height(),
    viewportHeight = $(window).height(),    
    padding = 50,
    newHeight,
    scrollableHeight = $scrollContent.height();
        
    if (scrollableHeight != null) {
        $scrollContent.css({ "max-height": "none", "height": "auto" });
        $content.css({ "max-height": "none", "height": "auto" });

        var scrollMinHeight = $scrollContent.css("min-height");
        newHeight = viewportHeight - (2 * padding) - (contentHeight - scrollableHeight);

        if (scrollMinHeight != "0px" && scrollMinHeight != undefined) {
            scrollMinHeight = scrollMinHeight.replace("px", "") - 0;
            if (newHeight < scrollMinHeight) {
                newHeight = scrollMinHeight;
            }
        }
        $scrollContent.css("max-height", newHeight + "px");
    }    
}

jQuery.fn.center = function(params) {

    var options = {
        vertical: true,
        horizontal: true
    }
    op = jQuery.extend(options, params);

    return this.each(function() {

        var ie6 = false;
        if ($.browser.msie && $.browser.version < 7) { ie6 = true };

        if (ie6) { window.scroll(0, 0); }

        var $self = $(this),
            width = $self.width(),
            height = $self.height(),
            paddingTop = parseInt($self.css("padding-top")),
            paddingBottom = parseInt($self.css("padding-bottom")),
            borderTop = parseInt($self.css("border-top-width")),
            borderBottom = parseInt($self.css("border-bottom-width")),
            mediaBorder = (borderTop + borderBottom) / 2,
            mediaPadding = (paddingTop + paddingBottom) / 2,
            positionType = $self.parent().css("position"),
            halfWidth = (width / 2) * (-1),
            halfHeight = ((height / 2) * (-1)) - mediaPadding - mediaBorder,
            viewportHeight = $(window).height();
        minPadding = 10,
            cssProp = {
                position: 'fixed'
            };

        if (ie6) {
            cssProp = {
                position: 'absolute'
            };
        }

        if (op.vertical) {
            cssProp.height = height;
            if (viewportHeight < height + (minPadding * 2)) {
                cssProp.top = minPadding + 'px';
                cssProp.marginTop = 0;
            }
            else {
                cssProp.top = '50%';
                cssProp.marginTop = halfHeight;
            }

            if (ie6) { cssProp.top = $(window).height() / 2 + "px"; }

        }
        if (op.horizontal) {
            cssProp.width = width;
            cssProp.left = '50%';
            cssProp.marginLeft = halfWidth;
        }
        if (positionType == 'static') {
            $self.parent().css("position", "relative");
        }
        $self.css(cssProp);

    });

};




//Primary nav flyout & hover
function primaryFlyoutHover() {

    var subnav = $('.subNav');
    var subnavMarcom = $('#subNavMarcom');
    var wasActive = false;

    $('#nav-mrc').hoverIntent(function() {
        if (subnav.is(':animated')) {
            return;
        } else {

            wasActive = $(this).hasClass('active');

            $(this).addClass('active');

            if ($.browser.msie) {

                $('#subNavMarcom').css('left', '0px');
                $('#subNavMarcom').css('width', '0');

                
                $(subnav).animate({
                    height: 'show'
                }, 150, function() {
                    $('#subNavMarcom').animate({
                        left: '-=17px',
                        width: '17px'
                    }, 50);
                }
                
                
                );
            } else {

                $(subnav).animate({ opacity: 0 }, 1);
                $('#subNavMarcom').animate({ opacity: 0 }, 1);
                $('#subNavMarcom').css('left', '0px');
                $('#subNavMarcom').css('width', '0');

                $(subnav).animate({
                    opacity: 1,
                    height: 'show'
                }, 150, function() {
                    $('#subNavMarcom').animate({
                        opacity: 1,
                        left: '-=17px',
                        width: '17px'
                    }, 100);
                }


                );
            }


        }
    },
    function() {

        if (!wasActive) {
            $(this).removeClass('active');
        }

        if ($.browser.msie) {
            $(subnav).animate({
                height: 'hide'
            }, 100);
        } else {
            $(subnav).animate({
                opacity: 0,
                height: 'hide'
            }, 200);
        }
    });


}


function zIndexWorkaround() {
    $(".subNav, .subnav li, .subnav li span, .subnav li a span").parents().each(function() {
        var p = $(this);
        var pos = p.css("position");

        if (pos == "relative" ||pos == "absolute" ||pos == "fixed") {

            p.hover(function() {
                $(this).addClass("on-top");
            },function() {
                $(this).removeClass("on-top");
            });
        }
    });
}

//Check if given input is empty or contains error string
function isInputEmpty($input, errStr) {
    if ($input.val() == "" || $input.val() == errStr) {
        $input.val(errStr).addClass("error-input");
        return true;
    }
    else {
        return false;
    }
}


//Run this stuff on load
$(document).ready(function() {

    $('li.subnav-disabled a').click(function() { return false });

    primaryFlyoutHover();
    initPopupLinks();
    checkingAccountBullet();
    toolTips();
    researchCenterColumns();
    initReadMoreLessLinks();
    zIndexWorkaround();
    clickableBullets();
    externalLinksInNewWindow();
    expandToFillViewport();
});

$(window).resize(function() {
    expandToFillViewport();
});
