jQuery(document).ready(function () {
    /*** Begin Preloading Menu On States ***/

    var marketsOn = new Image();
    marketsOn = "/~/media/Ingenix/Site%20Shell/Navigation/menu_markets_on.gif";
    var problemsOn = new Image();
    problemsOn = "/~/media/Ingenix/Site%20Shell/Navigation/menu_problems_on.gif";
    var aboutOn = new Image();
    aboutOn = "/~/media/Ingenix/Site%20Shell/Navigation/menu_about_us_on.gif";
    var newsOn = new Image();
    newsOn = "/~/media/Ingenix/Site%20Shell/Navigation/menu_news_on.gif";
    var resourceOn = new Image();
    resourceOn = "/~/media/Ingenix/Site%20Shell/Navigation/menu_resource_center_on.gif";

    /*** End Preloading Menu On States ***/

    // Search overtype behavior
    jQuery("input.searchField").one("click", function () {
        // Check value
        if (jQuery(this).val().toLowerCase() == "search...") {
            // Clear the field
            jQuery(this).val("");
        }
    });

    // Zip code search overtype behavior
    jQuery("input.zipcodesearch").one("click", function () {
        // Check value
        if (jQuery(this).val().toLowerCase() == "enter zip code") {
            // Clear the field
            jQuery(this).val("");
        }
    });

    // Menu behavior
    jQuery("div.menu").children("div").children("ul").children("li").mouseenter(function () {
        if (!jQuery(this).parent("ul").parent("div").hasClass("contact") && !jQuery(this).parent("ul").parent("div").hasClass("login")) {
            // Highlight menu item
            jQuery(this).children("a").eq(0).children("img").attr("src", jQuery(this).children("a").eq(0).children("img").attr("src").replace(".gif", "_on.gif")).parent("a").next("ul").eq(0).show();
        }
    }).mouseleave(function () {
        if (!jQuery(this).parent("ul").parent("div").hasClass("contact") && !jQuery(this).parent("ul").parent("div").hasClass("login")) {
            // Remove menu item highlight
            jQuery(this).children("a").eq(0).children("img").attr("src", jQuery(this).children("a").eq(0).children("img").attr("src").replace("_on.gif", ".gif")).parent("a").next("ul").eq(0).hide();
        }
    });

    /*** Begin General Carousel Behavior ***/

    // See if we have any carousel elements
    if (jQuery("div.carousel").length > 0) {
        // Loop through all the carousel elements on a page
        jQuery("div.carousel").each(function () {
            // Set the pause variable
            paused = false;

            // Only start the carousel if there's more than one slide
            if (jQuery(this).children("ul.image").children("li").length > 1) {
                // Show the carousel controls
                jQuery(this).children("div.carouselControls").show();

                // Instantiate a counter
                var currentSlide = 0;

                // Get the number of (zero-indexed) slides
                var slideNum = parseInt(jQuery(this).children("ul.image").children("li").length) - 1;

                // Create a reference for the carousel object
                var thisCarousel = jQuery(this);

                // Set up an interval
                var carouselInterval = setInterval(function () {
                    // Check if the carousel is paused
                    if (paused == false) {
                        // Decide how to increment the counter
                        if (currentSlide == slideNum) {
                            // Reset the counter
                            currentSlide = 0;
                        }
                        else {
                            // Increment the counter
                            currentSlide++;
                        }

                        // Show the correct slide
                        thisCarousel.children("ul.image").children("li").removeClass("focused").eq(currentSlide).addClass("focused");

                        // See if there are tabs in this carousel
                        if (thisCarousel.children("ul.tabs").length > 0) {
                            // Advance the next slide
                            thisCarousel.children("ul.tabs").children("li").removeClass("on").eq(currentSlide).addClass("on");
                        }
                    }
                }, 5000);

                // Check if this carousel has a tab set or not
                if (thisCarousel.children("ul.tabs").length == 1) {
                    // Mouseover behavior
                    jQuery(this).children("ul.tabs").children("li").mouseover(function () {
                        // Clear the carousel interval
                        clearInterval(carouselInterval);

                        // Execute behavior only if we're mousing over an unhighlighted tab
                        if (!jQuery(this).hasClass("on")) {
                            // Remove the on class
                            jQuery(this).parent("ul.tabs").children("li").removeClass("on");

                            // Add the on class to this tab
                            jQuery(this).addClass("on");

                            // Change the carousel slide
                            jQuery(this).parent("ul.tabs").prev("ul.image").children("li").removeClass("focused").eq(jQuery(this).index()).addClass("focused");
                        }
                    });
                }
            }
        });
    }

    // Pause button behavior
    jQuery("img.carouselPause").click(function () {
        // Flip the paused toggle
        paused = !paused;

        if (paused == true) {
            // Grey out the button
            jQuery("img.carouselPause").css({ opacity: "0.5" });
        }
        else {
            // Bring back the button
            jQuery("img.carouselPause").css({ opacity: "1.0" });
        }
    });

    // Next/previous button behavior
    jQuery("img.carouselBack, img.carouselForward").click(function () {
        // Pause the carousel button
        paused = true;

        // Grey out the pause button
        jQuery("img.carouselPause").css({ opacity: "0.5" });

        // Figure out whether we're going forward or backwards
        var action = jQuery(this).attr("class");

        // Get the current index highlighted
        var currentIndex = jQuery("ul.image li.focused").index();

        // Get the total amount of slides (zero-indexed)
        var totalSlides = parseInt(jQuery("ul.image").children("li").length) - 1;

        // Switch on the recorded action
        switch (action) {
            // Go forward   
            case "carouselForward":
                // Check if we're at the last index
                if (currentIndex == totalSlides) {
                    // Reset the index
                    currentIndex = 0;
                }
                else {
                    // Increment the index
                    currentIndex++;
                }
                break;

            // Go backward   
            case "carouselBack":
                // Check if we're at the first index
                if (currentIndex == 0) {
                    // Reset the index
                    currentIndex = totalSlides;
                }
                else {
                    // Increment the index
                    currentIndex--;
                }
                break;
        }

        // Remove the focused state from all slides and highlight the proper index
        jQuery("ul.image li").removeClass("focused").eq(currentIndex).addClass("focused");
    });

    /*** End General Carousel Behavior ***/

    /*** Begin Tiny Carousel Behavior ***/

    if (jQuery("div.tinyCarousel").length > 0) {
        // Establish a markup array for the tiny carousels
        jQuery.tinyContents = [];
        jQuery.tinyPositions = [];

        // Cycle through each instance of the tiny carousel
        jQuery("div.tinyCarousel").each(function () {
            // Save this index
            var thisCarouselIndex = jQuery(this).index();

            // Establish a contents object for this carousel
            jQuery.tinyContents[thisCarouselIndex] = [];
            jQuery.tinyPositions[thisCarouselIndex] = [];

            // Get the slide width
            var slideWidth = parseInt(jQuery(this).children("div.tinyBody").children("ul.tinyContents").children("li").css("width"));

            // Cycle through the slides
            jQuery(this).children("div.tinyBody").children("ul.tinyContents").children("li").each(function () {
                // Determine the offset value
                var offset = jQuery(this).index() * slideWidth + "px";

                // Fill the contents of the relevant array with this carousel's items
                jQuery.tinyContents[thisCarouselIndex].push(jQuery(this).html());
                jQuery.tinyPositions[thisCarouselIndex].push(offset);

                // Set the absolute position of each slide
                jQuery(this).css({ position: "absolute", left: offset });
            });

            // Bind the control elements
            jQuery(this).children("div.tinyBody").children("div.leftControl, div.rightControl").click(function () {
                // Set up the new markup
                var newMarkup = new String();


                // Determine which way to go
                switch (jQuery(this).hasClass("leftControl")) {
                    // Left button   
                    case true:
                        // Pop the first element off the the contents array
                        var firstElement = jQuery.tinyContents[thisCarouselIndex].shift();

                        // Push the first element onto the end of the array
                        jQuery.tinyContents[thisCarouselIndex].push(firstElement);
                        break;

                    // Right button   
                    case false:
                        // Pop the last element off of the contents array
                        var lastElement = jQuery.tinyContents[thisCarouselIndex].pop();

                        // Unshift the last element onto the beginning of the contents array
                        jQuery.tinyContents[thisCarouselIndex].unshift(lastElement);

                        break;
                }

                // Put together the new markup
                for (var i in jQuery.tinyContents[thisCarouselIndex]) {
                    // Begin the LI
                    if (!isNaN(i)) {
                        newMarkup += "<li style=\"position: absolute; left: " + jQuery.tinyPositions[thisCarouselIndex][i] + "\">";

                        // Throw the content in the LI
                        newMarkup += jQuery.tinyContents[thisCarouselIndex][i];

                        // Close the LI
                        newMarkup += "</li>";
                    }
                    else {
                        newMarkup = newMarkup;
                    }

                }

                // Drop in the new markup
                jQuery(this).parent("div.tinyBody").children("ul.tinyContents").html(newMarkup);
            });
        });
    }

    /*** End Tiny Carousel Behavior ***/

    /*** Begin General Tab Behavior ***/

    // Check if any tab collections exist
    if (jQuery("div.tabSet").length > 0) {
        // Cycle through each tab set collection
        jQuery("div.tabSet").each(function () {
            // Set the click event for this collection's tabs
            jQuery(this).children("div.tabs").children("div.tab").click(function () {
                // Only execute code if the tab being clicked is not the one in focus
                if (!jQuery(this).hasClass("on")) {
                    // Remove the on state from all tabs and highlight the current tab
                    jQuery(this).parent("div.tabs").children("div.tab").removeClass("on").end().end().addClass("on"); ;

                    // Focus the correct content area
                    jQuery(this).parent("div.tabs").parent("div.tabSet").children("div.tabContents").children("div.tabContent").removeClass("focused").parent("div.tabContents").children("div.tabContent").eq(jQuery(this).index()).addClass("focused");
                }
            });
        });
    }

    /*** End General Tab Behavior ***/

    /*** Begin Right Column Zip Code Search Function ***/

    jQuery("div#count_applet input.submit").click(function () {
        jQuery.ajax(
		{
		    type: "GET",
		    data:
			{
			    "zip": jQuery("input.zipcodesearch").val()
			},
		    dataType: "text",
		    url: "/Ingenix/Layouts/GetOrgCounts.aspx",
		    success: function (data, textStatus) {
		        // Reset the count to zero
		        jQuery("div.digit span").text("0");

		        // Get the count
		        var orgCount = new String(data);

		        // Split the count into an array
		        var orgCountArr = orgCount.split("");

		        // Reverse the array
		        orgCountArr = orgCountArr.reverse();

		        // Get the length of the available digits
		        var numDigits = jQuery("div.digit span").length - 1;

		        // Go through the array and populate the digits
		        for (var i in orgCountArr) {
		            // Populate the digit
		            jQuery("div.digit span").eq(numDigits).text(orgCountArr[i]);

		            // Decrement the digit number
		            numDigits--;
		        }
		    }
		});

        return false;
    });

    /*** End Right Column Zip Code Search Function ***/

    /*** Begin People Picker Behaviors ***/

    // Check if any people pickers exist on the page
    if (jQuery("div.peoplePicker").length > 0) {
        // Bind behaviors to each people picker
        jQuery("div.peoplePicker").each(function () {
            // Save a reference of this picker object
            var thisPicker = jQuery(this);

            // Start an interval for the people picker to cycle through entries
            var pickerInterval = setInterval(function () {
                // Get the current highlighted index
                var currentIndex = parseInt(thisPicker.children("div.bioTexts").children("div.bioLeft.focused").index());

                // Unhighlight the current slide
                thisPicker.children("div.bioTexts").children("div.bioLeft.focused").removeClass("focused");

                // Unhighlight the thumbnail
                thisPicker.children("div.bioRight").children("div.bioEntry").removeClass("focused");

                // Determine if this is the last slide or not
                if ((currentIndex + 1) < thisPicker.children("div.bioTexts").children("div.bioLeft").length) {
                    // Increment the next index
                    var nextSlide = currentIndex + 1;
                }
                else {
                    // Start over
                    var nextSlide = 0;
                }

                // Highlight the specified slide
                thisPicker.children("div.bioTexts").children("div.bioLeft").eq(nextSlide).addClass("focused").parent("div.bioTexts").parent("div.peoplePicker").children("div.bioRight").children("div.bioEntry").eq(nextSlide).addClass("focused");
            }, 5000);

            // Create an object for the hover states
            var hoverStates = [];

            // Populate the hover state array
            for (var i = 0; i < thisPicker.children("div.bioRight").children("div.bioEntry").length; i++) {
                // Add the hover state entry
                hoverStates.push(false);
            }

            // Hover event for images
            thisPicker.children("div.bioRight").children("div.bioEntry").mouseover(function () {
                // Save a reference of this hover object
                var thisHover = jQuery(this);

                // Set the hover state to true
                hoverStates[thisHover.index()] = true;

                // Hover latency...
                setTimeout(function () {
                    // Only hover if the cursor is still over the element
                    if (hoverStates[thisHover.index()] == true) {
                        // Clear picker interval
                        clearInterval(pickerInterval);

                        // Remove all focused states
                        thisPicker.children("div.bioTexts").children("div.bioLeft.focused").removeClass("focused").parent("div.bioTexts").parent("div.peoplePicker").children("div.bioRight").children("div.bioEntry.focused").removeClass("focused");

                        // Show the correct index
                        thisPicker.children("div.bioTexts").children("div.bioLeft").eq(thisHover.index()).addClass("focused").parent("div.bioTexts").parent("div.peoplePicker").children("div.bioRight").children("div.bioEntry").eq(thisHover.index()).addClass("focused");
                    }
                }, 1000);
            }).mouseout(function () {
                // Set the hover state to false
                hoverStates[jQuery(this).index()] = false;
            }).click(function () {
                // Set the hover state
                hoverStates[jQuery(this).index()] = true;

                // Clear picker interval
                clearInterval(pickerInterval);

                // Remove all focused states
                thisPicker.children("div.bioTexts").children("div.bioLeft.focused").removeClass("focused").parent("div.bioTexts").parent("div.peoplePicker").children("div.bioRight").children("div.bioEntry.focused").removeClass("focused");

                // Show the correct index
                thisPicker.children("div.bioTexts").children("div.bioLeft").eq(jQuery(this).index()).addClass("focused").parent("div.bioTexts").parent("div.peoplePicker").children("div.bioRight").children("div.bioEntry").eq(jQuery(this).index()).addClass("focused");
            });

            // Click event for previous button
            thisPicker.children("div.bioTexts").children("div:last").children("a#bioPrev").click(function () {
                // Clear the interval
                clearInterval(pickerInterval);

                // Determine the previous slide
                if (jQuery(this).parent("div").parent("div.bioTexts").children("div.bioLeft.focused").index() > 0) {
                    var previousSlide = jQuery(this).parent("div").parent("div.bioTexts").children("div.bioLeft.focused").index() - 1;
                }
                else {
                    var previousSlide = jQuery(this).parent("div").parent("div.bioTexts").children("div.bioLeft").length - 1;
                }

                // Unhighlight the slide
                jQuery(this).parent("div").parent("div.bioTexts").children("div.bioLeft.focused").removeClass("focused").parent("div.bioTexts").parent("div.peoplePicker").children("div.bioRight").children("div.bioEntry.focused").removeClass("focused");

                // Show the correct slide
                jQuery(this).parent("div").parent("div.bioTexts").children("div.bioLeft").eq(previousSlide).addClass("focused").parent("div.bioTexts").parent("div.peoplePicker").children("div.bioRight").children("div.bioEntry").eq(previousSlide).addClass("focused");
            });

            // Click event for next button
            thisPicker.children("div.bioTexts").children("div:last").children("a#bioNext").click(function () {
                // Clear the interval
                clearInterval(pickerInterval);

                // Determine the next slide
                if ((jQuery(this).parent("div").parent("div.bioTexts").children("div.bioLeft.focused").index() + 1) < jQuery(this).parent("div").parent("div.bioTexts").children("div.bioLeft").length) {
                    var nextSlide = jQuery(this).parent("div").parent("div.bioTexts").children("div.bioLeft.focused").index() + 1;
                }
                else {
                    var nextSlide = 0;
                }

                // Unhighlight the slide
                jQuery(this).parent("div").parent("div.bioTexts").children("div.bioLeft.focused").removeClass("focused").parent("div.bioTexts").parent("div.peoplePicker").children("div.bioRight").children("div.bioEntry.focused").removeClass("focused");

                // Show the correct slide
                jQuery(this).parent("div").parent("div.bioTexts").children("div.bioLeft").eq(nextSlide).addClass("focused").parent("div.bioTexts").parent("div.peoplePicker").children("div.bioRight").children("div.bioEntry").eq(nextSlide).addClass("focused");
            });
        });
    }

    /*** End People Picker Behaviors ***/

    /*** Begin Select Field Redirect Behavior ***/

    jQuery("select.redirectField").change(function () {
        // Redirect based on the value attribute
        location.href = jQuery(this).val();
    });

    /*** End Select Field Redirect Behavior ***/

    /*** Begin Client Login Page Behavior ***/

    // Login help display
    jQuery("a.loginHelp").one("click", function () {
        // Show the login help
        jQuery("p.loginHelp").show();
    });

    /*** End Client Login Page Behavior ***/

    /*** Begin Accordian Behavior ***/

    jQuery("div.accordianTitle").click(function () {
        // Determine if the accordian is open or not
        if (jQuery(this).children("div.accordianStatus").hasClass("expand")) {
            // Change the status icon's class
            jQuery(this).children("div.accordianStatus").removeClass("expand").addClass("collapse");

            // Expand the accordian contents
            jQuery(this).next("div.accordianContent").slideDown(125);
        }
        else if (jQuery(this).children("div.accordianStatus").hasClass("collapse")) {
            // Change the status icon's class
            jQuery(this).children("div.accordianStatus").removeClass("collapse").addClass("expand");

            // Collapse the accordian contents
            jQuery(this).next("div.accordianContent").slideUp(125);
        }
    });

    /*** End Accordian Behavior ***/

    /*** Begin Nav Accordian Behavior ***/

    jQuery("li.accordianItem a").click(function () {
        // Check if the link has an on class or not
        if (jQuery(this).hasClass("on")) {
            // Hide the items
            jQuery(this).removeClass("on").parent("li.accordianItem").removeClass("collapse").addClass("expand").children("div.accordianContent").slideUp(125);
        }
        else {
            // Show the items
            jQuery(this).addClass("on").parent("li.accordianItem").removeClass("expand").addClass("collapse").children("div.accordianContent").slideDown(125);
        }
    });

    /*** End Nav Accordian Behavior ***/

    /*** Begin Accordian Pagination Behaviors ***/

    jQuery("input.firstPage").live("mouseover", function () {
        // Hover on
        jQuery(this).addClass("firstPageOn");
    }).live("mouseout", function () {
        // Hover out
        jQuery(this).removeClass("firstPageOn");
    });

    jQuery("input.prevPage").live("mouseover", function () {
        // Hover on
        jQuery(this).addClass("prevPageOn");
    }).live("mouseout", function () {
        // Hover out
        jQuery(this).removeClass("prevPageOn");
    });

    jQuery("input.nextPage").live("mouseover", function () {
        // Hover on
        jQuery(this).addClass("nextPageOn");
    }).live("mouseout", function () {
        // Hover out
        jQuery(this).removeClass("nextPageOn");
    });

    jQuery("input.lastPage").live("mouseover", function () {
        // Hover on
        jQuery(this).addClass("lastPageOn");
    }).live("mouseout", function () {
        // Hover out
        jQuery(this).removeClass("lastPageOn");
    });

    jQuery("a.page").live("mouseover", function () {
        // Make sure this page isn't highlighted
        if (!jQuery(this).hasClass("pageOnPerm")) {
            // Hover on
            jQuery(this).addClass("pageOn");
        }
    }).live("mouseout", function () {
        if (!jQuery(this).hasClass("pageOnPerm")) {
            // Hover out
            jQuery(this).removeClass("pageOn");
        }
    });

    jQuery("span.resultsPerPage").live("click", function () {
        jQuery(this).next("div.pagesPer").show();
    });

    jQuery("div.pagesPer div").live("mouseover", function () {
        // Add hover state
        jQuery(this).addClass("hover");
    }).live("mouseout", function () {
        // Remove hover state
        jQuery(this).removeClass("hover");
    });

    jQuery("div.pagesPer div").live("click", function () {
        // Set the results per pages label
        jQuery(this).parent("div.pagesPer").prev("span.resultsPerPage").text(jQuery(this).text());

        // Hide the drop down
        jQuery(this).parent("div.pagesPer").hide();
    });

    /*** End Accordian Pagination Behaviors ***/

    /*** Begin Transparency Behaviors ***/

    // View comments
    jQuery("a.viewComments").click(function () {
        // Show comments div
        jQuery(this).parent("p").next("div.comments").show();
    });

    /*** End Transparency Behaviors ***/

    /*** Begin Contact Modal Behavior ***/

    jQuery("div.contact ul li a").colorbox(
	{
	    width: "700px",
	    height: "225px",
	    iframe: true,
	    speed: 250,
	    opacity: 0.5,
	    href: "/Ingenix/Layouts/ContactUsModal.aspx?context=modal",
	    onComplete: function () {
	        // Tweak styles on load
	        jQuery("div#cboxTopCenter").css("width", (parseInt(jQuery("div#cboxTopCenter").css("width")) - 4) + "px");
	        jQuery("div#cboxBottomCenter").css("width", (parseInt(jQuery("div#cboxBottomCenter").css("width")) - 4) + "px");
	        jQuery("div#cboxContent").css("width", (parseInt(jQuery("div#cboxContent").css("width")) - 4) + "px");

	        // Append Modal Title
	        if (jQuery("div#cboxTopCenter").children("span.cboxTitle").length == 0) {
	            jQuery("div#cboxTopCenter").prepend("<span class=\"cboxTitle\">Contact Us</span>");
	        }

	        // Append Modal Title
	        if (jQuery("div#cboxTopCenter").children("img.cboxCloseButton").length == 0) {
	            jQuery("div#cboxTopCenter").prepend("<img class=\"cboxCloseButton\" src=\"/~/media/Ingenix/Page%20Elements/Modal/modal_close.ashx\" width=\"13\" height=\"11\" alt=\"Close\" title=\"Close\" />");
	        }
	    }
	});

    // Modal close behavior
    jQuery("img.cboxCloseButton").live("click", function () {
        // Close the modal
        jQuery.colorbox.close();
    });

    // Modal behavior
    jQuery("img.cboxCloseButton").live("mouseover", function () {
        // Add hover state
        jQuery(this).attr("src", jQuery(this).attr("src").replace("modal_close.ashx", "modal_close_on.ashx"));
    }).live("mouseout", function () {
        // Remove hover state
        jQuery(this).attr("src", jQuery(this).attr("src").replace("modal_close_on.ashx", "modal_close.ashx"));
    });

    /*** End Contact Modal Behavior ***/

    /*** Begin IE6 Hacks ***/

    // Detect IE6 or IE7
    if (jQuery.browser.msie == true && (jQuery.browser.version == "6.0" || jQuery.browser.version == "7.0")) {
        jQuery("div.accordianPages").each(function () {
            if (jQuery.browser.version == "6.0") {
                if (jQuery(this).children("span").children("a.page").length > 2) {
                    jQuery(this).children("span").children("a.page").eq(0).css({ position: "relative", top: "15px" });
                }
            }
            else {
                jQuery(this).children("span").children("a.page").eq(0).css({ position: "relative", top: "15px" });
            }
        });
    }

    /*** End IE6 Hacks ***/
});

