﻿$(document).ready(function () {
    // Fix the sub menu rounding issue
    $(".submenurounding").each(function () {
        var rounding = $(this);

        rounding.css("width", rounding.parent("ul").width());
        rounding.children(".middle").css("width", rounding.width() - 10);
    });

    // Remove focus on links
    $("#Content.frontpage p a").blur().click(function () { $(this).blur(); });

    // Translate TM, C and R to the proper symbols in the pipeline module
    $("table.pipeline", "#Content").each(function () {
        var pipeline = $(this);

        pipeline.find("tr.productline > td").each(function () {
            var td = $(this);
            var text = td.html();

            text = text.replace("(TM)", "<sup>&trade;</sup>");
            text = text.replace("(C)", "<sup>&#169;</sup>");
            text = text.replace("(R)", "<sup>&#174;</sup>");

            td.html(text);
        });
    });

    // Add rounded borders to pipeline tables
    $('table.pipeline').each(function (i, item) {
        var table = $(this)
        table.children('tbody').children('tr.header').children('td').first().addClass('tleft');
        table.children('tbody').children('tr.header').children('td').last().addClass('tright');
        table.children('tbody').children('tr').last().children('td').first().addClass('bleft');
        table.children('tbody').children('tr').last().children('td').last().addClass('bright');
    });

    // Setup search
    $(".searcharrow", "#Header").each(function () {

        var search = $(this);
        var searchField = search.prev(".searchinput");
        var searchPage = "/search.aspx?q={0}";
        var searchValue;

        search.click(function () {
            searchValue = $.trim(searchField.val());
            if (searchValue.length > 0 && !searchField.hasClass("watermark"))
                window.location = searchPage.replace("{0}", searchValue);
        });

        searchField.keypress(function (event) {
            if (event.keyCode == "13")
                return false;
            return true;
        });

        searchField.keyup(function (event) {            
            searchValue = $.trim($(this).val());                        
            if (event.keyCode == "13" && searchValue.length > 0 && !searchField.hasClass("watermark")) {
                event.preventDefault();
                window.location = searchPage.replace("{0}", searchValue);
            }
        });
    });

    SetupWatermarks();

    // Bounce
    $("#Content.frontpage strong, #Content.frontpage span").each(function () {
        var strong = $(this);

        var random = Math.floor(Math.random() * 5000);
        setTimeout(function () { Off(strong); }, random); // Start the effects at a random time
    });

    // Setup flowplayer
    // First select all a tags that are linking to a video format compatible with flowplayer.
    $("a[href$='.flv'], a[href$='.mov']").each(function () {
        var video = $(this);

        // Add the "video" class to make the video link a block element. 
        // Also applies default width and height to prevent IE7 from tearing the page while the video loads.
        video.addClass("video");

        var playerWidth;
        var playerHeight;
        var playlist = [];
        var metaData;

        // If the video link contains an image, we should use that image as a splah image
        // and use the size of the image to calculate the size of the player.
        var splash = video.children("img:first");
        if (splash.length === 1) {
            playlist.push({ url: splash.attr("src") });

            playerWidth = splash.width();
            playerHeight = splash.height();
        }
        else {
            // If the video link has a title tag with proper with and height, we use those dimensions to calculate the size of the player.
            var title = $.trim(video.attr("title"));
            if (title.length > 0) {
                var dimensions = title.split("x"); // Split the title based on the rule: "widthxheight (450x230)".
                if (dimensions.length === 2) {
                    playerWidth = parseInt(dimensions[0], 10);
                    playerHeight = parseInt(dimensions[1], 10);
                }
            }
            else {
                // If there is neither a title tag or an image present, use the video meta data for calculating the player size.
                metaData = function (clip) {
                    playerWidth = clip.metaData.width;
                    playerHeight = clip.metaData.height;
                };
            }
        }

        // The combination of autoPlay and autoBuffering will enable the first frame of the video to be used as a splah image if there is no real splah image defined.
        playlist.push({ url: video.attr("href"), autoPlay: false, autoBuffering: false, onMetaData: metaData });
        playlist.push({ url: splash.attr("src") });

        // The max size of the player will always be limited to the width of the content tag it is contained within.                
        var contentWidth = video.closest(".sidebar, .content, #Content").width();
        if (playerWidth > contentWidth) {
            // Calculate a new proportional height for the video.
            var ratio = playerWidth / playerHeight;
            playerWidth = contentWidth;
            playerHeight = playerWidth / ratio;
        }

        video.css({ width: playerWidth, height: playerHeight });

        // Remove any child elements, to prevent the player from failing to load.
        video.text("");

        // Initiate the player with the created playlist.
        video.flowplayer("/scripts/flowplayer/flowplayer-3.2.5.swf", {
            playlist: playlist,
            plugins: {
                controls: {
                    // Buttons
                    all: false, scrubber: true, volume: true, mute: true, fullscreen: true,

                    // Style
                    bottom: 5, backgroundColor: 'rgba(0, 40, 87, 0.7)',
                    backgroundGradient: [0.0], borderRadius: 30, progressColor: "#DC5034", bufferColor: "#DC5034",
                    volumeSliderColor: "#DC5034", volumeColor: "#DC5034"
                }
            },
            onFullscreen: function () {
                this.getControls().setWidgets({ play: true, time: true });
            },
            onFullscreenExit: function () {
                this.getControls().setWidgets({ play: false, time: false });
            }
        });
    });
});

