$(function(){
	
	// Security requirement from MBVT. Only used on the home page, and if the user clicks the Username field in the sign in form.
	if($("body#index").length == 1)
	{
		var snippetID = '65239',
		host = 'www.splash-screen.net',
		sn = document.createElement('script');
		sn.setAttribute('async', true);
		sn.setAttribute('type', 'text/javascript');
		sn.setAttribute('src', (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//' + host + '/' + snippetID + '/' + 'splash.js');
		var s = document.getElementsByTagName('script')[0];
		s.parentNode.insertBefore(sn, s);

		function showSplash(){
			try { splashScreen(); }
			catch(e) {}
		}
		
		$("#userNumber").focus(function(){
			showSplash();
		});
	}

    $("#right_column .add_tooltip").tooltip({ 
       events: {def:"click,mouseleave"}, 
       effect: 'slide',
       relative: true,
       offset: [20, -40]
    }).bind("click", function(){
        return false;
    });
    
    $("#sub_nav .add_tooltip, #menu_how .add_tooltip").tooltip({ 
       events: {def:"click,mouseleave"}, 
       effect: 'slide',
       relative: true,
       offset: [20, 40]
    }).bind("click", function(){
        return false;
    });
    
    $(".tooltip .close").click( function() { 
        $(this).parent().parent().hide();
    });
    
    $('a.popup').popUp();

    /* Locations */
    
    $('#my_address_label').perfectForm();
    
    // Control My Address on Locations
    $('#find_a_branch_label').hide();
    $('#find_a_branch').val('Enter Zip Code');
    $('#find_a_branch').click(function() {
        $('#find_a_branch').val('');
    });
    
    $('#find_a_branch').blur(function() {
     if($(this).val() == '') {
         $('#find_a_branch').val('Enter Zip Code');
     }
    });


    /* FAQs */                     
    $('.faq div.answer, .job_openings div.description').hide();

    $('.faq h4').click(function(){
        if($.browser.msie)
        {
            // Hide all
            $('.faq div.answer').hide();   
            // Show specific
            var item = $(this).attr('rel');
            $('.'+ item).show();
        }
        else
        {
            // Hide all
            $('.faq div.answer').slideUp();   
            // Show specific
            var item = $(this).attr('rel');
            $('.'+ item).slideDown();
        }
    });
    
    $('.job_openings h4').click(function(){
        $('.job_openings div.description').hide();                     
        $(this).next().show();
        return false;
    });

    /* Modal */  
    $(".modal_click").overlay({
        mask: {
            loadSpeed: 200
        },
        closeOnClick: true,
        onBeforeLoad: function() {
            // grab wrapper element inside content
            var wrap = this.getOverlay().find(".modal_content_wrap");
            // load the page specified in the trigger
            wrap.load(this.getTrigger().attr("href"));
        }
    });
    
    $(".open_modal").colorbox({
        onLoad:function(){
            // append inner images
            $('#cboxMiddleLeft').html('<div class="middleLeftSupplement"></div>');
            $('#cboxMiddleRight').html('<div class="middleRightSupplement"></div>');
            $('#cboxBottomLeft').html('<div class="bottomLeftSupplement"></div>');
            $('#cboxBottomRight').html('<div class="bottomRightSupplement"></div>');
            $('#cboxBottomCenter').html('<div class="bottomCenterSupplement"></div>');
        },
        onComplete:function() {
            initAjaxForms('#cboxLoadedContent');
        }
    });

    $('.open_modal_inline').each(
        function() {
            var data = $(this).attr("data");
            data = (typeof data != "undefined") ? data.split("|") : false;
            var extra_width = 0;
            if($.browser.msie && $.browser.version < 9){
                extra_width = 10;
            }
            
            var width = data[0] ? parseInt(data[0]) + extra_width : 640;
            var height = data[1] ? parseInt(data[1]) + extra_width : 385;

            $(this).colorbox({
                onLoad:function(){
                    // append inner images
                    $('#cboxMiddleLeft').html('<div class="middleLeftSupplement"></div>');
                    $('#cboxMiddleRight').html('<div class="middleRightSupplement"></div>');
                    $('#cboxBottomLeft').html('<div class="bottomLeftSupplement"></div>');
                    $('#cboxBottomRight').html('<div class="bottomRightSupplement"></div>');
                    $('#cboxBottomCenter').html('<div class="bottomCenterSupplement"></div>');
                },
                innerWidth: width, 
                innerHeight: height,
                inline: true
            });
        }
    );
    
    $(".open_modal_iframe").each(function(){
        
        var data = $(this).attr("data");
        data = (typeof data != "undefined") ? data.split("|") : false;
        
        extra_width = 0;
        if($.browser.msie && $.browser.version < 9){
            extra_width = 10;
        }
        
        var width = data[0] ? parseInt(data[0]) + extra_width : 640;
        var height = data[1] ? parseInt(data[1]) + extra_width : 385;
        
        $(this).colorbox({
            iframe: true,
            innerWidth: width, 
            innerHeight: height,
            onLoad:function(){
                // append inner images
                $('#cboxMiddleLeft').html('<div class="middleLeftSupplement"></div>');
                $('#cboxMiddleRight').html('<div class="middleRightSupplement"></div>');
                $('#cboxBottomLeft').html('<div class="bottomLeftSupplement"></div>');
                $('#cboxBottomRight').html('<div class="bottomRightSupplement"></div>');
                $('#cboxBottomCenter').html('<div class="bottomCenterSupplement"></div>');
            }
        });
    })    
                           
    /* Tools */                        
    $(".tools:last").addClass('last')

    if($.browser.msie && $.browser.version < 8)
    {
        var mouseover = false;
        
        var showPopup = function()
        {
            var li = $(this);
            // hard code the width of pop up div
            var number_of_li = li.find('.popup_wrapper .popup ul:first').children().length;
            
            // Subtract 10px from the width of four columns.  Otherwise subtract 8px.
            if(number_of_li == 4) {
                var width = (number_of_li * 235) - 10;
            } else {
                var width = (number_of_li * 235) - 8;
            }
            
            $("#supernav li").find('.popup_wrapper').each(function(){
                if($(this).hasClass('popup_show')) $(this).removeClass('popup_show');
            });
            
            li.find('.popup_wrapper .popup').css('width', width);
            li.find('.popup_wrapper').addClass('popup_show');
            
            li.find('.popup_wrapper.popup_show').mouseenter(function(){
                $(this).addClass('popup_active');
            });
        }
        
        var hidePopup = function()
        {
            if( ! $(this).hasClass('popup_active')) $(this).find('.popup_wrapper').removeClass('popup_show');
            $(this).find('.popup_wrapper').removeClass('popup_active');
        }
    } 
    else
    { 
        var showPopup = function()
        {
            $(this).find('.popup_wrapper').stop(true, true).delay(600).slideDown();
        }
        
        var hidePopup = function()
        {
            $(this).find('.popup_wrapper').stop(true, true).slideUp();
        }
    }
    
    var config = {    
         over: showPopup,     
         timeout: 0,  
         out: hidePopup  
    };

    $("#supernav li.top").hoverIntent(config);
    
    
    
    
     /* Hover State for Main Nav */
    $('#supernav li.top').hover ( function() {
        // fixes tooltips layering underneath the navigation

        // console.debug(hThis);
        $('#supernav_container').css('z-index', '8001');
        $('#supernav').css('z-index', '8002');
        // end tooltip fix

        $(this).parent().addClass('active_border_removal'); 


        if($('#supernav li a').hasClass('current')) {
            $('.current').removeClass('current').addClass('current_placeholder'); 
        }
        $('.popup').hover( function (){
            $(this).parent().parent().parent('.top').children('a').addClass('currentSupernav');
        }, function (){
            $(this).parent().parent().parent('.top').children('a').removeClass('currentSupernav');
        });
    }, function() {
        // fixes tooltips layering underneath the navigation
        $('#supernav_container').css('z-index', '0');
        $('#supernav').css('z-index', '0');
        // end tooltip fix

        $('.current_placeholder').addClass('current').removeClass('current_placeholder');
        $(this).parent().removeClass('active_border_removal'); 

    });
    
    
    
    
    
    $('#site_search label').perfectForm();
    //$('#my_address_label').perfectForm();
    
    $('.promo_container').bigClick();

    if(!vendor)
    {
        $('a[href^="http"]')
            .not('a[href^="http://' + window.location.host + '"]')
            .not('a[href^="https://' + window.location.host + '"]')
            .not('.open_modal, .open_modal_iframe')
            .each(function(){
                var full_original_url = $(this).attr('href');
                var original_url = parseUri($(this).attr('href')).host;
                var url = original_url.replace('www.', '');
                var name = $(this).text();
                name = name ? name : url;
            
                if( ! new RegExp('^(' + external_link_exceptions + ')$').test(url))
                {
                    $(this).attr('rel', '#exit_overlay').click(function(){
                        $('#exit_overlay #external_link span.name').html('<a href="'+ full_original_url +'">'+ name +'</a>');
                        $('#exit_overlay #external_link span.url').html(full_original_url);
                        $('#exit_overlay a.continue').attr('href', full_original_url);
                    }).overlay();
                }    
          });
    }
    
    $('#sign_in fieldset').show();
    $('#account_type').change(function(){
        var val = $(this).val();
        if(val != "")
        {
            $('#sign_in .redirect').show();
            $(this).parent('li').hide();
            window.location = val;
        }
    });

    $('.jump_menu').change(function(){
        var val = $(this).val();
        if(val != "" && val != window.location)
        {
            window.location = val;
        }
    });
    
    $('#open_account_form').submit(function(){
        var val = $('#open_account').val();
        if(val != "")
        {
            window.location = val;
        }
        return false;
    });
    
    $('.zebra table tbody tr:odd').addClass('odd');
    
    // Set the widths of the rates table columns
    // $('.rates_table_wrapper th:eq(0)').width('20%');
    // $('.rates_table_wrapper th:eq(1)').width('15%');
    // $('.rates_table_wrapper th:eq(2)').width('10%');
    // $('.rates_table_wrapper th:eq(3)').width('10%');
    // $('.rates_table_wrapper th:eq(4)').width('15%');
    // $('.rates_table_wrapper th:eq(5)').width('25%');
    // $('.rates_table_wrapper th:eq(6)').width('5%');
    
    $('.print_rates').click(function(){
        window.print();
    });

    initAjaxForms();
});

jQuery.fn.perfectForm = function(options)
{
    var settings = {
        overlap: true,
        ignore: ''             
    }

    if(options) {
        jQuery.extend(settings, options);
    };

    this.not(settings.ignore).each(function(){
        var input = $(this).next('input, textarea');
        var label = $(this);
        
        // first check all inputs for values, then hide it's label if it has a value
        if( settings.overlap ) {
            label.addClass('overlap');
        }

        if( settings.overlap && input.val() != '' ) {
            label.hide();
        }
        
        label.click(function(){
            label.hide();
            input.focus();
        }, function(){
            if( input.val() == '' ) {
                label.show();
            }
        });
        
        // then add a focus event to all inputs to hide their labels when focused on, 
        // and remain hidden on blur if a value is entered
        input.focus(function(){
            label.hide();
        }).blur(function(){
            if( $(this).val() == '' ) {
                label.show();
            }
        });
    });
}


jQuery.fn.autoHeight = function(options) 
{
    var settings = {
        minHeight   : false,
        limitHeight  : false,
        ignore  : '',
        padding : 10
    }

    if(options) {
        jQuery.extend(settings, options);
    };

    var maxHeight = 0;

    this.not(settings.ignore).each(function(){
        if ($(this).height() > maxHeight){
            if(settings.limitHeight && maxHeight >= settings.limitHeight) {
                maxHeight = settings.limitWidth;
            } 
            else if(settings.minHeight && maxHeight <= settings.limitHeight)
            {
                maxHeight = settings.minHeight;
            } 
            else 
            {
                maxHeight = $(this).height();
            }
        }
    });  

    this.not(settings.ignore).height(maxHeight + settings.padding);

}


jQuery.fn.bigClick = function(options)
{
    var settings = {
        cssClass : 'clickable'
    }
    
    if(options) {
        jQuery.extend(settings, options);
    };
    
    this.each(function(){
        var anchor = $(this).find('a')[0];
        
        if(!anchor)
            return;         
        
        var href = $(anchor).attr('href');
        var title = $(anchor).attr('title');
        
        $(this).attr('title', title);
        
        $(this).mouseover(function(){
            $(this).css('cursor', 'pointer');
        });
        
        $(this).addClass(settings.cssClass).click(function(){
            window.location = href;
        });
    });
}



var getCookie = function(name){  
    var re=new RegExp(name+"=[^;]+", "i"); //construct RE to search for target name/value pair
    if (document.cookie.match(re)) //if cookie found
        return document.cookie.match(re)[0].split("=")[1]; //return its value
    return null;
};

var setCookie = function(name, value){
    document.cookie = name + "=" + value + "; path=/";
};



// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
var parseUri = function(str) {
    var o   = parseUri.options,
        m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
        uri = {},
        i   = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
    });

    return uri;
};

