﻿jQuery(document).ready(function () {
    // Carousel Interval Speed
    var carouselSpeed = 8000;

    /*** Begin image preloading code ***/

    // AJAX loading image
    var loadingImage = new Image();
    loadingImage.src = "/~/media/Images/Loading/loading.ashx";

    // Modal loading image
    var modalLoadingImage = new Image();
    modalLoadingImage.src = "/~/media/Images/Loading/modal_loading.ashx";

    // Modal close icon
    var modalClose = new Image();
    modalClose.src = "/~/media/Images/Buttons/close.ashx";

    /*** End image preloading code ***/

    /*** Begin IE Specific Hooks ***/

    // If we're in IE6...
    if (jQuery.browser.msie && jQuery.browser.version == "6.0") {
        // ...turn off all animations
        jQuery.fx.off = true;

        // Apply BGIFrame to subnav elements
        jQuery("ul.subNav").bgiframe();
    }

    // If we're in IE6 or IE7...
    if (jQuery.browser.msie && (jQuery.browser.version == "6.0" || jQuery.browser.version == "7.0" || jQuery.browser.version == "8.0")) {
        // Add CSS hooks for last tab styling
        jQuery("div.tabContents div.levelTwo div.tabs").children("div.tab:last-child").css({ borderRight: "0px" });
        jQuery("div.tabContents div.levelTwo div.tabContents div.levelThree div.tabs ").children("div.tab:last-child").css({ borderBottom: "0px" });
    }

    /*** End IE Specific Hooks ***/

    /*** Begin Search Overtype Behavior ***/

    // Search overtype behavior
    jQuery("input.searchInput").one("focus", function () {
        if (jQuery(this).val() == "Enter Search Terms...") {
            jQuery(this).removeClass("overType").val("");
        }
    });

    /*** End Search Overtype Behavior ***/

    /*** Begin Home Page Flyout Behavior ***/

    // Set the offsets
    var storyIndexOffset = 111;

    // Cycle through the image gallery list elements
    jQuery("ul.imageGallery").children("li.image").each(function () {
        // Offset this image gallery list element and set its background image
        jQuery(this).css({ left: (jQuery(this).index() * storyIndexOffset) + "px" });
    });

    // Cycle through the flyout DIVs
    jQuery("div.widget").each(function () {
        // Offset the flyout
        jQuery(this).css({ left: ((jQuery(this).index() * storyIndexOffset) - 286) + "px" });
    });

    // If a user mouses over the widget, hide it.
    jQuery("div.widget").mouseover(function () {
        jQuery(this).hide();
    });

    // Flyout behavior
    jQuery("li.image").mouseenter(function () {
        // Show flyout
        jQuery("div.widget").eq(jQuery(this).index()).show();
    }).mouseleave(function () {
        // Show flyout
        jQuery("div.widget").eq(jQuery(this).index()).hide();
    });

    var domain = document.domain;
    var url = "http://" + domain + "/Rockwell/Layouts/HomepageNewsJSON.aspx";

    // Start news behavior if the target DIV exists
    if (jQuery("div.headlines").length > 0) {
        // Get the news cycle data
        jQuery.ajax(
		{
		    type: "GET",
		    url: url,
		    dataType: "json",
		    beforeSend: function (xhr) {
		        jQuery("div.headlines").html("<span>Loading...</span>");
		    },
		    success: function (data, textStatus) {
		        // See if we need to limit the length of the news headline
		        if (data.news[0].t.length >= 80) {
		            var newsTitle = data.news[0].t.substring(0, 77) + "...";
		        }
		        else {
		            var newsTitle = data.news[0].t;
		        }

		        // Set the first entry in the array to the item:
		        jQuery("div.headlines").html("<span>The News:&nbsp;" + data.news[0].m + "." + data.news[0].d + "." + data.news[0].y + "&nbsp;<a href=\"" + data.news[0].ei + "\">" + newsTitle + "</a></span>");

		        // Instantiate counter variable to the second item in the newsFeed array
		        newsIterator = 1;

		        // News Loop Limit
		        newsLoopLimit = 4;

		        // Current Loop
		        currentLoop = 0;

		        // News cycle behavior
		        var newsInterval = setInterval(function () {
		            // Check if we've reached our loop limit
		            if (currentLoop < newsLoopLimit) {
		                // See if we need to limit the length of the news headline
		                if (data.news[newsIterator].t.length >= 80) {
		                    var newsEntryTitle = data.news[newsIterator].t.substring(0, 77) + "...";
		                }
		                else {
		                    var newsEntryTitle = data.news[newsIterator].t;
		                }

		                // Get the string together
		                var newsString = "<span>The News:&nbsp;" + data.news[newsIterator].m + "." + data.news[newsIterator].d + "." + data.news[newsIterator].y + "&nbsp;<a href=\"" + data.news[newsIterator].ei + "\">" + newsEntryTitle + "</a></span>";

		                // Populate the news container
		                jQuery("div.headlines").html(newsString);

		                // Figure out how newsIterator sequence
		                if (newsIterator < (data.news.length - 1)) {
		                    // Increment the news iterator
		                    newsIterator++;
		                }
		                else {
		                    // Reset the news iterator
		                    newsIterator = 0;

		                    // Increment the news limit loop
		                    currentLoop++;
		                }
		            }
		            else {
		                // Stop the loop
		                clearInterval(newsInterval);
		            }
		        }, 5000);
		    }
		});
    }


    /*** End Home Page Flyout Behavior ***/

    /*** Begin Navigation Hover Behaviors ***/

    // Set the nav hover state array
    navDelayArr = new Array();

    // Use a for loop to populate the navDelarArr's navigation states
    for (i = 0; i < jQuery("li.navItem").length; i++) {
        // Add the value to the navigation delay array
        navDelayArr.push(false);
    }

    // Nav hover events
    jQuery("li.navItem").mouseenter(function () {
        if (!jQuery(this).hasClass("permOn") && !jQuery(this).hasClass("home") && !jQuery(this).hasClass("contact") && !jQuery(this).hasClass("login")) {
            // Set the delay array entry
            navDelayArr[jQuery(this).index()] = true;

            // Delay the rollover
            jQuery(this).delay(200).queue(function () {
                // Only show popup if the user hasn't moused off of the element
                if (navDelayArr[jQuery(this).index()] == true) {
                    // Add hover state
                    jQuery(this).append("<div class=\"whiteStrip\"></div>").addClass("on").children("div.navItemLabel").addClass("onLabel").nextAll("ul.subNav").show();
                }

                // Remove this action from the queue.
                jQuery(this).dequeue();
            });
        }
        else if (!jQuery(this).hasClass("homePermOn")) {
            // Set the delay array entry
            navDelayArr[jQuery(this).index()] = true;

            // Delay the rollover
            jQuery(this).delay(200).queue(function () {
                // Only show popup if the user hasn't moused off of the element
                if (navDelayArr[jQuery(this).index()] == true) {
                    // Add hover state
                    jQuery(this).append("<div class=\"whiteStrip\"></div>").children("ul.subNav").show();
                }

                // Remove this action from the queue.
                jQuery(this).dequeue();
            });
        }
    }).mouseleave(function () {
        if (!jQuery(this).hasClass("permOn") && !jQuery(this).hasClass("home") && !jQuery(this).hasClass("contact") && !jQuery(this).hasClass("login")) {
            // Set the delay array entry
            navDelayArr[jQuery(this).index()] = false;

            if (jQuery(this).hasClass("on")) {
                // Delay the rollout
                jQuery(this).delay(200).queue(function () {
                    // Remove hover state
                    jQuery(this).removeClass("on").children("div.navItemLabel").removeClass("onLabel").nextAll("ul.subNav").hide().next("div.whiteStrip").remove();

                    // Remove this action from the queue.
                    jQuery(this).dequeue();
                });
            }
        }
        else {
            // Set the delay array entry
            navDelayArr[jQuery(this).index()] = false;

            // Delay the rollout
            jQuery(this).delay(200).queue(function () {
                // Remove hover state
                jQuery(this).children("div.navItemLabel").nextAll("ul.subNav").hide().next("div.whiteStrip").remove();

                // Remove this action from the queue.
                jQuery(this).dequeue();
            });
        }
    });

    // Mega Rollover Close Button Behavior
    jQuery("img.closeRollover").click(function () {
        // Remove hover state
        if (!jQuery(this).parent("div.close").parent("li").parent("ul.subNav").parent("li.navItem").hasClass("permOn")) {
            // Hide the menu
            jQuery(this).parent("div.close").parent("li").parent("ul.subNav").hide().next("div.whiteStrip").remove().end().prev("div.navItemLabel").removeClass("onLabel").parent("li.navItem").removeClass("on");
        }
        else {
            // Hide the menu, but leave the nav item's on state intact
            jQuery(this).parent("div.close").parent("li").parent("ul.subNav").hide().next("div.whiteStrip");
        }
    });

    /*** End Navigation Hover Behaviors ***/

    /*** Begin Carousel Behavior ***/

    if (jQuery("ul.carousel").length > 0) {
        // Set the slide variables
        var currentSlide = 0;
        var numSlides = jQuery("ul.carousel").children("li").length - 1;

        // Show the first slide
        jQuery("ul.carousel").children("li").eq(0).show();

        // Set the interval for the carousel fades if there is more than one slide
        if (jQuery("ul.carousel").children("li").length > 1) {
            var carouselInterval = setInterval(function () {
                // Fade out the old slide
                jQuery("ul.carousel").children("li").eq(currentSlide).fadeOut(500);

                // Figure out how to increment the slide index
                if (currentSlide == numSlides) {
                    // Reset currentSlide back to zero
                    currentSlide = 0;
                }
                else {
                    // Increment to the next slide
                    currentSlide++;
                }

                // Fade in the new slide
                jQuery("ul.carousel").children("li").eq(currentSlide).fadeIn(500);
            }, carouselSpeed);
        }
    }

    /*** End Carousel Behavior ***/

    /*** Begin Expandable Copy Behavior ***/

    // Set up the copy array
    var copyArray = [];

    // Iterate through all overview copy elements
    jQuery("p.overviewCopy").each(function () {
        // Check the length of the text
        if (jQuery(this).text().length > 1000) {
            // Save the full copy to a variable
            copyArray[jQuery(this).eq()] = [jQuery(this).html() + " [<a href=\"javascript:void(0);\" class=\"contractCopy\">Less</a>]", jQuery(this).html().substr(0, 750) + "... [<a href=\"javascript:void(0);\" class=\"expandCopy\">More</a>]"];

            // Replace the paragraph content with the truncated copy
            jQuery(this).html(copyArray[jQuery(this).eq()][1]);
        }
    });

    // Set a live event for this paragraph's expand and contract functions
    jQuery("a.expandCopy").live("click", function () {
        // Show the full copy
        jQuery(this).parent("p.overviewCopy").html(copyArray[jQuery(this).parent("p.overviewCopy").eq()][0]);
    });

    jQuery("a.contractCopy").live("click", function () {
        // Hide the full copy
        jQuery(this).parent("p.overviewCopy").html(copyArray[jQuery(this).parent("p.overviewCopy").eq()][1]);
    });

    /*** End Expandable Copy Behavior ***/

    /*** Begin Tab Behavior ***/

    // Show the first tab contents
    jQuery("div.tabSet").each(function () {
        jQuery(this).children("div.tabContents").eq(0).show();
    });

    // Tab behavior
    jQuery("div.tab").live("click", function () {
        if (!jQuery(this).parent("div.tabs").parent("div.tabSet").hasClass("disabledTabs")) {
            jQuery(this).parent("div.tabs").children("div.tab").removeClass("on");
            jQuery(this).addClass("on").children("span").eq(1).css({ textDecoration: "none" });
            jQuery(this).parent("div.tabs").parent("div.tabSet").children("div.tabContents").hide();
            jQuery(this).parent("div.tabs").parent("div.tabSet").children("div.tabContents").eq(jQuery(this).index()).show();
        }
    });

    // Sub tab hover state behavior
    jQuery("div.levelTwo").children("div.tabs").children("div.tab").mouseover(function () {
        // If this tab is not active...
        if (!jQuery(this).hasClass("on")) {
            jQuery(this).children("span").eq(1).css({ textDecoration: "underline" });
        }
    }).mouseout(function () {
        // If this tab is not active...
        if (!jQuery(this).hasClass("on")) {
            // Remove the underline
            jQuery(this).children("span").eq(1).css({ textDecoration: "none" });
        }
    });

    /*** End Tab Behavior ***/

    /*** Begin Image Switcher Behavior ***/

    jQuery("div.thumbnail1 a, div.thumbnail2 a, div.thumbnail3 a").click(function () {
        // Capture the ID
        var imageID = jQuery(this).attr("rel");
        var domain = document.domain;
        var url = "http://" + domain + "/Rockwell/Layouts/ProductSwitcher.aspx";

        // Fire the AJAX request
        jQuery.ajax(
		{
		    type: "GET",
		    url: url,
		    data:
			{
			    id: imageID
			},
		    dataType: "json",
		    beforeSend: function (xhr) {
		        // Change to a loading graphic
		        jQuery("div.mainImage").children("a.modal").children("img").attr({ src: loadingImage.src, width: "32", height: "32" }).addClass("loading");
		    },
		    success: function (data, textStatus) {
		        // Preload the requested image into an image object instance
		        var productImage = new Image();
		        productImage.src = data.imageURL;
		        productImage.alt = data.imageAltText;

		        // Change the image and modal rel attributes
		        jQuery("div.mainImage").children("a.modal").attr({ rel: imageID + "|image" }).children("img").attr({ src: productImage.src, alt: productImage.alt, title: productImage.alt, width: "345", height: "182" }).removeClass("loading");

		        // Change the rel attributes of the zoom control link
		        jQuery("div.zoomControl").attr({ rel: imageID + "|image" });
		    }
		});
    });

    /*** End Image Switcher Behavior ***/

    /*** Begin Modal Binding Behavior ***/

    // HTML modal
    jQuery("a.htmlModal").colorbox(
	{
	    width: "640px",
	    height: "520px",
	    iframe: true,
	    speed: 250,
	    close: false,
	    onComplete: function () {
	        // Populate the modal's close icon
	        jQuery("div#cboxTopRight").html("<div class=\"closeIcon\"><img src=\"" + modalClose.src + "\" width=\"13\" height=\"13\" alt=\"Close\" title=\"Close\" /></div>");
			
			// Check how many iframes there are
			if(jQuery("div#cboxLoadedContent").find("iframe").length > 1)
			{
				jQuery("div#cboxLoadedContent").find("iframe").not(":first").remove();
			}
	    }
	});

    // Image/media modal
    jQuery(".modal").colorbox(
	{
	    width: "200px",
	    height: "50px",
	    iframe: false,
	    photo: false,
	    href: "/modalcontent.html",
	    rel: "nofollow",
	    speed: 250,
	    scrolling: false,
	    close: false,
	    onComplete: function () {
	        // Remove scrollbars
	        jQuery("div#cboxLoadedContent").css({ overflow: "hidden" });

	        // Get the media parameters
	        var mediaID = jQuery(this).attr("rel").split("|")[0];
	        var mediaType = jQuery(this).attr("rel").split("|")[1];

	        var domain = document.domain;
	        var url = "http://" + domain + "/Rockwell/Layouts/MediaModal.aspx";

	        // Fire the AJAX call
	        jQuery.ajax(
			{
			    type: "GET",
			    url: url,
			    data:
				{
				    id: mediaID,
				    type: mediaType
				},
			    beforeSend: function (xhr) {
			        // Generate the loading graphic markup
			        var markup = "<img src=\"" + modalLoadingImage.src + "\" alt=\"Loading...\" title=\"Loading...\" />";

			        // Populate the modal's close icon
			        jQuery("div#cboxTopRight").html("<div class=\"closeIcon\"><img src=\"" + modalClose.src + "\" width=\"13\" height=\"13\" alt=\"Close\" title=\"Close\" /></div>");

			        // Populate the modal with the loading graphic
			        jQuery("div.mediaContainer").html(markup);
			    },
			    error: function (xhr, textStatus, errorThrown) {
			        // Generate the error markup
			        var markup = "<p>The requested resource was not found.</p>";

			        // Populate the modal with the error message
			        jQuery("div.mediaContainer").html(markup);

			        // Resize the box
			        jQuery.fn.colorbox.resize({ width: "400px", height: "100px" });
			    },
			    dataType: "json",
			    success: function (data, textStatus) {
			        // Establish the markup string variable
			        var markup = new String();

			        // Determine how to build the markup string
			        switch (mediaType) {
			            // Video content
			            case "video":
			                // Build the markup string
			                markup += "<object width=\"640\" height=\"505\">";
			                markup += "<param name=\"movie\" value=\"" + data.url + "\"></param>";
			                markup += "<param name=\"allowFullScreen\" value=\"true\"></param>";
			                markup += "<param name=\"allowscriptaccess\" value=\"always\"></param>";
			                markup += "<parem name=\"wmode\" value=\"transparent\"></param>";
			                markup += "<embed src=\"" + data.url + "\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"640\" height=\"505\" wmode=\"transparent\"></embed>";
			                markup += "</object>";

			                // Populate the modal
			                jQuery("div.mediaContainer").html(markup);

			                // Resize the modal
			                jQuery.fn.colorbox.resize({ width: "690px", height: "585px" });
			                break;

			            // Image content
			            case "image":
			                // Build the markup string
			                markup += "<img src=\"" + data.url + "\" class=\"modalImage\" />";

			                // Populate the modal
			                jQuery("#colorbox div.mediaContainer").html(markup);

			                // Resize the modal
			                jQuery("div.mediaContainer").find("img.modalImage").load(function () {
			                    jQuery.fn.colorbox.resize({ width: parseInt(jQuery("img.modalImage").outerWidth() + 50) + "px" });
			                });
			                break;
			        }
			    }
			});
	    }
	});

    // Bind a live click event to the modal close link...
    jQuery("div.closeIcon").live("click", function () {
        jQuery.fn.colorbox.close();
    });

    /*** End Modal Binding Behavior ***/

    /*** Begin Calendar Page Behavior ***/

    // Calendar plugin binding
    if (jQuery("div#calendar").length > 0) {
        jQuery("div#calendar").rockwellCalendar({ month: new Date().getMonth(), year: new Date().getFullYear() });
    }

    /*** End Calendar Page Behavior ***/

    /*** Begin Subscribe Page Behaviors ***/

    // Subscription agreement checkbox behavior
    jQuery("input.flexCheck").change(function () {
        if (jQuery(this).attr("checked") == true) {
            jQuery(this).parent("p").parent("div.flexColumn").find("input.submit").removeClass("disabled").removeAttr("disabled");
        }
        else {
            jQuery(this).parent("p").parent("div.flexColumn").find("input.submit").addClass("disabled").attr("disabled", "disabled");
        }
    });

    // Select All/None Link Behavior
    jQuery("a.selectAll, a.selectNone").click(function () {
        // Do a check on the clicked link's class
        if (jQuery(this).hasClass("selectAll")) {
            // Select all checked boxes
            jQuery(this).parent("p").find("span.subscribeCheck").find("input").attr("checked", true);
        }
        else if (jQuery(this).hasClass("selectNone")) {
            // Deselect all checked boxes
            jQuery(this).parent("p").find("span.subscribeCheck").find("input").removeAttr("checked");
        }
    });

    /*** End Subscribe Page Behaviors ***/

    /*** Begin Contact List Page Behaviors ***/

    // Form clearing link
    jQuery("span.clear a").click(function () {
        // Clear the form field
        jQuery("input.refineSearchField").val("");
    });

    /*** End Contact List Page Behaviors ***/

    /*** Begin Worldwide Page Behaviors ***/

    // Only execute the following behavior if the bottom news elements exist
    if (jQuery("div.bottomNews").length > 0) {
        // Hide all bottom news elements except for the first one
        jQuery("div.bottomNews div.newsItem").hide().eq(0).show();

        // Bind behavior for news item paging
        jQuery("div.bottomNews div.headline div.storyNav span a").click(function () {
            // Check if this is a new or previous button
            if (jQuery(this).hasClass("newsNext")) {
                // Figure out the next index
                var targetIndex = jQuery(this).parents("div.newsItem").index() + 1;
            }
            else if (jQuery(this).hasClass("newsPrev")) {
                // Figure out the previous index
                var targetIndex = jQuery(this).parents("div.newsItem").index() - 1;
            }

            // Hide all news items except for the targeted one
            jQuery("div.bottomNews div.newsItem").hide().eq(targetIndex).show();
        });
    }

    /*** End Worldwide Page Behaviors ***/
});

/*** Begin JavaScript Utility Functions ***/

function in_array(needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    }
    else {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    }

    return false;
}

/*** End JavaScript Utility Functions ***/