function On(elem) {
    elem.fadeTo(2000, 1, function () { Off(elem); });
}
function Off(elem) {
    elem.fadeTo(2000, 0.4, function () { On(elem); });
}

function SetupWatermarks() {
    $(".watermark").each(function () {
        var field = $(this);
        var orgValue = field.attr("title");
        var isPassword = field.hasClass("password");

        if (field.val() === "" || field.val() === orgValue) {
            field.val(orgValue);
        } else {
            if (isPassword) {
                var passwordField = GetPasswordInputField(field, true);
                SwitchInputFields(field, passwordField);
            } else {

                field.removeClass("watermark");
            }
        }

        // To support watermark text in input elements on the password type we need to switch between input elements on focus and blur if the field is marked as a password field
        field.focus(function () {
            if (isPassword) {
                var passwordField = GetPasswordInputField(field, false);
                SwitchInputFields(field, passwordField);
                passwordField.focus();
            } else {
                if (field.hasClass("watermark")) {
                    field.removeClass("watermark");
                    if (field.val() == orgValue) {
                        field.val("");
                    }
                }
            }
        });

        if (!isPassword) {
            field.blur(function () {
                var value = $.trim(field.val());
                if (value === "") {
                    field.addClass("watermark").val(orgValue);
                }
            });
        }
    });
}

// Due to an apparent security issue in IE, we can't clone an input element and change its type from text to password and visa versa
// Instead we need to create a brand new element and set all the attributes by hand.
function GetPasswordInputField(orgField, keepOrgValue) {
    var passwordField = orgField.data("passwordField");
    if (passwordField === undefined) {
        passwordField = $("<input type='password' />");

        passwordField.attr("id", orgField.attr("id"));
        passwordField.attr("class", orgField.attr("class"));
        passwordField.attr("title", orgField.attr("title"));
        passwordField.attr("tabindex", orgField.attr("tabindex"));
        passwordField.attr("name", orgField.attr("name"));

        if (keepOrgValue)
            passwordField.val(orgField.val());

        // Bind the blur event for the password field
        passwordField.blur(function () {
            var value = $.trim(passwordField.val());
            if (value === "") {
                var orgField = passwordField.data("orgField");
                SwitchInputFields(passwordField, orgField);
                orgField.val(orgField.attr("title"));
            }
        });

        // Keep references to fields for easier switching between them
        passwordField.data("orgField", orgField);
        orgField.data("passwordField", passwordField);
    }
    return passwordField;
}

function SwitchInputFields(firstField, secondField) {
    firstField.after(secondField);
    firstField.detach();
}