parseUri.options = {
    strictMode: false,
    key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
    q:   {
        name:   "queryKey",
        parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
        strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
        loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
    }
};
    
    /* Z-Index Fix For Colorbox in IE7 */
    if($.browser.msie && $.browser.version < 8)
    {
        $(function() {
            var zIndexNumber = 1000;
            $('#cboxWrapper div').each(function() {
                $(this).css('zIndex', zIndexNumber);
                zIndexNumber -= 10;
            });
            $('#cboxClose').css('zIndex', 1010);
            $('#cboxTopRight').css('zIndex', 10);
            
        });
    }





jQuery.fn.popUp = function(options)
{
    var settings = {
        name: 'newWindow',
        width: 500,
        height: 600,
        left: false,
        top: false,
        scrollbars: 'yes',
        resizeable: 'no',
        statusbar: 'no',
        menubar: 'no',
        toolbar: 'no'
    }

    if(options) {
        jQuery.extend(settings, options);
    };

    this.each(function(){
        $(this).click(function(){
            var rel = $(this).attr('data');
            var href = $(this).attr('href');
            if(!rel){
                window.open(href, settings.name);
            } else {
                var rel_split = rel.split('|');
                var width = rel_split[0] ? rel_split[0] : settings.width;
                var height = rel_split[1] ? rel_split[1] : settings.height;
                var scrollbars = rel_split[2] ? rel_split[2] : settings.scrollbars;
                var leftPos = settings.left ? settings.left : (screen.width-width)/2;
                var topPos = settings.right ? settings.right : (screen.height-height)/2;
                var config = 'width='+ width +',height='+ height +', \
                            left='+ leftPos +',top='+ topPos +', \
                            scrollbars='+ scrollbars +', \
                            resizable='+ settings.resizeable +', \
                            statusbar='+ settings.statusbar +', \
                            menubar='+ settings.menubar +', \
                            toolbar='+ settings.toolbar;

                window.open(href,settings.name, config);
            }
            return false;
        });
    });
}

function initAjaxForms(container) {
    if (typeof(container) != 'undefined')
    {
       formList = $(container).find('.ajax-form');
    } else {
        formList = $('.ajax-form');
    }
/*
    formList.each(function() {
console.log($(this).val());

        $(this).parent('form').ajaxForm({
            target: '#cboxLoadedContent',
            error:function(result) {
                console.log(result);
            }
        });
    });
    */
}

function csm_success_hook(data) {
    //console.log(data);

    if (data.title == "Error")
    {
        data.content += '<p><a href="">Try Again</a></p>';
    }

    return data;
}