/*** Begin Utility Functions ***/

function clearText(textBox, defaultText)
{
	if(textBox.value == defaultText)
	{
		textBox.value = "";
	}
}

function clickRecall(thisField, defaultText)
{
	if(thisField.value == "")
	{
		thisField.value = defaultText;
	}
}

function BindEvents()
{
	jQuery(document).ready(function()
	{
		/*** Begin General Tab Behavior ***/

		// Check if any tab collections exist
		if(jQuery("div.tabSet").length > 0)
		{
			// Cycle through each tab set collection
			jQuery("div.tabSet").each(function()
			{
				// Set the click event for this collection's tabs
				jQuery(this).children("div.tabs").children("div.tab").click(function()
				{
					// Only execute code if the tab being clicked is not the one in focus
					if(!jQuery(this).hasClass("on"))
					{
						// Remove the on state from all tabs and highlight the current tab
						jQuery(this).parent("div.tabs").children("div.tab").removeClass("on").end().end().addClass("on");

						// Focus the correct content area
						jQuery(this).parent("div.tabs").parent("div.tabSet").children("div.tabContents").children("div.tabContent").removeClass("focused").parent("div.tabContents").children("div.tabContent").eq(jQuery(this).index()).addClass("focused");
					}
				});
			});
		}

		/*** End General Tab Behavior ***/
	});
}

/*** End Utility Functions ***/
