/* VCA JS Library
* $Id: lib.js 378 2010-10-20 15:48:28Z nguillou $
*/

// CUFON STYLES
Cufon.replace('.home_slide_container h1', { fontFamily: 'Mesmer' });
Cufon.replace('.nav_tabbed_headline h1', { fontFamily: 'Helvetica Neue' });
Cufon.replace('.accordion_section h2, .modal h2, .archive h2', { fontFamily: 'Helvetica Neue' });
Cufon.replace('#carousel .slides a.btn_learnmore', { fontFamily: 'Helvetica Neue' });

// JQUERY FUNCTIONS
(function($){
    $(document).ready(function(){
    
// Give all homepage slider nav buttons IDs
        $('#home_hero_nav ul').find('li').each(function(i) {
            $(this).attr("id", "home_hero_nav_button_" + (1 + i) );
        });

// Header logo hover state
        $(".header_logo a").hover(
            function () {
                $(".header_logo").addClass("header_logo_hover");
            },
            function () {
                $(".header_logo").removeClass("header_logo_hover");
            }
        );


		$('#locations-dropdown').click(function() {
		switch($("#locations-dropdown-options").css('display')) {
			case "block":
				$("#locations-dropdown-options").css('display','none');
			break;
			case "none":
				$("#locations-dropdown-options").css('display','block');
			break;
		}
	});
	$('#locations-dropdown-options').hover(function(){
	      //$('#locations-dropdown-options').css('display','none');
	   }, function(){
	      $('#locations-dropdown-options').css('display','none');
	   });
	$('#locations-dropdown-options li a').click(function() {
		$('#locations-dropdown-options').css('display','none');
		$('#locations-dropdown').html($(this).html());
		$("#location").val($(this).html());
		$("#locations-dropdown-options li a").removeClass('selected');
		$(this).addClass('selected');
	});


// nav splitter
        $('#main_navigation li a').each(function(){
        
        var linkString      = $(this).text();
        var middleOfString  = linkString.length/2;
        var spacePos        = linkString.indexOf(' ');
        var spacesFound     = [];
        var newLinkString   = '';
        var distFromCenter  = 20;
        
        while(spacePos > -1) {
            spacesFound.push(spacePos);
            spacePos = linkString.indexOf(' ', spacePos+1);
        }
        if(spacesFound.length < 2){
            var linkArray = linkString.split(" ");
            for(var i=0; i<linkArray.length; i++){
                if(i==0){
                    newLinkString = '';
                }
                if(linkArray[i]!=' '){
                    if((linkArray.length-1)==i){
                        newLinkString += '<br />'+linkArray[i];
                    } else {
                        newLinkString += linkArray[i]+' ';
                    }
                }
            }
            $(this).html(newLinkString);
        } else {
            var indexKey;
            distFromCenter = spacesFound[0]-middleOfString;
            for(var j=0; j<spacesFound.length; j++) {
                if(distFromCenter == 0){
                    indexKey = j;
                    var linkArray = linkString.split(" ");
                    for(var i=0; i<linkArray.length; i++){
                        if(i==0){
                            newLinkString = '';
                            if(indexKey == 0){
                                indexKey = 1;
                            }
                        }
                        if(i==indexKey){
                            newLinkString += '<br />'+linkArray[i]+' ';
                        } else {
                            newLinkString += linkArray[i]+' ';
                        }
                    }
                    $(this).html(newLinkString);
                    break;
                } else {
                    if((Math.abs(distFromCenter)) > (Math.abs(spacesFound[j]-middleOfString))){
                        distFromCenter = spacesFound[j]-middleOfString;
                        indexKey = j;
                    }
                    if(j==spacesFound.length-1){
                        var linkArray = linkString.split(" ");
                        var indexCounter = 0;
                        for(var i=0; i<linkArray.length; i++){
                            if(linkArray[i]== ' '){
                            } else {
                                if(i==0){
                                    newLinkString = '';
                                    if(indexKey == 0) {
                                        indexKey = 1;
                                    }
                                }
                                if(i==indexKey*2){
                                    newLinkString += '<br />'+linkArray[i]+' ';
                                } else {
                                    newLinkString += linkArray[i]+' ';
                                }
                            }
                        }
                        $(this).html(newLinkString);
                    }
                }
            }
        }
    }
    );

// Adding first-element to content copy first element
        $('.content_copy').each(function(){
            $(this).children().first().css('margin-top', '5px');
        });

// Homepage hero slider
        $('#loopedSlider').loopedSlider({
            autoStart: 5800,
            slidespeed: 400
        });

// Global search box - clear on focus       
        $("input.header_search_input").focus(function() {
                if( this.value == this.defaultValue ) {
                    this.value = "";
                }
            }).blur(function() {
                if( !this.value.length ) {
                    this.value = this.defaultValue;
            }
        });

// Alternating Row Colors
        $("div.accordion").each(function() {
            $(this).find("h3.ui-accordion-header:odd").addClass('odd');
            $(this).find("div.ui-accordion-content:odd").addClass('odd');
        });
        $("#archive li:odd").addClass('odd');

// Tabbed Navigation
        $(".nav_tabbed_container div ul").find("li").each(function(i) {
            $(this).attr("id", "tab_sel_" + (1 +i) ); // set id on each tab
        });
        
        $(".content_column_tabbed").find(".content").addClass("tabbed_hidden"); // hide all tabs
        
        var theHash = document.location.hash;
        theHash = theHash.split("_");
        var openTab = theHash[1];
        var totalTabs = $('.nav_tabbed ul li').length;
        
        $('a').click(function() {
            var link = $(this).attr('href');
            if (link != null) {
                link = link.split('#');
                var currentUrl = window.location.href;
                currentUrl = currentUrl.split('#');
                if (link[0] == currentUrl[0]) {
                    var newTab = link[1];
                    newTab = newTab.split('_'); 
                    $(".nav_tabbed li").removeClass("active"); // remove active classes from all tabs
                    $(".nav_tabbed ul li:nth-child("+newTab[1]+")").addClass("active"); // set current tab as active
                    $(".content_column_tabbed").find(".content").addClass("tabbed_hidden"); // hide content from all tabs
                    $(".content_column_tabbed #content_tabs_"+newTab[1]).removeClass("tabbed_hidden");// show selected tab content
                }
            }
        });
        
        if(theHash[0] == "#tab" && openTab <= totalTabs) {
            $(".content_column_tabbed #content_tabs_"+openTab).removeClass("tabbed_hidden"); //show selected tab
            $(".nav_tabbed ul li:nth-child("+openTab+")").addClass("active"); // set selected tab as active
        } else {      
            $(".content_column_tabbed #content_tabs_1").removeClass("tabbed_hidden"); //show first tab
            $(".nav_tabbed ul li:first").addClass("active"); // set first tab as active
        }
        
        $('.nav_tabbed_container div ul li').click(function() {
            $(".nav_tabbed li").removeClass("active"); // remove active classes from all tabs
            $(this).addClass("active"); // set current tab as active
            $(".content_column_tabbed").find(".content").addClass("tabbed_hidden"); // hide content from all tabs
            var currtab = $(this).attr("id").replace("tab_sel_", ""); // find id of selected tab
            $(".content_column_tabbed #content_tabs_" + currtab).removeClass("tabbed_hidden"); // show selected tab content
            // Update content column height for custom scrolling.
            conColHeight = $('.content_column').height();
            if ((conColHeight < relColHeight)
                && (conColHeight >= relColHeightInit)
	    ) {
                $('.related_column').css('height', conColHeight + 'px');
                relColHeight = $('.related_column').height();
            } else if (conColHeight < relColHeight) {
                // Related column is now too big, resize to initial.
                $('.related_column').css('height', relColHeightInit + 'px');
                relColHeight = $('.related_column').height();
            }
            $(window).trigger('customscroll');
        });
        
// Target = _blank (rel=external)
        $('a[rel=external]').attr('target','_blank');

// jQuery UI Accordion
        var icons = {
            header: "closed",
            headerSelected: "open"
        };
    
        $(".accordion").accordion({
            collapsible: true,
            autoHeight: false,
            navigation: true,
            active: false,
            icons: icons
        });
        
// Call to action button hover and clickability
        $("p.cta_button").hover(
            function () {
                var buttonUrl = $(this).find('a').attr('href');
                $(this).addClass("cta_button_hover");
                window.status = buttonUrl;
                return true;
            },
            function () {
                $(this).removeClass("cta_button_hover");
                window.status = '';
                return true;
            }
        );

        $("p.cta_button").click(function() {
            var buttonUrl = $(this).find('a').attr('href');
            window.location.href = buttonUrl;
        });


// jCarouselLite
        $("#carousel .slides").jCarouselLite({
            btnNext: "#carousel .next",
            btnPrev: "#carousel .prev",
            visible: 4,
            scroll: 1
        });
        
// Location map
        $("#map a[rel].mtrigger").overlay({
            mask: {
                color: '#000',
                loadSpeed: 200,
                opacity: 0.35
            }
        });
        
// Physician Popup
        $("#carousel a[rel].modal_link").each(function() {
            $(this).attr('href','')
        });
        $("#carousel a[rel].modal_link").overlay({
            mask: {
                color: '#000',
                loadSpeed: 200,
                opacity: 0.35
            }
        });
        
// Related column scrolling
        if ($('#site_page')) {
            $('#site_page .cta_container').css('z-index', '0');
            $('#site_page .header_container,#site_page .nav_container,#site_page .subnav_container,#site_page .footer_container').css('position', 'relative').css('z-index', '2');
            var conColHeight = $('.content_column').height();
            var relColHeightInit = $('.related_column').height();
            var relColHeight = relColHeightInit;
            var footerHeight = $('.footer_container').height(); // height of footer
            var windowHeight = $(document).height(); // height of entire page
            var scrollTop = $('.content_column').position().top; // top scroll point
            var containerOffset = $('.cta_container').height(); // height of scrolling container
            var scrollBottom = windowHeight - footerHeight - containerOffset - 50; // point to stop scrolling

            $(window).bind('customscroll', function() {
                // Disable IE6
                if (! $.browser.msie || parseInt($.browser.version) > 6) {
                    var currScroll = $(window).scrollTop();
                    //footerHeight = $('.footer_container').height(); // height of footer
                    windowHeight = $(document).height(); // height of entire page
                    //scrollTop = $('.content_column').position().top; // top scroll point
                    //containerOffset = $('.cta_container').height(); // height of scrolling container
                    scrollBottom = windowHeight - footerHeight - containerOffset - 50; // point to stop scrolling

                    // Try not to do this very often.
                    if (conColHeight != relColHeight && conColHeight > relColHeight) { // Only scroll if the content column is larger than the related column

                        // Set the height of the related column to be the same as the content column
                        $('.related_column').css('height', conColHeight + 'px');
                        relColHeight = $('.related_column').height();
                    }
                    if (conColHeight == relColHeight) { // Only scroll if the content column is larger than the related column

                        // Stop scrolling at the bottom
                        if (currScroll >= scrollBottom) {
                            $('#site_page .cta_container')
                                .css('position', 'relative')
                                .css('top', (conColHeight - containerOffset) + 'px')
                                .css('zoom', '1');
                        }

                        else if (currScroll > scrollTop) {
                            $('#site_page .cta_container')
                                .css('position', 'fixed')
                                .css('top', '0px');
                        }

                        // Stop scrolling at the top
                        else {
                            $('#site_page .cta_container')
                                .css('position', 'relative')
                                .css('top', '0px')
                                .css('zoom', '1');
                        }
                    }
                }
            });

            // Update content column height for custom scrolling.
            $('.accordion').bind('accordionchange', function (event, ui) {
                conColHeight = $('.content_column').height();
                if ((conColHeight < relColHeight)
                    && (conColHeight >= relColHeightInit)
                ) {
                    $('.related_column').css('height', conColHeight + 'px');
                    relColHeight = $('.related_column').height();
                } else if (conColHeight < relColHeight) {
                    // Related column is now too big, resize to initial.
                    $('.related_column').css('height', relColHeightInit + 'px');
                    relColHeight = $('.related_column').height();
                }
                $(window).trigger('customscroll');
            });


            // Use custom scrolling function for sliding sidebar.
            $(window).scroll(function () {
                $(window).trigger('customscroll');
            });

        }

// Carousel hover states
    $('#carousel .prev').hover(
        function () {
            $(this).addClass('prev_hover');
        },
        function () {
            $(this).removeClass('prev_hover');
        }
    );

    $('#carousel .next').hover(
        function () {
            $(this).addClass('next_hover');
        },
        function () {
            $(this).removeClass('next_hover');
        }
    );

    $('.btn_learnmore_inactive').hover(
        function () {
            $(this).removeClass('btn_learnmore_inactive');
            $(this).addClass('btn_learnmore_hover');
        },
        function () {
            $(this).removeClass('btn_learnmore_hover');
            $(this).addClass('btn_learnmore_inactive');
        }
    );

// add phoneUS, zip validation type to js validation
        jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
            phone_number = phone_number.replace(/\s+/g, ""); 
            return this.optional(element) || phone_number.length > 9 &&
                phone_number.match(/^(\(?\d\d\d\)?)?( |-|\.)?\d\d\d( |-|\.)?\d{4,4}(( |-|\.)?[ext\.]+ ?\d+)?$/);
        }, "Please specify a valid phone number");

        jQuery.validator.addMethod("zip", function(zip_code, element) {
            zip_code = zip_code.replace(/\s+/g, ""); 
            return this.optional(element) || zip_code.match(/^\d{5}([\-]\d{4})?$/);
        }, "Please specify a valid zip code");

// Freeform validation
        $('#freeform').validate({
            rules: {
                confirm_email: {
                    required: true,
                    equalTo: "#email"
                }
            },
            messages: {
                confirm_email: {
                    required: "Please enter the same email as above",
                    equalTo: "Please enter the same email as above"
                }                
            }
        });


// Nav fix for IE6
if ($.browser.msie && $.browser.version.substr(0,1)<7) {
	$('#home_hero_nav_button_3 a span').css('position', 'relative');
	$('#home_hero_nav_button_3 a span').css('top', '-9px');
}




    });
})(jQuery); 

